SlideShare ist ein Scribd-Unternehmen logo
1 von 63
Downloaden Sie, um offline zu lesen
Page 1
ABCs of Programming Handbook
Ashley Menhennett
Handbook of programming terms.
Learn the ABC’s of coding with 26
terms and numerous code examples.
The
ABC’s of
Programming
The
ABC’s of
Programming
A - Array
LearnToProgram.tv, Incorporated
27 Hartford Turnpike Suite 206
Vernon, CT 06066
contact@learntoprogram.tv
(860) 840-7090
©2014 by LearnToProgram.tv, Incorporated
All rights reserved. No part of this document may be reproduced or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior
written permission of LearnToProgram.tv, Incorporated.
Limit of Liability/Disclaimer of Warranty:  While the publisher and author have used their best
efforts in preparing this book, they make no representations or warranties with respect to the
accuracy or completeness of the contents of this book and specifically disclaim any implied
warranties of merchantability or fitness for a particular purpose.  No warranty may be created
or extended by sales representatives or written sales materials.  The advice and strategies
contained herein may not be suitable for your situation.  You should consult with a professional
where appropriate.  By following the instructions contained herein, the reader willingly assumes
all risks in connection with such instructions.  Neither the publisher nor author shall be liable
for any loss of profit or any other commercial damages, including but not limited to special,
incidental, consequential, exemplary, or other damages resulting in whole or part, from the
readers’ use of, or reliance upon, this material. 
Mark Lassoff, Publisher
Kevin Hernandez, VP/ Production
Ashley Menhennett, Author
Alison Downs, Copy Editor
Alexandria O’Brien, Book Layout
Page 3
ABCs of Programming Handbook
About the Author
Ashley Menhennett is a 24-year-old programmer from Australia. Ashley also
enjoys sharing his knowledge through teaching web development and
programming.
A - Array
Courses Available from LearnToProgram, Inc.
HTML and CSS for Beginners (with HTML5)
Javascript for Beginners
Java for Beginners
jQuery for Beginners
iOS Development Code Camp
Become a Certified Web Developer
PHP & MySQL for Beginners
iOS 6/7 Development for Beginners
Objective C for Beginners
C Programming for Beginners
Android Development for Beginners
Creating an MP3 Player with Adobe Flash
AJAX Development
Python for Beginners
CSS Development (with CSS3)
HTML5 Mobile App Development with PhoneGap
3D Fundamentals with iOS
Photoshop for Coders
Design for Coders
User Experience Design
Joomla for Beginners
SQL Database for Beginners
Creating a PHP Login Script
Books from LearnToProgram, Inc.
HTML and CSS for Beginners
Javascript for Beginners
Python for Beginners
CSS Development (with CSS3!)
Page 5
ABCs of Programming Handbook
How to run the Javascript examples included in this eBook:
We will be using Javascript to explain the different concepts of programming
in this eBook. Javascript is not only an interpreted language which runs in a
browser, but also becoming a full fledged application development language.
Since it is interpreted, once you type in the Javascript code, it can be executed
at once. Any runtime errors can be immediately corrected and the program
executed again. There is no need to sit helplessly while waiting for the code to
compile before you can execute it.
Besides your browser, you will also need a text editor to input and modify your
code. There are many powerful and popular text editors, such as Sublime Text,
Komodo Edit, EditPlus, jsPad, GEdit, Textmate, and NotePad++.
Once you have your text editor and browser installed and ready to go, open
up your text editor and create a new file. You can name this file anything you
would like as long as it has the .html file extension. Copy and paste the following
code into your new .html file:
<!DOCTYPE html>
<html>
<head>
	 <meta charset="UTF-8">
	 <title>ABC’s of Programming</title>
	<script>
		
	</script>
</head>
<body>
	
</body>
</html>
It is within the <script> and </script> tags where you place your Javascript
code.
A - Array
Now, to run your Javascript code, you have to load your HTML file into your
browser. In Windows (using Explorer) and on the Mac (using Finder), you can
simply click or double-click on the HTML file. You can also type the HTML file’s full
pathname in the address or URL bar of your browser.
Alternatively, some text editors, such as Komodo Edit, have a preview
capability. This will allow you to load the browser to run your HTML file from
within the text editor.
Page 7
ABCs of Programming Handbook
Table of Contents
A - Array
B - Boolean
C - Concatenation
D - Debug
E - Exceptions
F - For Loops
G - Global Variable
H - HTML
I - If/Else
J - Java
K - Kilobytes
L - Library
M - Methods
N - Null
O - Objects
P - Pseudocode
Q - Query
R - Return
S - SQL
T - Ternary If
U - UML
V - Variable
W - While Loops
X - XML
Y - Yottabyte
Z - Z-index
8
11
13
15
17
19
22
24
26
28
30
31
33
35
37
40
41
43
46
49
50
52
54
55
58
59
A - Array
Arrays are a powerful and frequently used data type in most programming
languages. Just like variables, an array is uniquely identified by its assigned
name but unlike ordinary variables which can store only one value, an array
can store many values. Let’s take a look at declaring an array in Javascript:
var myArray = new Array();
Here, we have instantiated an array object and assigned that array object to
the myArray variable that we have declared (on the same line). If you try to run
the above code, you won’t see any data rendered inside the browser. This is
because we are only declaring a variable and initializing it—we haven’t stored
any values into the array.
We have three options to populate or add data to an array in Javascript. Let’s
take a look at instantiating an array object and assigning that array object to
our myArray variable (which we will declare) and populating it in three different
ways.
Option 1: Regular
var myArray = new Array();
myArray[0] = "value1";
myArray[1] = "value2";
myArray[2] = "value3";
Option 2: Condensed
var myArray = new Array("value1", "value2",
"value3");
Option 3: Literal
var myArray = ["value1", "value2", "value3"];
Array
Place
Sticker
Here
A
Page 9
ABCs of Programming Handbook
The values that are being held by myArray are called strings.
Each value stored in an array is identified by an index. You can think of an
index as an identifier or key that corresponds to a value stored at a specific
position in the array. The values held in the array can be referenced according
to their indexes. Javascript, like most programming languages, is zero indexed,
meaning that the indexes of an array’s stored values start at 0. If we have an
array that is storing three values, the index and corresponding values for these
indexes would be:
Array Indexes and Associated Values
INDEX VALUE
0 value1
1 value2
2 value3
To actually access the value held in an array, we use the name of the array,
followed by square brackets. Inside these square brackets we enter the index of
the element that we would like to access:
myArray[index];
Now that we have an understanding of what indexes are and how they work,
we are going to output the data that is held inside myArray through its indexes
to the browser. We will be using the write method of the document object in
Javascript to accomplish this.
var myArray = new Array();
myArray[0] = "value1";
myArray[1] = "value2";
myArray[2] = "value3";
document.write(myArray[0] + "<br>");
document.write(myArray[1] + "<br>");
document.write(myArray[2] + "<br>");
Near the end of the last three lines of the preceding code are the characters: +
“<br>”. The + symbol is the concatenation operator—you’ll learn more about
A - Array
that when you get to letter “C”. The characters <br> (without the quotation
marks) are the HTML tag for line break. Once you have copied the above
code example into your .html file, saved it and loaded it in your browser, you
will see the following display which shows the values that are stored in the array
myArray.
Place Sticker Here
Page 11
ABCs of Programming Handbook
Boolean logic gives programs the power to make decisions. It was named
after the mathematician George Boole. Using Boolean logic, programs can
evaluate a condition to either of the two Boolean values: true and false. For
an evaluated result of true, the program will execute a specific set of program
statements. For false, it will execute another set of program statements.
Let’s declare and initialize a Boolean variable, myBoolean, to true in Javascript
and then use myBoolean in a simple if statement.
var myBoolean = true;
if(myBoolean == true){
	 document.write("The value is true");
}
See how we use two equal signs (==) in the second line of the previous code?
Boolean
Place
Sticker
Here
B
Place Sticker Here
B - Boolean
This is a comparison operator, used to compare two values. When you see a
single equal sign, as in the first line, this is called an assignment operator. It is
used to assign a value (on the right-hand side of the equal sign) to a variable
(on the left-hand side.)
Once you have copied the above code example into your .html file, saved it
and loaded it in the browser, you should see the text “The value is true” output
to the browser.
Page 13
ABCs of Programming Handbook
Concatenation is the process of joining several separate pieces together into
one whole. Most languages only allow strings to be concatenated but in
Javascript it is possible to concatenate values of different data types. (Note,
however, that in Javascript there are a few combinations of data types that
cannot be validly concatenated such as an object and a string.)
The concatenation operator in Javascript is the plus sign (+) which is also
the addition operator. However, Javascript can deduce from the operands
whether the plus sign (+) indicates concatenation or addition.
First, let’s take a look at concatenating two strings in Javascript:
var myString = "Hello " + "World";
myString now contains the concatenated string: “Hello World”. Here, since
both operands are strings, Javascript interprets the + sign as the concatenation
operator.
We can also concatenate variables:
var myFirstString = "Hello ";
var mySecondString = "World";
var myThirdString = myFirstString + mySecondString;
myThirdString contains the concatenated string: “Hello World”.
Let’s output the value of myThirdString:
document.write(myThirdString);
Concatenation
Place
Sticker
Here
C
C - Concatenation
In this example, we will concatenate an integer data type and a string data
type
var myFirstInt = 1;
var myFirstString = "Hello!";
var mySecondString = myFirstInt + myFirstString;
The value of mySecondString is now “1Hello!”. Since one of the operands is a
string, Javascript still interprets the + operator as concatenation.
Now, in the next example, we are working purely with numbers and so
Javascript will interpret the + operator as addition.
var myFirstInt = 1;
var mySecondInt = 2;
var myThirdInt = myFirstInt + mySecondInt;
myThirdInt will have the value of 3.
Place Sticker Here
Page 15
ABCs of Programming Handbook
Debugging is an indispensable aspect of programming. In fact, programmers
tend to spend more time debugging code than writing it! Debugging is
the process of locating and correcting or bypassing errors or “bugs” in
programming code. Bypassing comes about when the bug can’t be corrected
and so you do the next best thing which is to avoid it.
The foundation of all debugging is testing—thorough and comprehensive
testing. As systems are being programmed and developed, they undergo
several possible levels of testing: unit, system, integration, acceptance, security,
usability, and so on. The actual testing levels implemented will depend on the
nature and complexity of the software being developed. More importantly, this
cycle of testing is conducted repeatedly.
All programs are now developed with a modular structure, allowing modules
and even sub-modules to be tested in isolation (unit testing) and then as groups
of modules (integration and usability testing) and then finally as a whole system
(acceptance, security and system testing).
An overlooked but essential aid to software testing and debugging are
source code comments. While the software documentation (software design
specifications printed on paper and usually held in binders) should contain
all the necessary information about a system, these documents may not
be currently updated and they could be misplaced or even lost. Source
code comments have greater chances of being updated than paper
documentation. As programmers make changes to the source code it takes
little effort to update the program comments as well. Source code comments
are more accessible than paper documentation and they can never be lost.
In Javascript, comments look like this:
//this is a comment in Javascript.
Comments are ignored by the browser or system that runs the program.
Here is code that has some errors in it. Try running the code to see if you can
Debug
Place
Sticker
Here
D
D - Debug
find the errors:
CODE TO DEBUG:
var myVariable = 45;
//myVariable is declared and assigned the value 45
var myOtherVariable = myVariable;
// myOtherVariable is declared and assigned the value
of myVariable (45).
Document.write(myotherVariable);
//myOtherVariable is being ‘written’ to the browser
var myFirstInt = ‘4’;
//myFirstInt is declared and assigned the value of
‘4’
var mySecondInt = 4;
//mySecondInt is declared and assigned the value of 4
document.write(myFirstInt + mySecondInt);
//myFirstInt and mySecondInt are added together
(using the addition operator in this context)
DEBUGGING ANSWER:
document.write(myOtherVariable);
//myOtherVariable was not using the correct
capitalization for the word: other.
Var myFirstInt = 4;
//myFirstInt was assigned the value of a string
(‘4’) and was actually concatenating the two values
together, not adding them.
Page 17
ABCs of Programming Handbook
Exceptions are extraordinary and unexpected events and circumstances
that occur during a program’s execution and cause the program to crash.
Exceptions are not bugs or programming defects. A bug is an error in the code,
not an event or circumstance.
One common example of an exception is a missing file. Let’s say that part of a
program’s logic is to access a specific file. During the first few days and weeks
of the program’s production run, it has successfully accessed that file. But now,
unknown to the users of the program, that file was deleted or corrupted for
some reason and now the program simply freezes or terminates at the point
where it is supposed to access the file. Users of the program have no idea why
a program which executed flawlessly before now just freezes or terminates.
Here is a situation tailor-made for the try...catch statement. Try...catch can
identify the type of exception encountered, inform the user with a clear error
message and then present the user with some options and then let the program
continue execution, ignoring the exception if possible, or gracefully exit the
program if the user so decides.
In the code block of the try clause of the try...catch statement, we place the
program statements where we reasonably expect an exception may occur.
In our preceding example of the missing file, this is where we would place the
statement which opens the file. If an exception occurs in the code block of the
try clause, then program execution will jump to the code block of the catch
clause.
Javascript will pass an error object to the code block of the catch clause. We
can make use of two (of the many) properties of this object, namely: name
and message. The name property contains the name of the exception and the
message property contains an error message we can display for the user.
Let’s write some code that will throw an exception and handle it with a try...
catch statement. We are going to call a function, myFunction, that does not
exist.
Exceptions
Place
Sticker
Here
E
E - Exceptions
Don’t let the simplicity of this example fool you—try-catch blocks are a very
important concept in all programming languages.
try{
	myFunction();
} catch(error){
	 document.write(‘Error: ‘ + error.name + ‘<br>’);
	 document.write(‘Error: ‘ + error.message);
}
Place Sticker Here
Page 19
ABCs of Programming Handbook
For Loops are a very useful and powerful construct in programming. Loops allow
us to repeatedly execute a block of code while a condition exists or until a
condition is met. One loop construct that exists in all programming languages is
the for-loop. This loop is handy when you know exactly how many times you will
execute (iterate over) a block of code and what condition(s) will keep the loop
executing and what condition(s) will terminate the loop.
Let’s look at the structure of the for-loop in Javascript:
for(initialize; test-condition; increment){
	 // block of code to loop through
}
The logic for a for-loop is declared in its first statement within the parentheses
after the for keyword. There are three statements which have been
appropriately labelled initialize, test-condition and increment to denote the
essential function of each statement. Note that each statement ends with a
semi-colon.
The initialize statement sets the starting value of the loop’s counter variable. The
counter variable keeps track of the number of times the loop is executed.
The test-condition statement declares the condition for the loop’s continued
execution. This condition is evaluated at the beginning of each loop. If the
evaluated result is true, the loop is executed. Otherwise, the loop terminates.
The increment statement sets the value by which the counter variable will be
incremented (which is usually 1) for every execution of the loop. This way, we
always know at any time how many iterations the loop has already undergone.
If we increment a variable, we add a value to that variable—usually 1.
For Loops
Place
Sticker
Here
F
F - For Loops
Here is a for-loop which will iterate five times.
for(var i = 0; i < 5; i++){
	 // any code in here will be executed 5 times!
}
For-loops are extremely handy when working with arrays. This is because we can
loop through an array via its indexes. To get the number of storage locations in
a Javascript array, we use the array’s length property, like this:
myArray.length;
It is important to note that the length of an array will always be 1 greater than
the highest index of the array. This is because in Javascript, indexes start at
0. Therefore, an array with five storage locations (length=5) will have 4 as its
highest index.
It should also be noted that the length of an array does not necessarily denote
the actual number of elements in the array, as some storage locations can be
empty.
Let’s create an array and loop through the array in Javascript:
var myArray = new Array('value1', 'value2', 'value3',
'value4', 'value5');
for(var i = 0; i < myArray.length; i++){
document.write("Index " + i + " : " + myArray[i] +
'<br>');
}
When we increment a variable we are adding one to it’s current value.
Page 21
ABCs of Programming Handbook
Place Sticker Here
G - Global Variable
In programming, scope refers to the visibility or accessibility of a function,
method, or variable. Rules of scope determine what variables and functions
can be accessed by the entire script or by specific areas of the script.
Let’s take a look at these lines of Javascript code:
var myVariable = "Hello World";
function myFunction(){
	 var myLocalVar = "I am inside myFunction()";
	document.write(myVariable);
}
document.write(myLocalVar);
In the above code, we have a global variable, myVariable, which is visible to
the entire script even from within the function myFunction().
On the other hand, a local variable, such as myLocalVar, which is declared
within the function myFunction(), is accessible from only within myFunction().
The last line of the preceding code will cause an error.
Let’s take a look at declaring a variable (locally) inside one function and then
trying to access that variable from another function:
function myFunction(){
	 var myVariable = "Hello World";
	myOtherFunction();
}
function myOtherFunction(){
	document.write(myVariable);
}
Global Variable
Place
Sticker
Here
G
Page 23
ABCs of Programming Handbook
This error occurs as myVariable is not visible to myOtherFunction, as the variable
is local to myFunction.
One way we can quickly and conveniently test our two functions in the
preceding code, is to attach either of them as an event handler to the onload
event of the <body> tag of an HTML page. When an HTML page is loaded into
a browser, the onload event is automatically fired and any attached event
handlers (in this case either of our two functions) are automatically executed.
(Please note that this is not the optimal method of using event handlers in
actual production websites. We are just doing this to facilitate the testing of our
functions.)
This is the change to make to the body tag of your HTML page.
<body onload="myFunction()">
Once we load the HTML file in the browser, we won’t see any output. Now,
in Google Chrome, access the browser’s console by right-clicking inside the
browser and clicking “Inspect Element” and selecting the “console” option at
the bottom of the browser window. You will see the following display:
Place Sticker Here
H - HTML
HTML stands for Hyper Text Markup Language. HTML was specified at the
European Laboratory for High-Energy Physics (CERN) in Geneva, Switzerland
as early as 1988. (A year later, the World Wide Web project was also started
there.) HTML is executed by the browser and is the language used to define the
structure, meaning, and content of webpages. HTML is also one of the three
main technologies that are used to make dynamic, rich web content, the other
two being Cascading Style Sheets (CSS), and Javascript. There have been
many major and minor versions of HTML since 1988 but the more significant
versions have been HTML 2.0 (1995), HTML 3.2 (1997), HTML 4.0.1 (1999), XHTML
(2000), and the current version HTML 5 (2008).
In a markup language, tags are used to define elements within a document. An
element consists of an opening and closing tag and the text between them. In
the following example, an HTML paragraph element is defined by the opening
tag <p> and closing tag </p>.
HTML
Place
Sticker
Here
H
Place Sticker Here
Page 25
ABCs of Programming Handbook
<p>This is a one sentence paragraph of text.</p>
The text between the tags is what is displayed on the browser. The tags
themselves are never displayed.
Another example of HTML tags are the six levels of headings, each denoted by
the letter ‘h’ followed by a number between 1 and 6; a level 1 heading being
the largest and a level 6 heading being the smallest.
<h1>This is a level 1 heading</h1>
<h3>This is a level 2 heading</h3>
The site http://dev.w3.org/html5/markup/elements.html provides a
comprehensive list of HTML tags.
I - If-Else
If-else statements are central to programming logic. These statements allow
our scripts to make decisions and take either of several actions based on those
decisions. We saw an if-statement in Javascript when discussing Boolean logic
under the letter ‘B’.
Now, let’s take a look at an if-else statement in Javascript:
if(1 < 2){
	 document.write("1 is less than 2");
} else {
	 document.write("1 is NOT less than 2");
}
The above if-else statement is saying, “If 1 is less than 2, display ‘1 is less than 2’
on the webpage. Otherwise, display ‘1 is NOT less than 2’.”
We can also use variables to make our if-else statements more powerful:
var x = 1;
var y = 2;
if(x < y){
	 document.write(x + " is less than " + y);
} else{
	 document.write(x + " is NOT less than " + y);
}
If-Else
Place
Sticker
Here
I
Page 27
ABCs of Programming Handbook
We are doing the exact same thing as the previous if-else statement, but this
time we are using variables instead of literal numbers in our condition. We can
then change the values that are assigned to the variables, x and y.
Place Sticker Here
J - Java
Java is a powerful and popular programming language. People often confuse
Java with Javascript, or assume that Javascript is Java-related, but actually the
two languages are not only very different in syntax and purpose but also have
separate origins and development histories. Java code is compiled into Byte
Code, which is read by a Java Virtual Machine (JVM), while Javascript is an
interpreted language that is executed by a browser.
Let’s take a look at a simple Java program:
package tv.learntoprogram.HelloWorld;
public class HelloWorld{
public static void main(String[] args){
	 System.out.println("Hello World");
}
}
Java
Place
Sticker
Here
J
Place Sticker Here
Page 29
ABCs of Programming Handbook
This code is saved in a file titled HelloWorld.java and it outputs “Hello World” to
the console when run.
We have used the NetBeans IDE to run this sample code.
Every Java program requires a main method. (We will take a closer look at
methods under the letter M.) The main method is the starting point of execution,
meaning that the program will start with the main method.
An important, fundamental concept in the Java programming language is a
package. A package is simply a unique way of identifying an application and is
preceded with the keyword package. Our package in the previous example is:
tv.learntoprogram.helloWorld;
To name our package, we use a reversedomain name, which is generally the
author’s domain name in reverse.
Java is a strongly typed language, meaning that each variable must have a
data type. Let’s declare and initialize a variable that we will use to store an
integer:
int myVariable = 1;
As you can see, we have declared myVariable as a whole number integer (int)
and assigned it an initial value of 1. Declaring myVariable as int means that we
can only store other values of type int in myVariable. If we tried to store a value
of float in myVariable, or a string value, the compiler would flag a fatal error.
K - Kilobytes
A kilobyte is equal to 1000 bytes, but you may be more familiar with the number
1024. The term kilobyte uses the decimal system, compared to a kibibyte, which
uses a binary prefix and has a value of 1024 bytes.
In programming it is important to understand the difference between bits and
bytes. A byte is comprised of eight bits, where a bit is the smallest unit of data
that we can have on a computer system. A bit can only be in two states, ON or
OFF. These two states are represented by the values 1 (for ON) and 0 (for OFF).
You may have heard of something called binary code. Binary code is
comprised of bits and 8 bits make up a byte. Binary code can be used to
represent letters, symbols or even instructions for a computer system.
Here is an example of binary code, for the string “hello world”:
01101000 01100101 01101100 01101100 01101111 00100000
01110111 01101111 01110010 01101100 01100100
Let’s take a look at some of the numeric data types in Java and see how much
space they are allocated in memory:
Numeric Data Types in Java
Numeric Data Type Min to Max Values Size Allocated in Memory
Byte -128 to 127 8 Bits
Short -32,768 to 32,767 16 Bits
Int -231
to 231
-1 32 Bits
Long -263
to 263
-1 64 Bits
As you can see, in Java programming it makes sense to choose the appropriate
numeric data types for your variables. For example, do not choose a variable
of type long to store the current ages of employees. A byte variable will do
since realistically no one younger than 10 years or older than 100 years gets
employed.
Kilobytes
Place
Sticker
Here
K
Page 31
ABCs of Programming Handbook
Many programming languages employ code libraries, which are collections
of proven, tested and bug-free code. The code in a library is in the form
of functions and classes and their related constants and global variables.
Programmers can call the library’s functions and create objects from its classes.
Libraries are a terrific time-saver in that they save a programmer the immense
effort and aggravation required to write and debug code that has already
been written, debugged and packaged into a library.
A very popular Javascript library is jQuery. It not only cuts down on
development time but results in very compact code. For example, let’s take a
look at how we would select an element in plain old Javascript:
document.getElementById("div");
With jQuery, we can write this as:
$("div");
This is not only compact but more readable code.
There are many ways to access a library from your code. In Javascript, the
most common way is to set the source attribute (src) of the script tag to the full
pathname of the library’s source code file, as shown in the following line:
<script src="myFile.js"></script>
Let’s look at Javascript code that calls the jQuery fadeIn() method which
changes the opacity of an element from hidden to visible. In the following
code example, the fadeIn() method accepts a parameter of 5000 which is the
number of milliseconds for the effect to last.
<!DOCTYPE html>
<html>
<head>
	 <meta charset="UTF-8">
Library
Place
Sticker
Here
L
L - Library
	 <title>ABC's of Programming</title>
	 <script src="http://code.jquery.com/jquery-
1.10.2.min.js">
	</script>
	<script>
		 $(document).ready(function(){
			$('#text').fadeIn(5000);
		 });
	</script>
</head>
<body>
	 <p id="text" style="display:none;">This text will
slowly fade in!</p>
</body>
</html>
Place Sticker Here
Page 33
ABCs of Programming Handbook
A method is just a function that is built into an object. The function now
becomes a method of the object and it can be called (invoked) by its name.
The method’s format and syntax is identical to that of functions, like so:
methodName(parameters) {
	statements
}
Methods are part of an object’s blueprint and are fundamental to the OOP
(Object-Oriented Programming) concept. We will go through objects under the
letter ‘O’.
In Javascript, we use the dot operator (.) to invoke a method of an object. It
looks like this:
Object.methodName();
Let’s take a look at some of the fundamental methods that are part of the
Math object that Javascript has to offer. The Math object is packed full of useful
methods that we can use for mathematical type operations in Javascript. For
example, if we needed to generate a random number, we use the random()
method of the Math object:
var myRandomNumber = Math.random();
document.write(myRandomNumber);
If you were to run the above code in your browser, the result may surprise you.
The random() method actually generates a random number between 0 and
not quite 1. So, we could have a number of 0.9059727436397225.
Methods
Place
Sticker
Here
M
M - Methods
In this new piece of code, we have instructed the browser to multiply the value
that is generated by the random() method by 10. This should give us a new
number that is between 0 and less than 10. As before, the number returned
could be a decimal, for example: 1.315551579464227.
So, we used the floor() method, also of the Math object, to round down this
number. This would then give us a whole number between 0 and 9. Finally, we
added 1 to the result to end up with a whole number between 1 and 10.
Let’s fix this up and generate a number between 1 and 10:
var myRandomNumber = Math.floor(Math.random() * 10) +
1;
document.write("The random number is: " +
myRandomNumber);
Place Sticker Here
Page 35
ABCs of Programming Handbook
null is a keyword that is used in most programming languages to signify the
absence of data. null is different from an empty string, the Boolean value false,
or the number 0. This is because an empty string, the Boolean value false, and
the number 0 all represent some form of data, whereas null represents the
absence of data.
null can be used in a variety of ways. For example, if we want to stop
referencing an object in Java, we could nullify that object’s reference variable
by setting it to null (objVariable = null). This would make the memory that the
object used eligible for Java’s garbage collection memory management tool.
Another use of null in a Java program is to check whether an object reference
variable is actually referencing an object. If the object reference variable is
referencing nothing, it is null. Let’s take a look at this in Java code:
Object myObject = new Object();
// more code, maybe myObject was nullified…
if(myObject == null){
null
Place
Sticker
Here
N
Place Sticker Here
N - null
System.out.println("myObject is not referencing any
object");
}else{
System.out.println("myObject is referencing an
object");
}
In this code, we have declared a variable, myObject, of type Object and
assigned it an instance of Object (the ancestor of all objects in Java). We then
go on to check if that object equals null, if it does equal null, that means that
the object reference variable myObject no longer references any object and a
message is printed to the console.
Page 37
ABCs of Programming Handbook
In programming, objects are a powerful and important concept. To understand
how objects work and what they do, we need to know what a class is and what
a class contains. A class is a blueprint for an object. It contains the details of the
class’ properties (also called instance variables) and methods.
Properties define the object’s current state or characteristics while methods
define the object’s behavior. (Recall from ‘M’ that a method is just a function
that is built into an object.)
Let’s take a look at objects in Java and start out by defining a simple person
class:
package tv.learntoprogram.person;
public class Person{
	 private int age;
	 private String name;
	 public void setAge(int age){
		 this.age = age;
}
public void setName(String name){
	 this.name = name;
}
public int getAge(){
		 return age;
}
public String getName(){
	 return name;
}
}
Objects
Place
Sticker
Here
O
O - Objects
Notice how the class starts with a capital letter. This is part of the Java naming
convention: classes should start with a capital letter, whereas methods and
variables generally start with a lower case letter.
Our instance variables are age and name. (These two properties give unique
characteristics to the object.) They have been marked private, which means
that these variables can only be accessed from within the class where they are
declared and defined.
Our methods are setAge(), setName(), getAge() and getName(). These
methods are marked as public, so they can be accessed outside of this class.
We also need to declare the return type for a method. For setAge() and
setName(), we don’t need to return any values, as we are simply setting the
value for the instance variables. However, we do want to return an int and a
String for the getAge() and getName() methods, respectively. You will learn
more about returning a value under the letter ‘R’.
As you can see, we have variables inside the parentheses for the setAge() and
setName() methods. In this context, these are called parameters. When we
invoke either the setAge() or setName() methods, we are expected to pass
values as arguments to the parameters defined in our methods. Inside the
setAge() and setName() methods we are using the keyword this, which, in this
context, means this object’s age or this object’s name. When we invoke these
methods, we pass in the expected values as arguments and these values are
assigned to the object’s instance variables respectively (age or name).
Once we have a class defined, we can then instantiate an object of that class.
Instantiating an object means creating an object from its class. In Java we do
this by using the keyword new:
package tv.learntoprogram.person;
public class Main{
public static void main(String[] args){
	 Person myPerson = new Person();
}
}
The following code would be saved in a file titled Main.java and would be
inside the same package as the Person class. myPerson is actually an object
Page 39
ABCs of Programming Handbook
reference variable, meaning that it references a Person object.
When we say:
Person myPerson = new Person();
We are instantiating a new Person object and assigning that Person object to
an object reference variable named myPerson.
To set the age and name of this Person object, we invoke the setAge() and
setName() methods on the myPerson object reference variable:
myPerson.setAge(24);
myPerson.setName("Joe");
We can then print out this Person object’s name and age:
System.out.println("The person's age is: " +
myPerson.getAge());
System.out.println("The person's name is: " +
myPerson.getName());
Place Sticker Here
P - Pseudocode
A programming language follows strict syntax and semantics rules and coding
procedures. Its main purpose is to convey instructions to a machine and
actually consists more of symbols than words and sentences. It usually takes a
year for a programmer to master a programming language.
On the other hand, pseudocode is an informal way of describing to other
persons (not to a machine) the logic and processes of a computer program.
Pseudocode uses standard English grammar rules, semantics, phrases and
sentences. It can be easily and immediately understood by everybody
including non-programmers.
Let’s take a look at the pseudocode of a simple calculator program.
Begin Program
	 While calculator running
		 Retrieve user input
		 If user input was not valid
			Output error
			 Request user input
		 Else if user input was valid
			Calculate Total
			Output Total
			 Request user input
		 Else if user input is equal to 'N'			
			Exit Program
		 End if
	 End While
End Program
Pseudocode
Place
Sticker
Here
P
As you can see here, pseudocode is not real
code but it can be easily converted into the
syntax of any programming language.
Page 41
ABCs of Programming Handbook
Data is stored in relational database systems to provide an organized structure
and ease later retrieval. We communicate with the database via a query.
To create queries, we strictly adhere to the syntax defined by the Structured
Query Language (SQL) which is the standard computer language for relational
database management and manipulation. (We will look at SQL under letter ‘S’).
As an example, let’s assume we have a database containing a table called
users. The table’s data is represented in the following grid. The users table
has three records - represented by the second to the fourth row. The first row
contains just labels or headings. Each record (row) corresponds to one unique
user. Each record consists of three fields: username, email and user_id. The
values in these fields uniquely describe a user. Put another way, no two records
can have identical data in all fields.
user_id username email
001 hisUserName his@address.com
002 myUserName example@example.com
003 herUserName her@address.com
Now, we want to retrieve the email address of a certain user named
‘myUserName’. To do this, we compose the following query (which has to follow
a strict syntax and use specific keywords):
SELECT email FROM users WHERE username = ‘myUserName’;
In this SQL statement, we are retrieving the email field of the record whose
username field holds the value ‘myUserName’. We are retrieving this all from the
users table.
Query
Place
Sticker
Here
Q
Q - Query
If we run this SQL statement in phpMyAdmin (a database administration tool),
we would get this result:
If you look closely at the last line in the preceding screenshot, you will see
example@example.com (without the quotes). This is the email address returned
by phpMyAdmin corresponding to username=”myUserName”.
In the preceding SQL statement above, we will replace ‘email’ with the asterisk
‘*’ which means all fields in the table.
SELECT * FROM users WHERE username = ‘myUserName’;
Place Sticker Here
Page 43
ABCs of Programming Handbook
In programming, many functions return a value through a return statement.
Even if a programmer does not use the return statement in a function, the
compiler or interpreter will program a return statement into the function that
returns the null value. (We discussed null earlier, under ‘N’). Returning a value
from a function can provide us either with an indication of whether a function’s
operations were successful or with a value for use in the rest of the program.
Let’s take a look at returning a Boolean from a function in Javascript.
Consider the following code:
function runTest(value){
	 var test = regexTest(value);
	 if(test == true){
		 document.write("value matched regex");
	 } else{
		 document.write("value did not match regex");
	}
}
function regexTest(value){
	 var regex = /e+/;
	if(regex.test(value)){
		 return true;
	 } else{
		 return false;
	}
}
We have two functions, runTest() and regexTest(). Once we invoke the runTest()
Return
Place
Sticker
Here
R
R - Return
function, the test variable is declared and the regexTest() function will be
invoked, using the value argument that we pass into the runTest() function. The
regexTest() function will take our argument and use the test() method to check
whether it matches our regular expression, defined in variable regex.
Regular expressions can be thought of as a pattern that we may want to use
to check if a value matches it. The regular expression (/e+/) we have used will
match one or more occurrences of the letter e. If we have a value of eeee or e
passed in, our regexTest() function will return true, but if we have a value of ‘k’,
our regexTest() function will return false.
Once the regexTest() function has completed, our ‘test’ variable will be
assigned the return value from regexTest(). The runTest() function will then write
a message out to the browser, depending on whether the test variable’s value
is equal to true or not.
We can invoke the runTest() function by attaching an onload event to the
opening <body> tag and inside the parentheses, passing in a string, like so:
<body onload="runTest('eeee')">
The complete .html code would look like this:
<!DOCTYPE html>
<html>
<head>
	 <meta charset="UTF-8">
	 <title>ABC's of Programming</title>
	<script>
		 function runTest(value){
			 var test = regexTest(value);
			 if(test == true){
				document.write("value matched regex");
			} else{
				 document.write("value did not match
regex");
Page 45
ABCs of Programming Handbook
			}
		 }
		 function regexTest(value){
			 var regex = /e+/;
			if(regex.test(value)){
				return true;
			} else{
				return false;
			}
		 }
	</script>
</head>
<body onload="runTest('eeee')">
</body>
</html>
The output of passing in eeee as the argument to runTest() would look like this:
Place Sticker Here
S - SQL
Structured Query Language (SQL) is the standard computer language for
relational database management and manipulation. SQL commands adhere
to a strict syntax and vocabulary.
Before we look at the syntax of SQL, let’s take a quick look at the simplified
structure of a table—the major component of a database. (A database can
consist of hundreds of tables.)
The grid below is a simplified representation of the structure of the table
website_users in the database named website. Each column signifies a specific
piece of data and its data type and a row signifies a record of data. The first
row in the grid is not an actual row in the table but simply holds the names of
the fields of each row, namely: user_id, name, email, age. The user_id field
is designated as the primary key and, as is, its value should be unique (no
two records can have the same value in their user_id field). The values of the
user_id field are generated by the database management system to ensure
uniqueness of its values. Our sample table has three rows or three records in the
table.
user_id name email age
001 Jose example@example.com 24
002 Larry his@address.com 56
003 Moe her@address.com 22
Here are SQL statements to create the database website and its table website_
users.
CREATE DATABASE website;
USE website;
CREATE TABLE website_users(
SQL
Place
Sticker
Here
S
Page 47
ABCs of Programming Handbook
	 user_id INT NOT NULL AUTO_INCREMENT,
	 name VARCHAR(255),
	 email VARCHAR(255),
	 age INT,
	 PRIMARY KEY(user_id)
);
In the preceding SQL statements, the CREATE DATABASE statement creates an
empty database. The USE statement allows access to it. Then, the CREATE TABLE
statement creates the table website_users and defines the table’s fields, in
particular, the names and data types of the fields.
The primary key field, user_id, is going to contain numbers, so it is declared
as type INT. It is set to NOT NULL so that it always has a value. It is also set to
AUTO_INCREMENT so that a unique value for it is generated. These are all
characteristics of a table’s primary key. The last clause of the CREATE TABLE
statement sets the field user_id as the primary key of the table.
The name and email columns have a data type of VARCHAR (variable
character field) with a maximum length of 255 characters. Numbers and text
can be stored in these fields as well as special characters. The age field would
also contain a numeric value.
To insert data into this example database, we use the following SQL statement:
INSERT INTO website_users(name, email, age)
VALUES("Joe", "example@example.com", 24);
The INSERT INTO statement adds values to the fields of a record, in effect,
adding a new record. We indicate the names of the fields (name, email,
age), which will accept the new values and then we list the values
themselves(“Joe”, “example@example.com”, 24)in the same order that we
listed the fields.
S - SQL
If we were to display the content of our database, which at this point contains
only the first record, it would look something like this:
Place Sticker Here
Page 49
ABCs of Programming Handbook
The ternary if-statement lets us rewrite a simple if-else-statement with single line
code blocks into one compact statement. First, let’s examine a Javascript if-
else-statement.
var result = false;
if(9 < 10){
	 result = true;
} else{
	 result = false;
}
We have initialized a variable result to the Boolean value false. Then, we
evaluate a conditional ( 9 < 10 ) which will definitely return the Boolean value
true. Thus, the variable result will be assigned the Boolean value true. Now, the
previous if-else-statement can be written as the following equivalent one-line
ternary if-statement:
var result = (9 < 10)? true: false;
The same logic and therefore the same results are obtained from this one-line
ternary if-statement as in the six-line if-else-statement.
Let’s take a closer look at the ternary if-statement syntax:
var myVariable = (condition)? true : false;
The condition is evaluated, if it is true, the code following the question mark is
executed (the Boolean value true gets assigned to myVariable). If the condition
is not true, then the code following the colon is executed (the Boolean value
true gets assigned to myVariable).
Of course, if your if-else-statement has multiple lines in the if and else code
blocks, then you cannot rewrite that if-else-statement as a ternary if statement.
Ternary If
Place
Sticker
Here
T
U - UML
UML (Unified Modeling Language) is a modeling language in the field of
software engineering that has been standardized by the Object Management
Group (ISO/IEC19501:2005) and is used by developers to specify, visualize,
construct and document software components. UML has become the de-facto
standard for building Object-Oriented software.
In terms of OOP (Object-Oriented Programming), a basic UML diagram can be
broken down into three sections: Name of the Class, State (Instance Variables)
and Behavior (Methods).
Let’s take a look at the basic layout of a UML diagram:
If we think about a computer in
terms of OOP, that is we consider
a computer as an object with
properties and behavior, we need to
consider two things: what state could
the computer be in, and what would
its behavior be?
For example, a very simplified
computer object model could be
in either of two states: on or off,
and, correspondingly, it would
be capable of two behaviors or
methods: turnOn() and turnOff().
Let’s take a look at this computer
class in a UML diagram:
UML
Place
Sticker
Here
U
Computer
isOn: Boolean
isOn: Boolean
turnOn(): void
turnOn(): void
Class Name
instanceVariable: Data Type
instanceVariable: Data Type
methodName(): Return Type
methodName(): Return Type
Page 51
ABCs of Programming Handbook
After we have designed our class using a UML diagram, turning that diagram
into working code is a straightforward task. In Java, our Computer class would
look like this:
package tv.learntoprogram.computer;
public class Computer{
	 private Boolean isOn = false;
private Boolean isOff = true;
public void turnOn(){
		 if(isOff == true){
			 isOn = true;
			 isOff = false;
		 } else{
		 System.out.println("Computer was already
on.");
		 }
}
public void turnoff(){
		 if(isOn == true){
			 isOn = false;
			 isOff = true;
		 } else{
		 System.out.println("Computer was already
off.");
		 }
	}
}
V - Variable
Variables are portions of a computer’s memory. To distinguish these memory
locations from one another, variables are assigned names.
A variable can hold different data types such as a whole number (int), a
decimal number (float), a string (a series of characters), or a Boolean (true
or false). Some programming languages, such as Java, are strongly typed,
meaning that the variable must be declared to hold a specific data type and
only that data type. Other languages such as Javascript are loosely typed,
meaning that no variable type declaration is required and any variable can
store any data type.
If we declare a variable in Java, we would say:
int myNumber = 2;
In Javascript, we would say:
var myNumber = 2;
In Javascript we could then reassign the value of myNumber to something like
a string:
myNumber = " String of Characters";
But if we tried to do this in Java, the compiler would flag our error and would
not produce an executable format of our program, making it impossible to
run. The Java compiler does this because Java is a strongly typed language. In
Variable
Place
Sticker
Here
V
Place Sticker Here
Page 53
ABCs of Programming Handbook
Java, once you have declared a variable to be of a certain data type, it can
only store values of that data type.
Strongly typed languages are very helpful. As you have seen in Javascript,
which is not a strongly typed language, we can change the data type of
a variable simply by assigning it a new value of a different data type. This
is sometimes the cause of unexpected behavior in a program and it can
often take a while to identify the source of the problem. With strongly typed
languages, we do not have this problem—this is because we cannot change
the data type of a variable.
W - While Loop
We explained for-loops under “F”. A for-loop is best used when you know how
many times you want to execute a block of code. If you don’t, then you can
use another loop construct, called the while-loop.
A while-loop starts with a condition. The condition is checked and if it evaluates
to true then the first iteration proceeds. Just before the second and subsequent
iterations, the condition is checked again and as long as it is true, the loop will
continue executing. But once the condition evaluates to false, the loop exits.
Let’s take a look at a simple while-loop in Javascript:
var i = 1;
while(i < 5){
	 document.write("Iteration Number: " + i + "<br>");
	i++;
}
This loop will iterate four times and generate the following output. Note that
for each iteration, we increment the variable i. If we do not do this, then the
program will execute the loop indefinitely.
While Loop
Place
Sticker
Here
W
Place Sticker Here
Page 55
ABCs of Programming Handbook
XML (eXtensible Markup Language) is a markup language designed to
transport and store data. In contrast, HTML (which we covered in ‘H’) is a
markup language designed to display data.
XML documents begin with a XML declaration, much like the doctype
declaration in HTML:
<?xml version="1.0"?>
An XML document must contain a root element. From this root element, child
and sub-child elements can be used to describe specific data contained within
the XML file. Let’s take a look at a simple XML document with a root element,
several child elements, and a few sub-child elements:
<?xml version="1.0"?>
<shop>
<item>
	<category>Electronics</category>
	<title>Laptop</title>
	<model>Satellite</model>
	<brand>Toshiba</brand>
</item>
<item>
	 <category>Electronics </category>
	<title>iMac</title>
	 <model>Late '09</model>
	<brand>Apple</brand>
</item>
<item>
XML
Place
Sticker
Here
X
X -XML
	<category>Appliance</category>
	<title>Fridge</title>
	<model>F200</model>
	<brand>Fridges-R-US</brand>
</item>
<item>
	<category>Electronics</category>
	<title>iPad</title>
	<model>Mini</model>
	<brand>Apple</brand>
</item>
</shop>
The <shop> element is our root element and the <item> elements are the child
elements of <shop>. The <category>, <title>, <model> and <brand> elements
are the child elements of <item> and are considered sub child elements.
If you were to save the above XML into a file (for example, we’ll call our file
shop.xml) and load it in your browser, it would look very strange. This is because
XML is generally used to store data for use in web services, not for presenting
data to the end user.
The element names in a XML document are created by the author. For
example, the element names we have used above (<brand>, <model> and so
on) are in no way standardized or part of a recommendation. However, keep
in mind that the names that you give your XML elements should describe the
contents of that element.
Page 57
ABCs of Programming Handbook
Place Sticker Here
Y - YottaByte
A YottaByte is an extremely large amount of data. In order to put this huge
amount of data into context, let’s take a look at a comparison of the main
data amounts and get a rough idea of what we would need to store these
various data amounts:
Various data amounts
Data Amount: Example Storage:
1 Yottabyte = 1000 Zettabytes We would need 1 Trillion 1 Terabyte Hard
Drives to store 1 Yottabyte of Data.
1 Zettabyte = 1000 Exabytes We would need 1 Billion 1 Terabyte Hard
Drives to store 1 Zettabyte of data.
1 Exabyte = 1000 Petabytes We would need 1 Billion 1 Gigabyte Hard
Drives to store 1 Exabyte of data.
1 Petabyte = 1000 Terabytes We would need 1 Million 1 Gigabyte Hard
Drives to store 1 Petabyte of data.
1 Terabyte = 1000 Gigabytes We would need approximately 213 4.7GB
DVD’s to store 1 Terabyte of data.
1 Gigabyte = 1000 Megabytes We would need around 1 Thousand 3 ½
“
Floppy Disks to store 1 Gigabyte of data.
1 Megabyte = 1000 Kilobytes We could store 1.44 Megabytes on a single
3 ½
“ Floppy Disk.
1 Kilobyte = 1000 Bytes We could store approximately 5 copies of
the latest Uncompressed jQuery Javascript
Library (276KB) on a single 3 ½
“ Floppy Disk.
As you can see, a Yottabyte is a huge amount of data and it is very unlikely that
any one organization would ever have enough data to fill this giant space.
YottaByte
Place
Sticker
Here
Y
Page 59
ABCs of Programming Handbook
In HTML, elements have a stacking order. This means that elements whose
position property are assigned either the values absolute, relative, or fixed will
always appear in the order in which they were created. (In CSS, the default
value of the position property is static.) With the help of CSS (Cascading Style
Sheets), we can actually manipulate this stacking order and choose which
elements appear on top and the order of the elements underneath the top
element. Z-index is a CSS property that sets the stack order of specific elements.
Consider this simple HTML file, which includes some simple CSS used to style the
elements on the page:
<!DOCTYPE html>
<html>
<head>
	 <meta charset=”UTF-8”>
	 <title>ABC’s of Programming</title>
	<style>
		 div{
			height: 200px;
			width: 200px;
			position: absolute;
		 }
		 #div1{
			top:0;
			left:0;
			background-color: blue;
		 }
Z-index
Place
Sticker
Here
Z
Z - Z-index
		 #div2{
			top:40px;
			left:40px;
			background-color: black;
		 }
		 #div3{
			top:20px;
			left:20px;
			background-color: pink;
		 }
	</style>
</head>
<body>
	 <div id=”div1”></div>
	 <div id=”div2”></div>
	 <div id=”div3”></div>
</body>
</html>
Page 61
ABCs of Programming Handbook
Place Sticker Here
If we load this HTML in our browser, we will see that the pink element (#div3) is in
front of the other elements:
Z - Z-index
Let’s change the stacking order of these elements using the z-index property. By
setting the z-index property to 1 we force the blue element (#div1) to the front.
#div1{
	top:0;
	left:0;
	 background-color: blue;
	z-index:1;
}
Place Sticker Here
Page 63
ABCs of Programming Handbook
Other LearnToProgram Books:
CSS Development (with CSS3!)
by Zachary Kingston
Python for Beginners
by Alex Bowers
Javascript for Beginners
by Mark Lassoff
HTML & CSS for Beginners
by Mark Lassoff
Availiable for Print or Kindle
https://learntoprogram.tv/books#

Weitere ähnliche Inhalte

Andere mochten auch

Andere mochten auch (9)

Net proiect-diagnostic-si-strategiile-firmei
Net proiect-diagnostic-si-strategiile-firmeiNet proiect-diagnostic-si-strategiile-firmei
Net proiect-diagnostic-si-strategiile-firmei
 
Pasos para producir un video
Pasos para producir un videoPasos para producir un video
Pasos para producir un video
 
Presentación curso
Presentación cursoPresentación curso
Presentación curso
 
Educación a distancia
Educación a distanciaEducación a distancia
Educación a distancia
 
How business can earn more revenue by making an efficient website?
How business can earn more revenue by making an efficient website?How business can earn more revenue by making an efficient website?
How business can earn more revenue by making an efficient website?
 
Sajid Sakkar CV
Sajid Sakkar CVSajid Sakkar CV
Sajid Sakkar CV
 
Las tics en el turismo
Las tics en el turismoLas tics en el turismo
Las tics en el turismo
 
Pravin Chand Resume 2016 pdf
Pravin Chand Resume 2016 pdfPravin Chand Resume 2016 pdf
Pravin Chand Resume 2016 pdf
 
Harbin Dadi E-catalog
Harbin Dadi E-catalog Harbin Dadi E-catalog
Harbin Dadi E-catalog
 

Ähnlich wie ABCs of Programming_eBook Contents

Java script basics
Java script basicsJava script basics
Java script basicsJohn Smith
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript ProgrammingRaveendra R
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript poojanov04
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproceHector Garzo
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdfHASENSEID
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
Javascript tutorial basic for starter
Javascript tutorial basic for starterJavascript tutorial basic for starter
Javascript tutorial basic for starterMarcello Harford
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
JavaScript Training in Ambala ! Batra Computer Centre
JavaScript Training in Ambala ! Batra Computer CentreJavaScript Training in Ambala ! Batra Computer Centre
JavaScript Training in Ambala ! Batra Computer Centrejatin batra
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentationAdhoura Academy
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erickokelloerick
 
Lecture17 ie321 dr_atifshahzad_js
Lecture17 ie321 dr_atifshahzad_jsLecture17 ie321 dr_atifshahzad_js
Lecture17 ie321 dr_atifshahzad_jsAtif Shahzad
 
Javascript breakdown-workbook
Javascript breakdown-workbookJavascript breakdown-workbook
Javascript breakdown-workbookHARUN PEHLIVAN
 

Ähnlich wie ABCs of Programming_eBook Contents (20)

Java script basics
Java script basicsJava script basics
Java script basics
 
Web programming
Web programmingWeb programming
Web programming
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproce
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Javascript tutorial basic for starter
Javascript tutorial basic for starterJavascript tutorial basic for starter
Javascript tutorial basic for starter
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
JavaScript Training in Ambala ! Batra Computer Centre
JavaScript Training in Ambala ! Batra Computer CentreJavaScript Training in Ambala ! Batra Computer Centre
JavaScript Training in Ambala ! Batra Computer Centre
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
Java script basic
Java script basicJava script basic
Java script basic
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
 
Lecture17 ie321 dr_atifshahzad_js
Lecture17 ie321 dr_atifshahzad_jsLecture17 ie321 dr_atifshahzad_js
Lecture17 ie321 dr_atifshahzad_js
 
Javascript
JavascriptJavascript
Javascript
 
Javascript breakdown-workbook
Javascript breakdown-workbookJavascript breakdown-workbook
Javascript breakdown-workbook
 

ABCs of Programming_eBook Contents

  • 1. Page 1 ABCs of Programming Handbook Ashley Menhennett Handbook of programming terms. Learn the ABC’s of coding with 26 terms and numerous code examples. The ABC’s of Programming The ABC’s of Programming
  • 2. A - Array LearnToProgram.tv, Incorporated 27 Hartford Turnpike Suite 206 Vernon, CT 06066 contact@learntoprogram.tv (860) 840-7090 ©2014 by LearnToProgram.tv, Incorporated All rights reserved. No part of this document may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of LearnToProgram.tv, Incorporated. Limit of Liability/Disclaimer of Warranty:  While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose.  No warranty may be created or extended by sales representatives or written sales materials.  The advice and strategies contained herein may not be suitable for your situation.  You should consult with a professional where appropriate.  By following the instructions contained herein, the reader willingly assumes all risks in connection with such instructions.  Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, exemplary, or other damages resulting in whole or part, from the readers’ use of, or reliance upon, this material.  Mark Lassoff, Publisher Kevin Hernandez, VP/ Production Ashley Menhennett, Author Alison Downs, Copy Editor Alexandria O’Brien, Book Layout
  • 3. Page 3 ABCs of Programming Handbook About the Author Ashley Menhennett is a 24-year-old programmer from Australia. Ashley also enjoys sharing his knowledge through teaching web development and programming.
  • 4. A - Array Courses Available from LearnToProgram, Inc. HTML and CSS for Beginners (with HTML5) Javascript for Beginners Java for Beginners jQuery for Beginners iOS Development Code Camp Become a Certified Web Developer PHP & MySQL for Beginners iOS 6/7 Development for Beginners Objective C for Beginners C Programming for Beginners Android Development for Beginners Creating an MP3 Player with Adobe Flash AJAX Development Python for Beginners CSS Development (with CSS3) HTML5 Mobile App Development with PhoneGap 3D Fundamentals with iOS Photoshop for Coders Design for Coders User Experience Design Joomla for Beginners SQL Database for Beginners Creating a PHP Login Script Books from LearnToProgram, Inc. HTML and CSS for Beginners Javascript for Beginners Python for Beginners CSS Development (with CSS3!)
  • 5. Page 5 ABCs of Programming Handbook How to run the Javascript examples included in this eBook: We will be using Javascript to explain the different concepts of programming in this eBook. Javascript is not only an interpreted language which runs in a browser, but also becoming a full fledged application development language. Since it is interpreted, once you type in the Javascript code, it can be executed at once. Any runtime errors can be immediately corrected and the program executed again. There is no need to sit helplessly while waiting for the code to compile before you can execute it. Besides your browser, you will also need a text editor to input and modify your code. There are many powerful and popular text editors, such as Sublime Text, Komodo Edit, EditPlus, jsPad, GEdit, Textmate, and NotePad++. Once you have your text editor and browser installed and ready to go, open up your text editor and create a new file. You can name this file anything you would like as long as it has the .html file extension. Copy and paste the following code into your new .html file: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ABC’s of Programming</title> <script> </script> </head> <body> </body> </html> It is within the <script> and </script> tags where you place your Javascript code.
  • 6. A - Array Now, to run your Javascript code, you have to load your HTML file into your browser. In Windows (using Explorer) and on the Mac (using Finder), you can simply click or double-click on the HTML file. You can also type the HTML file’s full pathname in the address or URL bar of your browser. Alternatively, some text editors, such as Komodo Edit, have a preview capability. This will allow you to load the browser to run your HTML file from within the text editor.
  • 7. Page 7 ABCs of Programming Handbook Table of Contents A - Array B - Boolean C - Concatenation D - Debug E - Exceptions F - For Loops G - Global Variable H - HTML I - If/Else J - Java K - Kilobytes L - Library M - Methods N - Null O - Objects P - Pseudocode Q - Query R - Return S - SQL T - Ternary If U - UML V - Variable W - While Loops X - XML Y - Yottabyte Z - Z-index 8 11 13 15 17 19 22 24 26 28 30 31 33 35 37 40 41 43 46 49 50 52 54 55 58 59
  • 8. A - Array Arrays are a powerful and frequently used data type in most programming languages. Just like variables, an array is uniquely identified by its assigned name but unlike ordinary variables which can store only one value, an array can store many values. Let’s take a look at declaring an array in Javascript: var myArray = new Array(); Here, we have instantiated an array object and assigned that array object to the myArray variable that we have declared (on the same line). If you try to run the above code, you won’t see any data rendered inside the browser. This is because we are only declaring a variable and initializing it—we haven’t stored any values into the array. We have three options to populate or add data to an array in Javascript. Let’s take a look at instantiating an array object and assigning that array object to our myArray variable (which we will declare) and populating it in three different ways. Option 1: Regular var myArray = new Array(); myArray[0] = "value1"; myArray[1] = "value2"; myArray[2] = "value3"; Option 2: Condensed var myArray = new Array("value1", "value2", "value3"); Option 3: Literal var myArray = ["value1", "value2", "value3"]; Array Place Sticker Here A
  • 9. Page 9 ABCs of Programming Handbook The values that are being held by myArray are called strings. Each value stored in an array is identified by an index. You can think of an index as an identifier or key that corresponds to a value stored at a specific position in the array. The values held in the array can be referenced according to their indexes. Javascript, like most programming languages, is zero indexed, meaning that the indexes of an array’s stored values start at 0. If we have an array that is storing three values, the index and corresponding values for these indexes would be: Array Indexes and Associated Values INDEX VALUE 0 value1 1 value2 2 value3 To actually access the value held in an array, we use the name of the array, followed by square brackets. Inside these square brackets we enter the index of the element that we would like to access: myArray[index]; Now that we have an understanding of what indexes are and how they work, we are going to output the data that is held inside myArray through its indexes to the browser. We will be using the write method of the document object in Javascript to accomplish this. var myArray = new Array(); myArray[0] = "value1"; myArray[1] = "value2"; myArray[2] = "value3"; document.write(myArray[0] + "<br>"); document.write(myArray[1] + "<br>"); document.write(myArray[2] + "<br>"); Near the end of the last three lines of the preceding code are the characters: + “<br>”. The + symbol is the concatenation operator—you’ll learn more about
  • 10. A - Array that when you get to letter “C”. The characters <br> (without the quotation marks) are the HTML tag for line break. Once you have copied the above code example into your .html file, saved it and loaded it in your browser, you will see the following display which shows the values that are stored in the array myArray. Place Sticker Here
  • 11. Page 11 ABCs of Programming Handbook Boolean logic gives programs the power to make decisions. It was named after the mathematician George Boole. Using Boolean logic, programs can evaluate a condition to either of the two Boolean values: true and false. For an evaluated result of true, the program will execute a specific set of program statements. For false, it will execute another set of program statements. Let’s declare and initialize a Boolean variable, myBoolean, to true in Javascript and then use myBoolean in a simple if statement. var myBoolean = true; if(myBoolean == true){ document.write("The value is true"); } See how we use two equal signs (==) in the second line of the previous code? Boolean Place Sticker Here B Place Sticker Here
  • 12. B - Boolean This is a comparison operator, used to compare two values. When you see a single equal sign, as in the first line, this is called an assignment operator. It is used to assign a value (on the right-hand side of the equal sign) to a variable (on the left-hand side.) Once you have copied the above code example into your .html file, saved it and loaded it in the browser, you should see the text “The value is true” output to the browser.
  • 13. Page 13 ABCs of Programming Handbook Concatenation is the process of joining several separate pieces together into one whole. Most languages only allow strings to be concatenated but in Javascript it is possible to concatenate values of different data types. (Note, however, that in Javascript there are a few combinations of data types that cannot be validly concatenated such as an object and a string.) The concatenation operator in Javascript is the plus sign (+) which is also the addition operator. However, Javascript can deduce from the operands whether the plus sign (+) indicates concatenation or addition. First, let’s take a look at concatenating two strings in Javascript: var myString = "Hello " + "World"; myString now contains the concatenated string: “Hello World”. Here, since both operands are strings, Javascript interprets the + sign as the concatenation operator. We can also concatenate variables: var myFirstString = "Hello "; var mySecondString = "World"; var myThirdString = myFirstString + mySecondString; myThirdString contains the concatenated string: “Hello World”. Let’s output the value of myThirdString: document.write(myThirdString); Concatenation Place Sticker Here C
  • 14. C - Concatenation In this example, we will concatenate an integer data type and a string data type var myFirstInt = 1; var myFirstString = "Hello!"; var mySecondString = myFirstInt + myFirstString; The value of mySecondString is now “1Hello!”. Since one of the operands is a string, Javascript still interprets the + operator as concatenation. Now, in the next example, we are working purely with numbers and so Javascript will interpret the + operator as addition. var myFirstInt = 1; var mySecondInt = 2; var myThirdInt = myFirstInt + mySecondInt; myThirdInt will have the value of 3. Place Sticker Here
  • 15. Page 15 ABCs of Programming Handbook Debugging is an indispensable aspect of programming. In fact, programmers tend to spend more time debugging code than writing it! Debugging is the process of locating and correcting or bypassing errors or “bugs” in programming code. Bypassing comes about when the bug can’t be corrected and so you do the next best thing which is to avoid it. The foundation of all debugging is testing—thorough and comprehensive testing. As systems are being programmed and developed, they undergo several possible levels of testing: unit, system, integration, acceptance, security, usability, and so on. The actual testing levels implemented will depend on the nature and complexity of the software being developed. More importantly, this cycle of testing is conducted repeatedly. All programs are now developed with a modular structure, allowing modules and even sub-modules to be tested in isolation (unit testing) and then as groups of modules (integration and usability testing) and then finally as a whole system (acceptance, security and system testing). An overlooked but essential aid to software testing and debugging are source code comments. While the software documentation (software design specifications printed on paper and usually held in binders) should contain all the necessary information about a system, these documents may not be currently updated and they could be misplaced or even lost. Source code comments have greater chances of being updated than paper documentation. As programmers make changes to the source code it takes little effort to update the program comments as well. Source code comments are more accessible than paper documentation and they can never be lost. In Javascript, comments look like this: //this is a comment in Javascript. Comments are ignored by the browser or system that runs the program. Here is code that has some errors in it. Try running the code to see if you can Debug Place Sticker Here D
  • 16. D - Debug find the errors: CODE TO DEBUG: var myVariable = 45; //myVariable is declared and assigned the value 45 var myOtherVariable = myVariable; // myOtherVariable is declared and assigned the value of myVariable (45). Document.write(myotherVariable); //myOtherVariable is being ‘written’ to the browser var myFirstInt = ‘4’; //myFirstInt is declared and assigned the value of ‘4’ var mySecondInt = 4; //mySecondInt is declared and assigned the value of 4 document.write(myFirstInt + mySecondInt); //myFirstInt and mySecondInt are added together (using the addition operator in this context) DEBUGGING ANSWER: document.write(myOtherVariable); //myOtherVariable was not using the correct capitalization for the word: other. Var myFirstInt = 4; //myFirstInt was assigned the value of a string (‘4’) and was actually concatenating the two values together, not adding them.
  • 17. Page 17 ABCs of Programming Handbook Exceptions are extraordinary and unexpected events and circumstances that occur during a program’s execution and cause the program to crash. Exceptions are not bugs or programming defects. A bug is an error in the code, not an event or circumstance. One common example of an exception is a missing file. Let’s say that part of a program’s logic is to access a specific file. During the first few days and weeks of the program’s production run, it has successfully accessed that file. But now, unknown to the users of the program, that file was deleted or corrupted for some reason and now the program simply freezes or terminates at the point where it is supposed to access the file. Users of the program have no idea why a program which executed flawlessly before now just freezes or terminates. Here is a situation tailor-made for the try...catch statement. Try...catch can identify the type of exception encountered, inform the user with a clear error message and then present the user with some options and then let the program continue execution, ignoring the exception if possible, or gracefully exit the program if the user so decides. In the code block of the try clause of the try...catch statement, we place the program statements where we reasonably expect an exception may occur. In our preceding example of the missing file, this is where we would place the statement which opens the file. If an exception occurs in the code block of the try clause, then program execution will jump to the code block of the catch clause. Javascript will pass an error object to the code block of the catch clause. We can make use of two (of the many) properties of this object, namely: name and message. The name property contains the name of the exception and the message property contains an error message we can display for the user. Let’s write some code that will throw an exception and handle it with a try... catch statement. We are going to call a function, myFunction, that does not exist. Exceptions Place Sticker Here E
  • 18. E - Exceptions Don’t let the simplicity of this example fool you—try-catch blocks are a very important concept in all programming languages. try{ myFunction(); } catch(error){ document.write(‘Error: ‘ + error.name + ‘<br>’); document.write(‘Error: ‘ + error.message); } Place Sticker Here
  • 19. Page 19 ABCs of Programming Handbook For Loops are a very useful and powerful construct in programming. Loops allow us to repeatedly execute a block of code while a condition exists or until a condition is met. One loop construct that exists in all programming languages is the for-loop. This loop is handy when you know exactly how many times you will execute (iterate over) a block of code and what condition(s) will keep the loop executing and what condition(s) will terminate the loop. Let’s look at the structure of the for-loop in Javascript: for(initialize; test-condition; increment){ // block of code to loop through } The logic for a for-loop is declared in its first statement within the parentheses after the for keyword. There are three statements which have been appropriately labelled initialize, test-condition and increment to denote the essential function of each statement. Note that each statement ends with a semi-colon. The initialize statement sets the starting value of the loop’s counter variable. The counter variable keeps track of the number of times the loop is executed. The test-condition statement declares the condition for the loop’s continued execution. This condition is evaluated at the beginning of each loop. If the evaluated result is true, the loop is executed. Otherwise, the loop terminates. The increment statement sets the value by which the counter variable will be incremented (which is usually 1) for every execution of the loop. This way, we always know at any time how many iterations the loop has already undergone. If we increment a variable, we add a value to that variable—usually 1. For Loops Place Sticker Here F
  • 20. F - For Loops Here is a for-loop which will iterate five times. for(var i = 0; i < 5; i++){ // any code in here will be executed 5 times! } For-loops are extremely handy when working with arrays. This is because we can loop through an array via its indexes. To get the number of storage locations in a Javascript array, we use the array’s length property, like this: myArray.length; It is important to note that the length of an array will always be 1 greater than the highest index of the array. This is because in Javascript, indexes start at 0. Therefore, an array with five storage locations (length=5) will have 4 as its highest index. It should also be noted that the length of an array does not necessarily denote the actual number of elements in the array, as some storage locations can be empty. Let’s create an array and loop through the array in Javascript: var myArray = new Array('value1', 'value2', 'value3', 'value4', 'value5'); for(var i = 0; i < myArray.length; i++){ document.write("Index " + i + " : " + myArray[i] + '<br>'); } When we increment a variable we are adding one to it’s current value.
  • 21. Page 21 ABCs of Programming Handbook Place Sticker Here
  • 22. G - Global Variable In programming, scope refers to the visibility or accessibility of a function, method, or variable. Rules of scope determine what variables and functions can be accessed by the entire script or by specific areas of the script. Let’s take a look at these lines of Javascript code: var myVariable = "Hello World"; function myFunction(){ var myLocalVar = "I am inside myFunction()"; document.write(myVariable); } document.write(myLocalVar); In the above code, we have a global variable, myVariable, which is visible to the entire script even from within the function myFunction(). On the other hand, a local variable, such as myLocalVar, which is declared within the function myFunction(), is accessible from only within myFunction(). The last line of the preceding code will cause an error. Let’s take a look at declaring a variable (locally) inside one function and then trying to access that variable from another function: function myFunction(){ var myVariable = "Hello World"; myOtherFunction(); } function myOtherFunction(){ document.write(myVariable); } Global Variable Place Sticker Here G
  • 23. Page 23 ABCs of Programming Handbook This error occurs as myVariable is not visible to myOtherFunction, as the variable is local to myFunction. One way we can quickly and conveniently test our two functions in the preceding code, is to attach either of them as an event handler to the onload event of the <body> tag of an HTML page. When an HTML page is loaded into a browser, the onload event is automatically fired and any attached event handlers (in this case either of our two functions) are automatically executed. (Please note that this is not the optimal method of using event handlers in actual production websites. We are just doing this to facilitate the testing of our functions.) This is the change to make to the body tag of your HTML page. <body onload="myFunction()"> Once we load the HTML file in the browser, we won’t see any output. Now, in Google Chrome, access the browser’s console by right-clicking inside the browser and clicking “Inspect Element” and selecting the “console” option at the bottom of the browser window. You will see the following display: Place Sticker Here
  • 24. H - HTML HTML stands for Hyper Text Markup Language. HTML was specified at the European Laboratory for High-Energy Physics (CERN) in Geneva, Switzerland as early as 1988. (A year later, the World Wide Web project was also started there.) HTML is executed by the browser and is the language used to define the structure, meaning, and content of webpages. HTML is also one of the three main technologies that are used to make dynamic, rich web content, the other two being Cascading Style Sheets (CSS), and Javascript. There have been many major and minor versions of HTML since 1988 but the more significant versions have been HTML 2.0 (1995), HTML 3.2 (1997), HTML 4.0.1 (1999), XHTML (2000), and the current version HTML 5 (2008). In a markup language, tags are used to define elements within a document. An element consists of an opening and closing tag and the text between them. In the following example, an HTML paragraph element is defined by the opening tag <p> and closing tag </p>. HTML Place Sticker Here H Place Sticker Here
  • 25. Page 25 ABCs of Programming Handbook <p>This is a one sentence paragraph of text.</p> The text between the tags is what is displayed on the browser. The tags themselves are never displayed. Another example of HTML tags are the six levels of headings, each denoted by the letter ‘h’ followed by a number between 1 and 6; a level 1 heading being the largest and a level 6 heading being the smallest. <h1>This is a level 1 heading</h1> <h3>This is a level 2 heading</h3> The site http://dev.w3.org/html5/markup/elements.html provides a comprehensive list of HTML tags.
  • 26. I - If-Else If-else statements are central to programming logic. These statements allow our scripts to make decisions and take either of several actions based on those decisions. We saw an if-statement in Javascript when discussing Boolean logic under the letter ‘B’. Now, let’s take a look at an if-else statement in Javascript: if(1 < 2){ document.write("1 is less than 2"); } else { document.write("1 is NOT less than 2"); } The above if-else statement is saying, “If 1 is less than 2, display ‘1 is less than 2’ on the webpage. Otherwise, display ‘1 is NOT less than 2’.” We can also use variables to make our if-else statements more powerful: var x = 1; var y = 2; if(x < y){ document.write(x + " is less than " + y); } else{ document.write(x + " is NOT less than " + y); } If-Else Place Sticker Here I
  • 27. Page 27 ABCs of Programming Handbook We are doing the exact same thing as the previous if-else statement, but this time we are using variables instead of literal numbers in our condition. We can then change the values that are assigned to the variables, x and y. Place Sticker Here
  • 28. J - Java Java is a powerful and popular programming language. People often confuse Java with Javascript, or assume that Javascript is Java-related, but actually the two languages are not only very different in syntax and purpose but also have separate origins and development histories. Java code is compiled into Byte Code, which is read by a Java Virtual Machine (JVM), while Javascript is an interpreted language that is executed by a browser. Let’s take a look at a simple Java program: package tv.learntoprogram.HelloWorld; public class HelloWorld{ public static void main(String[] args){ System.out.println("Hello World"); } } Java Place Sticker Here J Place Sticker Here
  • 29. Page 29 ABCs of Programming Handbook This code is saved in a file titled HelloWorld.java and it outputs “Hello World” to the console when run. We have used the NetBeans IDE to run this sample code. Every Java program requires a main method. (We will take a closer look at methods under the letter M.) The main method is the starting point of execution, meaning that the program will start with the main method. An important, fundamental concept in the Java programming language is a package. A package is simply a unique way of identifying an application and is preceded with the keyword package. Our package in the previous example is: tv.learntoprogram.helloWorld; To name our package, we use a reversedomain name, which is generally the author’s domain name in reverse. Java is a strongly typed language, meaning that each variable must have a data type. Let’s declare and initialize a variable that we will use to store an integer: int myVariable = 1; As you can see, we have declared myVariable as a whole number integer (int) and assigned it an initial value of 1. Declaring myVariable as int means that we can only store other values of type int in myVariable. If we tried to store a value of float in myVariable, or a string value, the compiler would flag a fatal error.
  • 30. K - Kilobytes A kilobyte is equal to 1000 bytes, but you may be more familiar with the number 1024. The term kilobyte uses the decimal system, compared to a kibibyte, which uses a binary prefix and has a value of 1024 bytes. In programming it is important to understand the difference between bits and bytes. A byte is comprised of eight bits, where a bit is the smallest unit of data that we can have on a computer system. A bit can only be in two states, ON or OFF. These two states are represented by the values 1 (for ON) and 0 (for OFF). You may have heard of something called binary code. Binary code is comprised of bits and 8 bits make up a byte. Binary code can be used to represent letters, symbols or even instructions for a computer system. Here is an example of binary code, for the string “hello world”: 01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100 Let’s take a look at some of the numeric data types in Java and see how much space they are allocated in memory: Numeric Data Types in Java Numeric Data Type Min to Max Values Size Allocated in Memory Byte -128 to 127 8 Bits Short -32,768 to 32,767 16 Bits Int -231 to 231 -1 32 Bits Long -263 to 263 -1 64 Bits As you can see, in Java programming it makes sense to choose the appropriate numeric data types for your variables. For example, do not choose a variable of type long to store the current ages of employees. A byte variable will do since realistically no one younger than 10 years or older than 100 years gets employed. Kilobytes Place Sticker Here K
  • 31. Page 31 ABCs of Programming Handbook Many programming languages employ code libraries, which are collections of proven, tested and bug-free code. The code in a library is in the form of functions and classes and their related constants and global variables. Programmers can call the library’s functions and create objects from its classes. Libraries are a terrific time-saver in that they save a programmer the immense effort and aggravation required to write and debug code that has already been written, debugged and packaged into a library. A very popular Javascript library is jQuery. It not only cuts down on development time but results in very compact code. For example, let’s take a look at how we would select an element in plain old Javascript: document.getElementById("div"); With jQuery, we can write this as: $("div"); This is not only compact but more readable code. There are many ways to access a library from your code. In Javascript, the most common way is to set the source attribute (src) of the script tag to the full pathname of the library’s source code file, as shown in the following line: <script src="myFile.js"></script> Let’s look at Javascript code that calls the jQuery fadeIn() method which changes the opacity of an element from hidden to visible. In the following code example, the fadeIn() method accepts a parameter of 5000 which is the number of milliseconds for the effect to last. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> Library Place Sticker Here L
  • 32. L - Library <title>ABC's of Programming</title> <script src="http://code.jquery.com/jquery- 1.10.2.min.js"> </script> <script> $(document).ready(function(){ $('#text').fadeIn(5000); }); </script> </head> <body> <p id="text" style="display:none;">This text will slowly fade in!</p> </body> </html> Place Sticker Here
  • 33. Page 33 ABCs of Programming Handbook A method is just a function that is built into an object. The function now becomes a method of the object and it can be called (invoked) by its name. The method’s format and syntax is identical to that of functions, like so: methodName(parameters) { statements } Methods are part of an object’s blueprint and are fundamental to the OOP (Object-Oriented Programming) concept. We will go through objects under the letter ‘O’. In Javascript, we use the dot operator (.) to invoke a method of an object. It looks like this: Object.methodName(); Let’s take a look at some of the fundamental methods that are part of the Math object that Javascript has to offer. The Math object is packed full of useful methods that we can use for mathematical type operations in Javascript. For example, if we needed to generate a random number, we use the random() method of the Math object: var myRandomNumber = Math.random(); document.write(myRandomNumber); If you were to run the above code in your browser, the result may surprise you. The random() method actually generates a random number between 0 and not quite 1. So, we could have a number of 0.9059727436397225. Methods Place Sticker Here M
  • 34. M - Methods In this new piece of code, we have instructed the browser to multiply the value that is generated by the random() method by 10. This should give us a new number that is between 0 and less than 10. As before, the number returned could be a decimal, for example: 1.315551579464227. So, we used the floor() method, also of the Math object, to round down this number. This would then give us a whole number between 0 and 9. Finally, we added 1 to the result to end up with a whole number between 1 and 10. Let’s fix this up and generate a number between 1 and 10: var myRandomNumber = Math.floor(Math.random() * 10) + 1; document.write("The random number is: " + myRandomNumber); Place Sticker Here
  • 35. Page 35 ABCs of Programming Handbook null is a keyword that is used in most programming languages to signify the absence of data. null is different from an empty string, the Boolean value false, or the number 0. This is because an empty string, the Boolean value false, and the number 0 all represent some form of data, whereas null represents the absence of data. null can be used in a variety of ways. For example, if we want to stop referencing an object in Java, we could nullify that object’s reference variable by setting it to null (objVariable = null). This would make the memory that the object used eligible for Java’s garbage collection memory management tool. Another use of null in a Java program is to check whether an object reference variable is actually referencing an object. If the object reference variable is referencing nothing, it is null. Let’s take a look at this in Java code: Object myObject = new Object(); // more code, maybe myObject was nullified… if(myObject == null){ null Place Sticker Here N Place Sticker Here
  • 36. N - null System.out.println("myObject is not referencing any object"); }else{ System.out.println("myObject is referencing an object"); } In this code, we have declared a variable, myObject, of type Object and assigned it an instance of Object (the ancestor of all objects in Java). We then go on to check if that object equals null, if it does equal null, that means that the object reference variable myObject no longer references any object and a message is printed to the console.
  • 37. Page 37 ABCs of Programming Handbook In programming, objects are a powerful and important concept. To understand how objects work and what they do, we need to know what a class is and what a class contains. A class is a blueprint for an object. It contains the details of the class’ properties (also called instance variables) and methods. Properties define the object’s current state or characteristics while methods define the object’s behavior. (Recall from ‘M’ that a method is just a function that is built into an object.) Let’s take a look at objects in Java and start out by defining a simple person class: package tv.learntoprogram.person; public class Person{ private int age; private String name; public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public String getName(){ return name; } } Objects Place Sticker Here O
  • 38. O - Objects Notice how the class starts with a capital letter. This is part of the Java naming convention: classes should start with a capital letter, whereas methods and variables generally start with a lower case letter. Our instance variables are age and name. (These two properties give unique characteristics to the object.) They have been marked private, which means that these variables can only be accessed from within the class where they are declared and defined. Our methods are setAge(), setName(), getAge() and getName(). These methods are marked as public, so they can be accessed outside of this class. We also need to declare the return type for a method. For setAge() and setName(), we don’t need to return any values, as we are simply setting the value for the instance variables. However, we do want to return an int and a String for the getAge() and getName() methods, respectively. You will learn more about returning a value under the letter ‘R’. As you can see, we have variables inside the parentheses for the setAge() and setName() methods. In this context, these are called parameters. When we invoke either the setAge() or setName() methods, we are expected to pass values as arguments to the parameters defined in our methods. Inside the setAge() and setName() methods we are using the keyword this, which, in this context, means this object’s age or this object’s name. When we invoke these methods, we pass in the expected values as arguments and these values are assigned to the object’s instance variables respectively (age or name). Once we have a class defined, we can then instantiate an object of that class. Instantiating an object means creating an object from its class. In Java we do this by using the keyword new: package tv.learntoprogram.person; public class Main{ public static void main(String[] args){ Person myPerson = new Person(); } } The following code would be saved in a file titled Main.java and would be inside the same package as the Person class. myPerson is actually an object
  • 39. Page 39 ABCs of Programming Handbook reference variable, meaning that it references a Person object. When we say: Person myPerson = new Person(); We are instantiating a new Person object and assigning that Person object to an object reference variable named myPerson. To set the age and name of this Person object, we invoke the setAge() and setName() methods on the myPerson object reference variable: myPerson.setAge(24); myPerson.setName("Joe"); We can then print out this Person object’s name and age: System.out.println("The person's age is: " + myPerson.getAge()); System.out.println("The person's name is: " + myPerson.getName()); Place Sticker Here
  • 40. P - Pseudocode A programming language follows strict syntax and semantics rules and coding procedures. Its main purpose is to convey instructions to a machine and actually consists more of symbols than words and sentences. It usually takes a year for a programmer to master a programming language. On the other hand, pseudocode is an informal way of describing to other persons (not to a machine) the logic and processes of a computer program. Pseudocode uses standard English grammar rules, semantics, phrases and sentences. It can be easily and immediately understood by everybody including non-programmers. Let’s take a look at the pseudocode of a simple calculator program. Begin Program While calculator running Retrieve user input If user input was not valid Output error Request user input Else if user input was valid Calculate Total Output Total Request user input Else if user input is equal to 'N' Exit Program End if End While End Program Pseudocode Place Sticker Here P As you can see here, pseudocode is not real code but it can be easily converted into the syntax of any programming language.
  • 41. Page 41 ABCs of Programming Handbook Data is stored in relational database systems to provide an organized structure and ease later retrieval. We communicate with the database via a query. To create queries, we strictly adhere to the syntax defined by the Structured Query Language (SQL) which is the standard computer language for relational database management and manipulation. (We will look at SQL under letter ‘S’). As an example, let’s assume we have a database containing a table called users. The table’s data is represented in the following grid. The users table has three records - represented by the second to the fourth row. The first row contains just labels or headings. Each record (row) corresponds to one unique user. Each record consists of three fields: username, email and user_id. The values in these fields uniquely describe a user. Put another way, no two records can have identical data in all fields. user_id username email 001 hisUserName his@address.com 002 myUserName example@example.com 003 herUserName her@address.com Now, we want to retrieve the email address of a certain user named ‘myUserName’. To do this, we compose the following query (which has to follow a strict syntax and use specific keywords): SELECT email FROM users WHERE username = ‘myUserName’; In this SQL statement, we are retrieving the email field of the record whose username field holds the value ‘myUserName’. We are retrieving this all from the users table. Query Place Sticker Here Q
  • 42. Q - Query If we run this SQL statement in phpMyAdmin (a database administration tool), we would get this result: If you look closely at the last line in the preceding screenshot, you will see example@example.com (without the quotes). This is the email address returned by phpMyAdmin corresponding to username=”myUserName”. In the preceding SQL statement above, we will replace ‘email’ with the asterisk ‘*’ which means all fields in the table. SELECT * FROM users WHERE username = ‘myUserName’; Place Sticker Here
  • 43. Page 43 ABCs of Programming Handbook In programming, many functions return a value through a return statement. Even if a programmer does not use the return statement in a function, the compiler or interpreter will program a return statement into the function that returns the null value. (We discussed null earlier, under ‘N’). Returning a value from a function can provide us either with an indication of whether a function’s operations were successful or with a value for use in the rest of the program. Let’s take a look at returning a Boolean from a function in Javascript. Consider the following code: function runTest(value){ var test = regexTest(value); if(test == true){ document.write("value matched regex"); } else{ document.write("value did not match regex"); } } function regexTest(value){ var regex = /e+/; if(regex.test(value)){ return true; } else{ return false; } } We have two functions, runTest() and regexTest(). Once we invoke the runTest() Return Place Sticker Here R
  • 44. R - Return function, the test variable is declared and the regexTest() function will be invoked, using the value argument that we pass into the runTest() function. The regexTest() function will take our argument and use the test() method to check whether it matches our regular expression, defined in variable regex. Regular expressions can be thought of as a pattern that we may want to use to check if a value matches it. The regular expression (/e+/) we have used will match one or more occurrences of the letter e. If we have a value of eeee or e passed in, our regexTest() function will return true, but if we have a value of ‘k’, our regexTest() function will return false. Once the regexTest() function has completed, our ‘test’ variable will be assigned the return value from regexTest(). The runTest() function will then write a message out to the browser, depending on whether the test variable’s value is equal to true or not. We can invoke the runTest() function by attaching an onload event to the opening <body> tag and inside the parentheses, passing in a string, like so: <body onload="runTest('eeee')"> The complete .html code would look like this: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ABC's of Programming</title> <script> function runTest(value){ var test = regexTest(value); if(test == true){ document.write("value matched regex"); } else{ document.write("value did not match regex");
  • 45. Page 45 ABCs of Programming Handbook } } function regexTest(value){ var regex = /e+/; if(regex.test(value)){ return true; } else{ return false; } } </script> </head> <body onload="runTest('eeee')"> </body> </html> The output of passing in eeee as the argument to runTest() would look like this: Place Sticker Here
  • 46. S - SQL Structured Query Language (SQL) is the standard computer language for relational database management and manipulation. SQL commands adhere to a strict syntax and vocabulary. Before we look at the syntax of SQL, let’s take a quick look at the simplified structure of a table—the major component of a database. (A database can consist of hundreds of tables.) The grid below is a simplified representation of the structure of the table website_users in the database named website. Each column signifies a specific piece of data and its data type and a row signifies a record of data. The first row in the grid is not an actual row in the table but simply holds the names of the fields of each row, namely: user_id, name, email, age. The user_id field is designated as the primary key and, as is, its value should be unique (no two records can have the same value in their user_id field). The values of the user_id field are generated by the database management system to ensure uniqueness of its values. Our sample table has three rows or three records in the table. user_id name email age 001 Jose example@example.com 24 002 Larry his@address.com 56 003 Moe her@address.com 22 Here are SQL statements to create the database website and its table website_ users. CREATE DATABASE website; USE website; CREATE TABLE website_users( SQL Place Sticker Here S
  • 47. Page 47 ABCs of Programming Handbook user_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), age INT, PRIMARY KEY(user_id) ); In the preceding SQL statements, the CREATE DATABASE statement creates an empty database. The USE statement allows access to it. Then, the CREATE TABLE statement creates the table website_users and defines the table’s fields, in particular, the names and data types of the fields. The primary key field, user_id, is going to contain numbers, so it is declared as type INT. It is set to NOT NULL so that it always has a value. It is also set to AUTO_INCREMENT so that a unique value for it is generated. These are all characteristics of a table’s primary key. The last clause of the CREATE TABLE statement sets the field user_id as the primary key of the table. The name and email columns have a data type of VARCHAR (variable character field) with a maximum length of 255 characters. Numbers and text can be stored in these fields as well as special characters. The age field would also contain a numeric value. To insert data into this example database, we use the following SQL statement: INSERT INTO website_users(name, email, age) VALUES("Joe", "example@example.com", 24); The INSERT INTO statement adds values to the fields of a record, in effect, adding a new record. We indicate the names of the fields (name, email, age), which will accept the new values and then we list the values themselves(“Joe”, “example@example.com”, 24)in the same order that we listed the fields.
  • 48. S - SQL If we were to display the content of our database, which at this point contains only the first record, it would look something like this: Place Sticker Here
  • 49. Page 49 ABCs of Programming Handbook The ternary if-statement lets us rewrite a simple if-else-statement with single line code blocks into one compact statement. First, let’s examine a Javascript if- else-statement. var result = false; if(9 < 10){ result = true; } else{ result = false; } We have initialized a variable result to the Boolean value false. Then, we evaluate a conditional ( 9 < 10 ) which will definitely return the Boolean value true. Thus, the variable result will be assigned the Boolean value true. Now, the previous if-else-statement can be written as the following equivalent one-line ternary if-statement: var result = (9 < 10)? true: false; The same logic and therefore the same results are obtained from this one-line ternary if-statement as in the six-line if-else-statement. Let’s take a closer look at the ternary if-statement syntax: var myVariable = (condition)? true : false; The condition is evaluated, if it is true, the code following the question mark is executed (the Boolean value true gets assigned to myVariable). If the condition is not true, then the code following the colon is executed (the Boolean value true gets assigned to myVariable). Of course, if your if-else-statement has multiple lines in the if and else code blocks, then you cannot rewrite that if-else-statement as a ternary if statement. Ternary If Place Sticker Here T
  • 50. U - UML UML (Unified Modeling Language) is a modeling language in the field of software engineering that has been standardized by the Object Management Group (ISO/IEC19501:2005) and is used by developers to specify, visualize, construct and document software components. UML has become the de-facto standard for building Object-Oriented software. In terms of OOP (Object-Oriented Programming), a basic UML diagram can be broken down into three sections: Name of the Class, State (Instance Variables) and Behavior (Methods). Let’s take a look at the basic layout of a UML diagram: If we think about a computer in terms of OOP, that is we consider a computer as an object with properties and behavior, we need to consider two things: what state could the computer be in, and what would its behavior be? For example, a very simplified computer object model could be in either of two states: on or off, and, correspondingly, it would be capable of two behaviors or methods: turnOn() and turnOff(). Let’s take a look at this computer class in a UML diagram: UML Place Sticker Here U Computer isOn: Boolean isOn: Boolean turnOn(): void turnOn(): void Class Name instanceVariable: Data Type instanceVariable: Data Type methodName(): Return Type methodName(): Return Type
  • 51. Page 51 ABCs of Programming Handbook After we have designed our class using a UML diagram, turning that diagram into working code is a straightforward task. In Java, our Computer class would look like this: package tv.learntoprogram.computer; public class Computer{ private Boolean isOn = false; private Boolean isOff = true; public void turnOn(){ if(isOff == true){ isOn = true; isOff = false; } else{ System.out.println("Computer was already on."); } } public void turnoff(){ if(isOn == true){ isOn = false; isOff = true; } else{ System.out.println("Computer was already off."); } } }
  • 52. V - Variable Variables are portions of a computer’s memory. To distinguish these memory locations from one another, variables are assigned names. A variable can hold different data types such as a whole number (int), a decimal number (float), a string (a series of characters), or a Boolean (true or false). Some programming languages, such as Java, are strongly typed, meaning that the variable must be declared to hold a specific data type and only that data type. Other languages such as Javascript are loosely typed, meaning that no variable type declaration is required and any variable can store any data type. If we declare a variable in Java, we would say: int myNumber = 2; In Javascript, we would say: var myNumber = 2; In Javascript we could then reassign the value of myNumber to something like a string: myNumber = " String of Characters"; But if we tried to do this in Java, the compiler would flag our error and would not produce an executable format of our program, making it impossible to run. The Java compiler does this because Java is a strongly typed language. In Variable Place Sticker Here V Place Sticker Here
  • 53. Page 53 ABCs of Programming Handbook Java, once you have declared a variable to be of a certain data type, it can only store values of that data type. Strongly typed languages are very helpful. As you have seen in Javascript, which is not a strongly typed language, we can change the data type of a variable simply by assigning it a new value of a different data type. This is sometimes the cause of unexpected behavior in a program and it can often take a while to identify the source of the problem. With strongly typed languages, we do not have this problem—this is because we cannot change the data type of a variable.
  • 54. W - While Loop We explained for-loops under “F”. A for-loop is best used when you know how many times you want to execute a block of code. If you don’t, then you can use another loop construct, called the while-loop. A while-loop starts with a condition. The condition is checked and if it evaluates to true then the first iteration proceeds. Just before the second and subsequent iterations, the condition is checked again and as long as it is true, the loop will continue executing. But once the condition evaluates to false, the loop exits. Let’s take a look at a simple while-loop in Javascript: var i = 1; while(i < 5){ document.write("Iteration Number: " + i + "<br>"); i++; } This loop will iterate four times and generate the following output. Note that for each iteration, we increment the variable i. If we do not do this, then the program will execute the loop indefinitely. While Loop Place Sticker Here W Place Sticker Here
  • 55. Page 55 ABCs of Programming Handbook XML (eXtensible Markup Language) is a markup language designed to transport and store data. In contrast, HTML (which we covered in ‘H’) is a markup language designed to display data. XML documents begin with a XML declaration, much like the doctype declaration in HTML: <?xml version="1.0"?> An XML document must contain a root element. From this root element, child and sub-child elements can be used to describe specific data contained within the XML file. Let’s take a look at a simple XML document with a root element, several child elements, and a few sub-child elements: <?xml version="1.0"?> <shop> <item> <category>Electronics</category> <title>Laptop</title> <model>Satellite</model> <brand>Toshiba</brand> </item> <item> <category>Electronics </category> <title>iMac</title> <model>Late '09</model> <brand>Apple</brand> </item> <item> XML Place Sticker Here X
  • 56. X -XML <category>Appliance</category> <title>Fridge</title> <model>F200</model> <brand>Fridges-R-US</brand> </item> <item> <category>Electronics</category> <title>iPad</title> <model>Mini</model> <brand>Apple</brand> </item> </shop> The <shop> element is our root element and the <item> elements are the child elements of <shop>. The <category>, <title>, <model> and <brand> elements are the child elements of <item> and are considered sub child elements. If you were to save the above XML into a file (for example, we’ll call our file shop.xml) and load it in your browser, it would look very strange. This is because XML is generally used to store data for use in web services, not for presenting data to the end user. The element names in a XML document are created by the author. For example, the element names we have used above (<brand>, <model> and so on) are in no way standardized or part of a recommendation. However, keep in mind that the names that you give your XML elements should describe the contents of that element.
  • 57. Page 57 ABCs of Programming Handbook Place Sticker Here
  • 58. Y - YottaByte A YottaByte is an extremely large amount of data. In order to put this huge amount of data into context, let’s take a look at a comparison of the main data amounts and get a rough idea of what we would need to store these various data amounts: Various data amounts Data Amount: Example Storage: 1 Yottabyte = 1000 Zettabytes We would need 1 Trillion 1 Terabyte Hard Drives to store 1 Yottabyte of Data. 1 Zettabyte = 1000 Exabytes We would need 1 Billion 1 Terabyte Hard Drives to store 1 Zettabyte of data. 1 Exabyte = 1000 Petabytes We would need 1 Billion 1 Gigabyte Hard Drives to store 1 Exabyte of data. 1 Petabyte = 1000 Terabytes We would need 1 Million 1 Gigabyte Hard Drives to store 1 Petabyte of data. 1 Terabyte = 1000 Gigabytes We would need approximately 213 4.7GB DVD’s to store 1 Terabyte of data. 1 Gigabyte = 1000 Megabytes We would need around 1 Thousand 3 ½ “ Floppy Disks to store 1 Gigabyte of data. 1 Megabyte = 1000 Kilobytes We could store 1.44 Megabytes on a single 3 ½ “ Floppy Disk. 1 Kilobyte = 1000 Bytes We could store approximately 5 copies of the latest Uncompressed jQuery Javascript Library (276KB) on a single 3 ½ “ Floppy Disk. As you can see, a Yottabyte is a huge amount of data and it is very unlikely that any one organization would ever have enough data to fill this giant space. YottaByte Place Sticker Here Y
  • 59. Page 59 ABCs of Programming Handbook In HTML, elements have a stacking order. This means that elements whose position property are assigned either the values absolute, relative, or fixed will always appear in the order in which they were created. (In CSS, the default value of the position property is static.) With the help of CSS (Cascading Style Sheets), we can actually manipulate this stacking order and choose which elements appear on top and the order of the elements underneath the top element. Z-index is a CSS property that sets the stack order of specific elements. Consider this simple HTML file, which includes some simple CSS used to style the elements on the page: <!DOCTYPE html> <html> <head> <meta charset=”UTF-8”> <title>ABC’s of Programming</title> <style> div{ height: 200px; width: 200px; position: absolute; } #div1{ top:0; left:0; background-color: blue; } Z-index Place Sticker Here Z
  • 60. Z - Z-index #div2{ top:40px; left:40px; background-color: black; } #div3{ top:20px; left:20px; background-color: pink; } </style> </head> <body> <div id=”div1”></div> <div id=”div2”></div> <div id=”div3”></div> </body> </html>
  • 61. Page 61 ABCs of Programming Handbook Place Sticker Here If we load this HTML in our browser, we will see that the pink element (#div3) is in front of the other elements:
  • 62. Z - Z-index Let’s change the stacking order of these elements using the z-index property. By setting the z-index property to 1 we force the blue element (#div1) to the front. #div1{ top:0; left:0; background-color: blue; z-index:1; } Place Sticker Here
  • 63. Page 63 ABCs of Programming Handbook Other LearnToProgram Books: CSS Development (with CSS3!) by Zachary Kingston Python for Beginners by Alex Bowers Javascript for Beginners by Mark Lassoff HTML & CSS for Beginners by Mark Lassoff Availiable for Print or Kindle https://learntoprogram.tv/books#