Sa
le
sS
am
pl
e
About the Book This coding book is supplementary to the main “Mel n Conji” content book. This book represents a 21st-century approach to learning coding concepts and developing computational thinking and problem-solving skills. To prepare students for the digital age, the curriculum is interwoven with well-thought-out concept graduation with real-life examples and practice problems.
Special Features • Illustrative approach: Concepts in coding and computer science are delivered through pictorial representations and learner-friendly approaches. • Learning through real-life examples: Age-appropriate examples that enable learners to relate to the concept and learn about the unknown from the known. • Extensive practice: Multiple practice scenarios to reinforce learnings. • Coding challenges: Includes projects through which learners can demonstrate their learning outcomes in coding and computer science.
About Uolo Uolo partners with K-12 schools to bring technology-based learning programs. We believe pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. Uolo is trusted by over 10,000 schools across India, South East Asia, and the Middle East.
Singapore
|
Gurugram
CS_CB_Coding_ICSE_Grade8_Cover.indd All Pages
|
Bengaluru
|
hello@uolo.com `xxx
© 2024 Uolo EdTech Pvt. Ltd. All rights reserved.
NEP 2020 based
|
ICSE compliant
|
Technology powered
06/11/23 4:29 PM
ICSE Computer Science
Computer Science
Java II Web Development III
Book 1.indb 1
11/6/2023 8:42:16 PM
Contents Java 1
Fundamentals of Java
1
What Is Programming? What Is Java?
Why Learn Java?
Execution of a Java Program Tokens in Java
Structure of a Java Program Syntax
Data Types Variables
Operators 2 Conditional Statements in Java
19
User Inputs Conditions
3 Loops in Java
32
Introduction to Loops Jump Statements
Web Development 4 Introduction to HTML
39
What Is HTML?
Basics of HTML
Basic Tags of HTML
Understanding CSS
ii
Book 1.indb 2
11/6/2023 8:42:16 PM
Adding Images Creating Links Adding Audio Adding Video 5 JavaScript
54
What Is JavaScript?
Writing First Program Using JavaScript Fundamentals of JavaScript
Conditional Statements in JavaScript 6 HTML Forms
66
What Are HTML Forms? Form Structure
Creating and Displaying a Form Form Attributes
Form Validation
Setting Properties of a Form Using Internal CSS
iii
Book 1.indb 3
11/6/2023 8:42:16 PM
1
Fundamentals of Java
Computers are incredible and powerful machines. Today, they are everywhere, be it a shop, a bank, a school, government offices, or malls. But they don’t do anything without our instructions. They are helpful, but deep down, they are not smart. The instructions we give to a computer are sets of commands to perform a task; these sets are collectively referred to as a program.
What Is Programming? Programming is the process of creating a set of instructions that tells a computer how to perform a task. A task is a piece of work to be done. In a program, it may represent a section of the program. We need a language to instruct computers to carry out a task, just as we use English to communicate with one another. As computers are machines, they can only understand machine language. As machines are electrically powered devices, they listen to two signals, on and off, which are represented by 0s and 1s, respectively.
Low-Level Language A language that is formed using 0s and 1s is called a low-level language (LLL). As it is based on only two digits, it is also known as a binary language.
High-Level Language A high-level language (HLL) is a human-friendly programming language like Java, Python, C, or C++. It is intended to make computer programming simpler for programmers, as it is not feasible for programmers to remember the 0 and 1 codes for everything. Later, these high-level language programs are translated into low-level language programs to make computers understand them.
What Is Java? Java is a widely used programming language and software platform that runs on billions of devices, including notebook computers, mobile devices, gaming consoles, medical devices, and many others. It is used to develop mobile apps, web apps, desktop apps, games, and much more. Any hardware or software environment in which a program runs is known as a platform. As Java has a runtime environment (JRE) and an application programming interface (API), it is called a platform.
Did You Know? Java was developed by Sun Microsystems (which is now a part of Oracle) in 1995. James Gosling is known as the father of Java.
1
Book 1.indb 1
11/6/2023 8:42:17 PM
Why Learn Java? Below are the reasons why we should learn Java: 1
Java is based on the “Write Once, Run Anywhere” principle, which makes it a platform-independent language.
2
Java is beginner-friendly and gives you a competitive edge, as it is one of the leading programming languages in the industry.
3
Java has strong memory management, which makes it robust.
4
Java takes less execution time, as it is a compiled language.
5
Java is secure and dynamic.
6
Java is used on a large scale around the world, covering many sectors.
7
Java offers a variety of job roles, expanding career options such as software developer, web developer and application developer.
Execution of a Java Program Java is a high-level language, so any program written in it must first undergo a two-step conversion to a machinelevel language. Any Java program is initially translated into bytecode, a type of machine-independent code. This bytecode is then executed on a machine-specific Java Virtual Machine (JVM).
Using a Compiler A compiler is a computer program that converts high-level program instructions into machine language. This program reads the source code, decodes it instruction by instruction into machine language, and then provides a machine-independent Java file that can run on any machine, like Windows, MacOS, and Android, with the help of a JVM. Some of the commonly used Java compilers are javac (an official Java compiler), the GNU Compiler for Java (GCJ), the Eclipse Compiler for Java (ECJ), and Jikes.
The JVM acts as a run-time engine to run Java applications. It runs the Java code. It provides a runtime environment in which Java bytecode (a compiled Java program) can be executed. JVMs are available for platforms like Windows, MacOS, and Android So, the Java compiler first compiles the program into machine-independent bytecode, which is then executed by the JVM, a machine-dependent platform, to produce the final output.
Compile Time Java Source Code
Compiler
Java Byte Code
Java Virtual Machine Native Machine Code
Just-In-Time (JIT) Compiler Run Time
2
Book 1.indb 2
11/6/2023 8:42:17 PM
Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) is a programming paradigm that is widely used in Java and many other programming languages. In Java, OOP is based on the following core principles: Objects: In OOP, everything is treated as an object. An object is a self-contained unit that represents a real-world entity or concept and contains both data (attributes) and the methods (functions) that operate on that data. Objects are instances of classes. Classes: A class is a blueprint or template for creating objects. A class defines the structure and behaviour of objects. In Java, classes are used to create objects by defining their attributes and methods. Consider a real-world scenario of a factory producing cars. Think of the Car class as a blueprint or template for manufacturing cars in a factory. This blueprint defines what each car should have and how they should behave. In the class, you specify attributes (Make, Model, Year) and methods (Start, Stop) that all cars produced from this factory should possess. Using the prototype of a car, you can create many objects that possess the attributes and methods of the Car class.
Car Class Attributes: Make Model Year
Methods: Start Stop
Car 1
Car 2
Car 3
Car 4
Advantages of OOPs 1
OOP is faster and easier.
2
OOP gives the programmes a clear structure.
3
OOP helps keep the code easier to maintain, modify, and debug.
4
OOP makes it possible to create fully reusable applications with less code and a shorter development time.
Tokens in Java Java tokens are the smallest elements of a Java program. These are the basic building blocks, which can be put together to make a program. Java tokens can be identifiers, keywords, constants, punctuators, or operators (like +, *).
Identifiers An identifier is any name assigned to various components of a Java program. Identifiers are used to name classes, methods, and variables. Identifiers can be short names, like x and y, or more descriptive names, like age, sum, Chapter 1 • Fundamentals of Java
Book 1.indb 3
3
11/6/2023 8:42:17 PM
choice, or result. It is better to use descriptive names in order to make your programs easy to understand and maintain.
Keywords Keywords are reserved words in Java that have a special meaning and can only be used for that purpose. We cannot use keywords to name any variable, class, or method in Java, as doing so will show an error. A few keywords in Java are public, static, void, class, int, float, char, if, while, for, etc.
Constants They are the fixed values that do not change during the execution of a program. Constants can be numeric constants or character constants. Numeric Constants: 12, -5, 2334, -786, 1.55, 0.756, etc. Character Constants: They can be single character constants, like “P”, “a”, and “B”, or multicharacter (string) constants, like “Uolo”, and “Welcome”.
Punctuators Punctuators are the symbols used to separate other tokens. They are also known as separators. There are 9 punctuators in Java which are ; , . ( ) { } [ ].
Structure of a Java Program In Java, we write programs using classes and objects. A typical structure of a Java program includes the following: 1
Documentation statement
2
Class Definition statement
3
Main method
Documentation //Program to print “Hello World!”. class Welcome{
public static void main (String args[]) {
Class Definition
System.out.printIn(“Hello, Java!”);
{ }
The main Method
Let us understand the meaning of each part in detail.
Documentation Statement We start a Java program with a documentation statement that tells what the program is about. We use comments to add documentation about a program. A comment is a line of code that is ignored by the Java compiler.
4
Book 1.indb 4
11/6/2023 8:42:17 PM
In Java, we have three types of comments:
• Single-line comment • Multi-line comment • Documentation comment
Single-line comments are added using a pair of forward slashes (//). A multi-line comment starts with /* and ends with */. A documentation comment starts with /** and ends with */.
Class Definition In the example above, we have created the class named Welcome. We call this statement a class definition. The opening curly braces at the end of the line indicate the start of the class.
The main() Method Inside the class, we have the main method, which is the execution point of the program when we run it. A Java program must have a main method else it will not execute. The name of the program should be the same as the name of the class which has the main method. Here, the class Welcome has the main method, so the name of the program should be Welcome.java. A main method can be public, static, and void. public: It indicates that the main method can be called from anywhere outside or inside the class. Calling a method is nothing but asking Java to execute the program written inside a method. static: It indicates that the main method will remain the same in all the objects that are created from the class. For example, let us say we create the objects Welcome1, Welcome2, and Welcome3 from the class Welcome, the main method will remain the same in all the three objects, that is, it will have only one instruction (line 3) inside it. void: It indicates that the main method will not return any result other than executing the instruction present inside it. The open curly bracket at the end indicates the beginning of the main method. The instruction System.out.println() is a print instruction in Java that will display the message written inside the parentheses, which is “Hello, Java!” We end an instruction with a semicolon at the end. The first closing curly bracket indicates the end of the method, and the second closing curly bracket indicates the end of the class. A Java compiler will convert this Welcome.java program into Welcome.class, which will be the bytecode. Then, a JVM will execute the main method inside this Welcome.class bytecode, where it will run the System.out.println() statement to display the message, “Hello, Java!” Welcome.java
Output
//Program to print “Hello, Java!”
Hello, Java!
class Welcome{
public static void main(String[] args) {
}
}
System.out.println(“Hello, Java!”);
Chapter 1 • Fundamentals of Java
Book 1.indb 5
5
11/6/2023 8:42:18 PM
Example 1.1 Program to display names. Names.java
Output
//Program to print “Hello, Java!”
My name is John.
class Names{
public static void main(String[] args) {
}
}
My best friend’s name is Adam.
System.out.println(“My name is John.”);
System.out.println(“My best friend’s name is Adam.”);
Example 1.2 Program to print the sum of two numbers. Sum.java
Output
class Sum{
50
public static void main(String[] args){
}
}
System.out.println(24 + 26);
In Examples 1.1 and 1.2, the + operator is used to concatenate strings and add two numbers, respectively. You will learn more about operators later in this chapter. Example 1.3 Program to display two messages in a single line. Welcome.java
Output
class Welcome{
Welcome to the world of Java!Hope you are having fun!
public static void main(String[] args){
System.out.print(“Welcome to the world of Java!”);
}
}
System.out.print(“Hope you are having fun!”);
Whenever we display a message using the method System.out.println(), it first displays the message in the output then moves the cursor in the output to a new line. That is why, in Example 1.1 on the previous page, the messages are displayed in two separate lines. But the method System.out.print() does not move the cursor to a new line and that is why in Example 1.3, the messages are displayed in the same line.
6
Book 1.indb 6
11/6/2023 8:42:18 PM
Example 1.4 Program to display the product of two numbers. Product.java
Output
class Product{
30 x 50 = 1500
public static void main(String[] args){
}
}
System.out.println(“30 x 50 = “ + 30 * 50);
Example 1.5 Program to calculate the area of a rectangle whose width is 5 and height is 10. Area.java
Output
public class Area{
Area of rectangle = 50
public static void main(String[] args){
}
}
System.out.print(“Area of rectangle = “ + 5 * 10);
Syntax Syntax refers to the set of rules defining how a program should be written. Every programming language has its own syntax. Similarly, the syntax of Java also defines all the main rules, commands, and constructions to write programs that the Java compiler understands. A few of the syntax rules in Java are:
• Every Java code has to be written inside a class, as it is one of the main principles of object-oriented programming that Java strictly follows.
• The main() method should be defined inside a class. • In Java, we end all the instructions with a semicolon (;). That is, each individual statement should be
ended with a semicolon. It informs the compiler where an instruction ends and the next instruction begins.
• Java is case-sensitive, which means the names “showData” and “showdata” are two different names. Syntax Error
Syntax errors are mistakes in the code, such as spelling mistakes and punctuation errors. It indicates that the programmer has written an invalid statement. If the program contains any syntax errors, the compiler will display them after compiling it. Two common types of syntax errors are:
• Missing double quotes in print statements
Chapter 1 • Fundamentals of Java
Book 1.indb 7
Think and Tell Do you think knowing syntax is required for learning every language?
7
11/6/2023 8:42:18 PM
Main.java
Output
class Main{
/tmp/cGx28261UN/Main.java:3: error: ’)’ expected
public static void main(String[] args){ System.out.println(Hello!);
}
}
ᴧ
System.out.print(Hello!);
1 error
• Missing the semicolon symbol at the end of any instruction. Main.java
Output
public class Main
/tmp/cGx28261UN/Main.java:3: error: ’;’ expected
{
public static void main(String[] args) {
}
}
System.out.println(“Hello”)
System.out.print (“Hello!”) 1 error
ᴧ
Data Types Data types allow us to define what type of data a memory location can hold. The main data types in Java are as follows: Data Type Size
Description
byte
1 byte
Stores whole numbers from -128 to 127.
short
2 bytes
Stores whole numbers from -32,768 to 32,767.
int
4 bytes
Stores whole numbers from -2,147,483,648 to 2,147,483,647.
long
8 bytes
Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
float
4 bytes
Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits.
double
8 bytes
Stores fractional numbers. Sufficient for storing 15 decimal digits.
boolean
1 bit
Stores true or false values.
char
2 bytes
Stores a single character/letter or ASCII values.
Apart from these data types, one more commonly used data type is String. It helps us store multiple characters in a variable, like “John”, “4 kilograms”, and “$ 50”.
Variables A variable is a memory location on a computer which can hold any value and can also change over time, as needed.
8
Book 1.indb 8
11/6/2023 8:42:18 PM
To understand it in an easy way, think of it like a box in which you can store a number and later can replace that number with another number.
Variable Value Variable Value
In simple words, variables are names given to the memory location where your value is stored.
5
The figure below illustrates three variables with their respective values. The three variables used in the figure are “name”, “winner” , and “score”. The variable “name” holds the value “Bob”, the variable “winner” holds the value “True”, and the variable “score” holds the value “35”. Therefore, whenever the variable “name” is used in a program, this variable refers directly to its value, “Bob”.
num num
Variable Name
Variable Name
Declaring a Variable Declaring a variable means creating a variable. If we want to use a variable in Java, we need to create it in advance. To create or declare a variable, we need to specify the data type of the variable along with the variable name. A data type refers to the type of value the variable is going to hold. Syntax: <data type> <variable name>;
Data type
int
Variable name
count
;
Semicolon
Say, we want to create a variable to store a count. As the value of count will be a number, we use the keyword int, which means integer (a non-decimal number), to declare the type of the variable, and we can use count as the name of the variable. Examples String name; int count;
String is the data type used if the value of the variable stores characters or words within it. The data type is int if the variable is used to store an integer value. In the example above, the variable “name” should hold characters or words within it and the variable “count” should hold an integer value.
Variable Initialisation Initialising a variable means assigning a value to the declared variable for the first time. The syntax for initialising a variable is as follows. Chapter 1 • Fundamentals of Java
Book 1.indb 9
9
11/6/2023 8:42:18 PM
Syntax: <data type> <variable name> = <value>;
Data type Variable name int
count = 4
;
Semicolon
Initial value Initialisation of the variable includes the following three components: Data type
:
Type of data the variable will store.
Variable name
:
Name of the memory location where the value will be stored.
Initial Value
:
The value the variable will be initialised with.
Example int x; x=10;
In the above example, the first line, “int x”, is declaring the variable and specifying that the value stored in the variable is of the integer type. The second line, “x = 10”, gives the initial value to the variable x, which is of data type int.
Therefore, whenever the variable x is used in the program, it refers to the value stored within it, which is 10. Example 1.6 Program to store number 5 in a variable and display it. Main.java
Output
class Main{
Number is 5
public static void main(String[] args){ int number;
number = 5;
}
}
System.out.println(“Number is “ + number);
In the program above, we have initialised the number variable with 5 in line 3, and in line 4, we display the value of the variable using the print instruction. We can group Java variables into the following categories, based on the data types we learnt:
• String variables • Integer variables • Float variables • Character variables • Boolean
:
Store letters and numbers within double quotes.
:
Store numbers without decimal values.
:
Store numbers with decimal values.
:
Store a single character such as “a” or “b”.
:
Stores only true or false values.
10
Book 1.indb 10
11/6/2023 8:42:18 PM
Example 1.7 Program to store three numbers 5, 6, and 10 in different variables and display the sum of the numbers. Sum.java
Output
class Sum1{
Sum is 21
public static void main(String[] args){
int number1, number2, number3; number1 = 5; number2 = 6;
number3 = 10;
int sum = number1 + number2 + number3; System.out.println(“Sum is “ + sum);
}
}
System.out.println(“Number is “ + number);
In the above program, three integer variables number1, number2, and number3 are declared in line 3. In lines 4, 5, and 6, the variables are initialised with their respective values using assignment statements. Then, the sum is calculated in line 7 and line 8 displays the sum.
Scope of Variables In Java, the scope of a variable is defined as its visibility or accessibility within a class, method, or block of code. The variables declared inside a block or method are not visible or accessible outside it. If you try to do so, you will get a compilation error.
Types of Variables Based on their scope, the following are the types of variables in Java: 1
Local
2
Instance
3
Static
Local Variable A variable that is defined and created within a method, constructor, or function in Java is called a local variable. These variables are created when the function or method is created and destroyed after the control comes out of the block. Therefore, the scope of the local variable lies within the function or method for which it has been created. The variable cannot be used outside the block it has been initialised to. Example 1.8 Example.java
Output
class example{
Local Variable 10
public static void main(String[] args){ int var = 10;
}
}
System.out.println(“Local Variable “ + var);
Chapter 1 • Fundamentals of Java
Book 1.indb 11
11
11/6/2023 8:42:18 PM
Instance Variable A variable declared inside a class but outside the body of methods is called an instance variable. It is not declared static. Example 1.9 Simple.java
Output
class Simple{
10
10.0
public static void main(String[] args){ int a = 10;
float f = a;
System.out.println(a);
}
}
System.out.println(f);
Static Variable A variable that is declared static is called a static variable. It cannot be local. You can create a single copy of a static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded into memory.
Naming Variables The general rules for naming a variable in Java are:
• Names can contain letters, digits, underscores, and dollar signs. • Names must not begin with a number. • Names cannot contain blank spaces. • Names are case sensitive, so “myVar” and “myvar” are two different names in Java. • Java keywords, such as int or boolean, cannot be used as names. • Names in Java can be of any length. • Variable names can also begin with $ and _.
A few examples of valid variable names are count, name, _num, num1, num_1, $name, etc. However, names like 1num, tile count, and value #1 are invalid variable names. Example 1.10 Main.java
Output
class Main{
/tmp/cGx2826UN/Main.java:3: error: not a statement
public static void main(String[] args){
}
}
int 1num = 5;
int 1num = 5; ᴧ
/tmp/cGx2826UN/Main.java:3: error: ‘;’ expected int 1num = 5;
2 errors
ᴧ
12
Book 1.indb 12
11/6/2023 8:42:19 PM
Camel Case When we have two or more distinct words in a variable name, we can write them without spaces in between and capitalise the first letter of each new word.
first word lower case
For example: “Name of the company” can be written as “nameOfTheCompany”. As this represents the camel’s hump, we call it Camel-case.
camelCase
capitalise the first letter of all the following words
Example 1.11 Program to store whole numbers in byte, short, int, and long variables. Main.java
Output
class Main{
A byte-sized number is 64
public static void main(String[] args){ byte number1 = 64;
System.out.println(“A byte-sized number is “ + number1); short number2 = 32000;
A short-sized number is 32000
A int-sized number is -2010097456 A long-sized number is 1956789034264578326
System.out.println(“A short-sized number is “ + number2); int number3 = -2010097456;
System.out.println(“A int-sized number is “ + number3); long number4 = 1956789034264578326L;
}
}
System.out.println(“A long-sized number is “ + number4);
Example 1.12 A Java program to store decimal numbers in float and double variables. Main.java class Main{
public static void main(String[] args){ float number1 = 645.6743f;
System.out.println(“A float-sized decimal number is “ + number1);
A float-sized decimal number is 645.6743
A double-sized decimal number is 3229.006538971
double number2 = 3229.006538971d;
}
}
System.out.println(“A double-sized decimal number is “ + number2);
Chapter 1 • Fundamentals of Java
Book 1.indb 13
13
11/6/2023 8:42:19 PM
Example 1.13 A Java program to store your name in a variable and display it in the output. Main.java
Output
class Main{
My name is John
public static void main(String[] args){ String name = “John”;
}
}
System.out.println(“My name is “ + name);
Operators Operators are special symbols that are used to perform calculations. We can use operators with variables and constants to form expressions.
Unary Operators These operators work on a single variable or constant. They are used to increase or decrease the value stored in a variable by 1. Operator
Name
Description
Example
++
Increment
Increases the value of a variable by 1.
++x
--
Decrement
Decreases the value of a variable by 1.
--x
Arithmetic Operators Arithmetic operators in Java are used along with the integer or float values and variables to perform mathematical operations on them. Operator
Name
Description
Example
+
Addition
Adds two values together.
x+y
-
Subtraction
Subtracts one value from another.
x-y
*
Multiplication
Multiplies two values.
x*y
/
Division
Divides one value by another.
x/y
%
Modulus
Returns the remainder.
x%y
Comparison Operators They are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The result of a comparison is either true or false. Operator
Name
Example
==
Equal to
x == y
!=
Not equal
x != y
>
Greater than
x>y
14
Book 1.indb 14
11/6/2023 8:42:19 PM
Operator
Name
Example
<
Less than
x<y
>=
Greater than or equal to
x >= y
<=
Less than or equal to
x <= y
Logical Operators They are used to compare the result of two or more expressions in Java and give the result as true or false. Operator
Name
Description
Example
&&
Logical and
Returns true if both statements are true.
x < 5 && x < 10
||
Logical or
Returns true if one of the statements is true.
x < 5 || x < 4
!
Logical not
Reverse the result, returns false if the result is true.
!(x < 5 && x < 10)
BEDMAS Rule Java performs the following operations in order to solve a mathematical expression: 1
Brackets (B)
2
Exponents (E)
3
Division (D)
4
Multiplication (M)
5
Addition (A)
6
Subtraction (S)
Example 9 + 7 * (8 − 4) / 2 − 3 =9+7*4/2−3
(First, the brackets are solved.)
= 9 +7 * 2 − 3
(Then, division is solved.)
= 9 + 14 − 3
(Then, multiplication is solved.)
= 23 − 3
(Then, addition is solved.)
= 20
(Finally, subtraction is solved.)
Example 1.14 Program to calculate the area and perimeter of a square with the side as 5. Main.java
Output
class Main{
Area: 25
public static void main(String[] args){ int side = 5;
Perimeter: 20
int area = side * side;
int perimeter = 4 * side;
System.out.println(“Area: “ + area);
}
}
System.out.println(“Perimeter: “ + perimeter);
Chapter 1 • Fundamentals of Java
Book 1.indb 15
15
11/6/2023 8:42:19 PM
Example 1.15 Program to show the difference between using a unary operator before and after a variable. Main.java
Output
class Main{
Value of num1++ is 5 Value of num1 is 6
public static void main(String[] args){ int num1 = 5;
Value of ++num2 is 6
System.out.println(“Value of num1++ is “ + num1++); System.out.println(“Value of num1 is “ + num1); System.out.println(); int num2 = 5;
}
}
System.out.println(“Value of ++num2 is “ + ++num2);
In the above program, when num1++ is used, Java first displays the value of num1 and then increases its value by 1. So, line 5 displays 5 as num1 is 5, then Java increases the value of num1 to 6 (5 + 1) and displays the new value in line 6. However, when ++num2 is used, Java first increases the value by 1 and then displays the value of num2. So in line 10, Java increases num2 to 6 (5 + 1) and displays the new value.
Chapter Checkup A
Fill in the Blanks. logical
Hints
instance
arithmetic
1
In Java, a
2
A variable that is associated with an instance of a class is called a/an
3
The scope of a local variable is limited to the
5
block of code
is a blueprint for creating objects. variable.
in which it is declared.
operators perform mathematical operations in Java.
4
B
class
In Java, the “&&” operator is an example of a/an
operator.
Tick () the Correct Option. 1
Which keyword is used to create a class in Java?
a
define
b
class
c
create
d
make
16
Book 1.indb 16
11/6/2023 8:42:19 PM
2
What type of variable is declared with a static keyword in Java?
a
Local variable
b
Instance variable
c
Static variable
d
Dynamic variable
3
The == operator in Java is an example of a:
a
Arithmetic operator
b
Comparison operator
c
Logical operator
d
Assignment operator
4
Which of the following symbols is used to end the statement in a Java program?
a
;
b
:
c
||
d
*
C
Who Am I? 1
I’m a programming construct used to create objects from a class in Java. What am I?
2
I’m a type of variable in Java that is declared using the static keyword. What am I?
3
I’m an operator in Java that is used for comparing values. What am I?
4
I’m a logical operator in Java that returns true if both statements are true. What am I?
5
I’m a type of operator that work with a single variable. What am I?
D
E
Write T for True and F for False. 1
Local variables have a class-wide scope.
2
An instance variable is associated with a specific instance of a class.
3
The scope of a static variable is limited to a specific method.
4
The “!=” operator is a logical operator.
5
Java supports object-oriented programming (OOP) principles.
Answer the Following. 1
Explain the difference between a local variable and an instance variable in terms of scope.
Chapter 1 • Fundamentals of Java
Book 1.indb 17
17
11/6/2023 8:42:19 PM
2
List three types of arithmetic operators in Java and provide an example of each.
3
Describe the purpose of the variables in Java.
4
Provide an example of a relational operator in Java and explain its use.
5
How do logical operators like && and || help in decision-making in Java?
F
Apply Your Learning. 1
Create a Java class called “Person” with instance variables for name, age, and address.
2 Write the main method for the “Person” class in question 2 that calculates the birth year based on the current year and age. 3 Implement a Java program that uses the “Person” class in question 2 to create two person objects, set their attributes, and calculate their birth years. 4
Compare the birth years of the two persons in question 3, using a relational operator and print the result.
5 Write a Java program that demonstrates the use of logical operators in making decisions based on the age and address of the two persons created in question 3.
18
Book 1.indb 18
11/6/2023 8:42:20 PM
2
Conditional Statements in Java
User Inputs To get input from a user, we have to use the Scanner class. The Scanner class can be imported from the java.util package, as shown below.
To use any of the Scanner class methods, we must first create an object of the class. Below is an example of how to create and use an object of the Scanner class to call a method from the class.
You can choose a name for the object. When the object is created, you can use any method from the Scanner class for the input data type. The table below shows the methods used to read various input values. Method
Description
nextBoolean()
Reads a boolean value from the user.
nextByte()
Reads a byte value from the user.
nextDouble()
Reads a double value from the user.
nextFloat()
Reads a float value from the user.
nextInt()
Reads an int value from the user.
nextLine()
Reads a string value from the user.
nextLong()
Reads a long value from the user.
nextShort()
Reads a short value from the user.
19
Book 1.indb 19
11/6/2023 8:42:20 PM
Example 2.1 Program to read your name as input and print it. Main.java
Output
import java.util.Scanner;
Enter your name
class Main{
public static void main(String[] args){
Scanner myObj = new Scanner(System.in);
Amita
Username is: Amita
String Name;
System.out.println(“Enter your name “); Name = myObj.nextLine();
}
}
System.out.println(“Username is: “ + Name);
Example 2.2 Program to read the name, age, and salary of an employee and print it. Main.java
Output
import java.util.Scanner;
Enter name, age and salary:
class Main{
public static void main(String[] args){
Scanner myObj = new Scanner(System.in);
System.out.println(“Enter name, age and salary:”); String name = myObj.nextLine(); int age = myObj.nextInt();
double salary = myObj.nextDouble();
Amita 36
85000
Name: Amita Age: 36
Salary: 85000.0
System.out.println(“Name: “ + name); System.out.println(“Age: “ + age);
}
}
System.out.println(“Salary: “ + salary);
Conditions Consider a real-life scenario where you are cycling and suddenly a puppy runs in front of you. What would you do? You will surely stop cycling. However, you would have kept going if the puppy hadn’t crossed you. This is how we make decisions in real life.
Decision Statement The decision statement in Java allows you to make a decision based on the outcome of a condition.
20
Book 1.indb 20
11/6/2023 8:42:20 PM
Generally, a Java program runs the code in sequence. But we can control the order in which the program executes and run specific code based on the outcome of a condition. This is accomplished through the use of control flow statements, such as the if-else statement. Control flow statements allow us to specify a set of instructions that should be executed only if certain conditions are met. Start
Condition
True
False Code
Think and Tell How does Java decide which branch of code to execute when using an if-else statement?
End
In this chapter, we will learn the following control flow statements for decisionmaking in Java:
• If statement • If-else statements • Nested-if statements • If-else-if statements If Statement
The if statement is used to execute a statement or a block of statements only when the given condition becomes true. Consider a scenario where you need to check if someone is eligible to vote or not. How would you know if someone is eligible to vote? One can vote if he or she is 18 or older. Right! Chapter 2 • Conditional Statements in Java
Book 1.indb 21
21
11/6/2023 8:42:20 PM
Syntax: if (condition) {
//Task to be performed if the condition becomes true.
}
condition
keyword
opening braces
if (Age>= 18) { System.out.println(”Eligible to Vote!”); closing braces
} Statement(s) that will execute only when the condition is true
If the condition becomes true, only then the statements inside the block will be executed; otherwise. The control goes to the next statement after the closing braces. Example 2.3 A program to check which of the two variables, x or y, has the greater value. Main.java
Output
class Main{
x is greater than y
public static void main(String[] args){ int x = 20; int y = 18; if(x > y) {
}
}
}
System.out.println(“x is greater than y”);
Did You Know?
Java also provides a shorthand version of the “if-else” statement known as the ternary conditional operator (?:). It allows you to write a simple if-else statement in a single line.
22
Book 1.indb 22
11/6/2023 8:42:20 PM
Example 2.4 A program to check whether the number is even. Main.java
Output
class Main{
The number is even
public static void main(String[] args){ int number = 100; if(number % 2 == 0) { System.out.println(“The number is even”); } } }
The if-else Statement The if-else statement has two sets of code to be executed, whether the given condition is true or false. Let us consider the example of eligibility to vote again to understand how if-else works. Take a look at the flowchart below. If the condition is met, the person is eligible to vote; otherwise, the person is not eligible to vote.
If Age>=18
False False
Not Eligible to Vote
True True
Discuss
What is the difference between if and if-else statements?
Eligible to Vote
Syntax: if (condition) { }
else{ }
//Task to be performed if the condition becomes true.
//Task to be performed if the condition becomes false.
Chapter 2 • Conditional Statements in Java
Book 1.indb 23
23
11/6/2023 8:42:21 PM
condition
Statement(s) to be executed when the condition is true
if (Age>= 18) { System.out.println(”Eligible to Vote!”); } keyword
else { System.out.println(”Not eligible to Vote!”); } Statement(s) to be executed when the condition is false
If the condition becomes true, then the statements inside the if block will be executed; otherwise, the statements inside the else block will be executed. Example 2.5 A program to print “Good day” if the time is before 18 else print “Good evening”. Main.java
Output
class Main{
Good evening.
public static void main(String[] args){ int time = 20;
if(time < 18) { }
System.out.println(“Good day.”);
else{
}
}
}
System.out.println(“Good evening.”);
Example 2.6 A program to check whether a number is even or odd. Main.java
Output
class Main{
The number is odd
public static void main(String[] args){ int number = 99;
if(number%2 == 0) {
System.out.println(“The number is even”);
24
Book 1.indb 24
11/6/2023 8:42:21 PM
Main.java
Output
}
else{
}
}
}
System.out.println(“The number is odd”);
Nested If Statement “Nest” means within. In Java, an “if statement” is referred to as being “nested” if it is stated inside another “if statement” or an “if-else statement”. In fact, there is no limit to how deep a nest can go. Nested if statements are common in Java programming.
False
True
if b > c
b is the Largest number
True
if a > b
False
False
c is the Largest number
if a > c
True
a is the Largest number
Syntax: if (condition1) { if (condition2) { //Task to be performed if condition1 and condition2 becomes true. else { //Task to be performed if condition1 is true but condition2 is false. } } else{ if(condition 3) { //Task to be performed if condition1 becomes false but condition 3 is true. }
Chapter 2 • Conditional Statements in Java
Book 1.indb 25
25
11/6/2023 8:42:21 PM
else { //Task to be performed if condition1 and condition 3 is false. }
}
Nested if block if (a>c) { if (a>c) { System.out.printIn(“a is the largest number”);
} else { System.out.println(“c is the largest number”); } } } else{ if (a>c) { if (b>c) { System.out.println(“b is the largest number”); } else { System.out.println(“c is the largest number”); }
Outer if block
Outer else block
Assume that a = 30, b = 12, and c = -15. First, the outer if condition is examined. The control goes to the nested if block as the outer if condition is true. Now that the nested-if condition has been checked and found to be true as well, the output is “30 is the largest number”. Example 2.7 A program to check the largest of three numbers. Main.java
Output
import java.util.Scanner;
Enter the values for a, b, and c: 10
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner (System.in);
20 30
The largest number is: 30
26
Book 1.indb 26
11/6/2023 8:42:21 PM
Main.java
Output
System.out.printIn(“Enter the values for a, b, and c”); int a = myObj.nextInt();
int b = myObj.nextInt();
int c = myObj.nextInt();
if(a>b)
{
if(a>c) {
System.out.printIn(“The largest number is:” + a); }
else {
System.out.println(“The largest number is:” + c);
}
else {
if (b>c) {
System.out.println(“The largest number is:” + b);
}
else {
System.out.println(“The largest number is:” + c);
}
}
}
Example 2.8 A program to check the values of a and b. Main.java
Output
public class Main{
a is 10 and b is 20
public static void main(string[]args) {
int a=10;
int b=20;
if(a==10)
{
if(b==20) {
System.out.println(“a is 10 and b is 20”); }
Chapter 2 • Conditional Statements in Java
Book 1.indb 27
27
11/6/2023 8:42:21 PM
Main.java
Output
else {
System.out.println(“a is 10 and b is not 20”); }
}
}
The If-Else-If Ladder An addition to the if-else statement is the if-else-if ladder statement. It is used in situations where multiple cases need to be checked. If one of the conditions in an if-else-if ladder statement is true, the statements defined in the if block will be executed. If some other condition is true, the statements defined in the else-if block will be executed. Eventually, the statements defined in the else block will be executed if none of the conditions are true. Several else-if blocks are possible. If none of the conditions match, the default statement is executed. Let’s look at the example below to understand better.
time < 10
True
Good morning
False time < 18 False
True
Good day
Good evening
Code after outermost if-else block
Syntax: if (condition1) { //Task to be performed if condition1 becomes true. } else if (condition2) { //Task to be performed if condition1 becomes false and condition2 becomes true. } else{ //Task to be performed if condition1 and condition2 both become false. } }
28
Book 1.indb 28
11/6/2023 8:42:21 PM
if (time<10)
{ System.out.println(”Good morning.”);
Outer if-else block
} else
if (time<18)
{ System.out.println(”Good day .”); }
Inner if-else block
else {
System.out.println(”Good evening.”); {
if-else-if ladder Example 2.9 A program to print “Good Morning”, “Good Day”, and “Good Evening”, depending on the time. Main.java
Output
class Main{
Good evening.
public static void main(String[] args){ int time = 22;
if(time < 10) {
System.out.println(“Good morning.”);
} else if (time < 18){
System.out.println(“Good day.”);
}else {
}
}
}
System.out.println(“Good evening.”);
Example 2.10 A program to check the value of a variable. Main.java
Output
class Main{
i is greater than or equal to 30
public static void main(String[] args){ int i = 30;
Chapter 2 • Conditional Statements in Java
Book 1.indb 29
Statement(s) after if-else-if ladder
29
11/6/2023 8:42:21 PM
Main.java
Output
if(i < 10) {
System.out.println(“i is less than 10”);
} else if (i < 20){
System.out.println(“i is less than 20”);
} else if (i < 30){
System.out.println(“i is less than 30”);
} else { }
}
}
System.out.println(“i is greater than or equal to 30”);
System.out.println(“Statement(s) after if-else-if ladder”);
Chapter Checkup A
Fill in the Blanks. Hints 1 2 3
nextLine()
object
nested
To get input from a user, we have to use the
else
Scanner
class.
method reads a string value from the user. A ‘if’ statement is referred to as being
if it is stated inside another ‘if’ statement.
4 In the if-else-if ladder statements, if none of the conditions is true, then the statements defined in the block will be executed. 5 B
To use any of the Scanner class methods, we must first create a/an
of the class.
Write T for True and F for False. 1
Several else-if blocks are possible in Java.
2
If-else statements is an example of control flow statements.
3
In the if-else statement, if the condition is true, then the statements inside the else block are executed.
4
The Scanner class can be imported from the java.util package.
5
The nextBoolean() method reads a boolean value from the user.
30
Book 1.indb 30
11/6/2023 8:42:21 PM
C
Answer the Following. 1
What do you mean by nested-if statements?
2
Name the types of control flow statements that can be used in Java.
3
Differentiate between the if and if…else statements.
4
What are if-else-if ladder statements?
5
Describe the following methods used in Java.
a
nextLong():
b
nextFloat():
c
nextInt():
D
Apply Your Learning. 1
Write a program to check whether a student has passed the exam or not.
2 Write a program to assign a number within 1, 2, and 3 to a variable and print it in words, as per the integer assigned. 3
Write a program to check whether 2023 will be a leap year or not.
4
Write a program to input a number and check whether a number is greater than 10, using the if statement.
5 Write a program that prompts a user for the lengths of the three sides of a triangle and determines whether the triangle is scalene, isosceles, or equilateral. 6
Write a program in Java to determine if a number is divisible by 15.
Chapter 2 • Conditional Statements in Java
Book 1.indb 31
31
11/6/2023 8:42:21 PM
31
Loops in Java
Introduction to Loops In programming, a loop executes a set of instructions until a termination condition is reached. Loops are also known as iterative statements. In real life, we usually play our favourite songs on a loop. Here, the word loop represents playing that favourite song repeatedly.
Favourite Song
In programming, we can run a statement multiple times using a loop. Let’s say we want to print “hello” 10 times. This can be done in two ways: 1 Write the print statement 10 times. 2 Write the print statement once and put it in a loop to run 10 times. Of course, the second alternative is always more convenient because it means we have to write less code. There are three iteration statements in Java. 1 while
Think and Tell
2 do-while
What is the concept of loop control variable in loops?
3 for In this chapter, we will learn about the while and for loops.
While Loop A while loop repeats a statement or a block of statements as long as the looping condition remains true.
32
Book 1.indb 32
11/6/2023 8:42:22 PM
Syntax: //variable initialization while (condition) { //body of the loop //increment/decrement statement }
condition variable initialization
body of loop
int i=10; keyword
while
(i>1) { System.out.println(i); i--;
} decrement The condition can be an expression which returns a boolean value, i.e., true/false. The body of the loop will run as long as the condition is true. When the condition returns false, the loop terminates. We can skip the curly brackets if the body of the loop contains only one line. Example 3.1 Program to print first 10 natural numbers, using a while loop. Example1.java
Output
class Example1{
1
public static void main(String[] args){ // The variable i acts as the counter. //i counts the number of times the loop has executed int i = 1; while(i <= 10) { System.out.println(i);
Chapter 3 • Loops in Java
Book 1.indb 33
2 3 4 5 6 7 8
33
11/6/2023 8:42:22 PM
Example1.java //increases i by 1 after each loop }
i++;
Output 9
10
}
}
Example 3.2 Program to print the odd numbers between 1 to 10. Example2.java
Output
class Example2{
1
public static void main(String[] args){ // The variable i acts as the counter.
//i counts the number of times the loop has executed int i = 1;
while(i <= 10) {
3 5 7 9
System.out.println(i); //increases i by 2 after each loop
// this can also be written as i = i + 2 }
i += 2;
}
}
For Loop A for loop needs a loop control variable, which acts as the counter. Syntax: for(initialization;condition;increment/decrement){ //body of the loop } Observe that there are three sections inside the parentheses, separated by semicolons. 1 The initialisation section runs when the loop starts. This section sets the initial value of the loop control variable. 2 In a termination condition, the loop runs as long as the condition is true. 3 The last portion is an expression that increments or decrements the loop control variable.
34
Book 1.indb 34
11/6/2023 8:42:22 PM
For every iteration, the condition is checked. If the condition is true, the body of the loop is executed. Then, the loop control variable is incremented/decremented. This is repeated until the condition returns false. An iteration is one pass of a loop. Example 3.3 Program to print first 10 natural numbers, using a for loop. Example3.java
Output
class Example3 {
1 2
public static void main(String[] args) { initialization for ( int i = 1; 1 < = 10; 1++) }
}
}
}
increment condition
System.out.println(i);
3 4 5 6 7 8 9
10
Example 3.4 Program to find the factorial of a number. Example4.java
Output
class Example4{
Factorial of 4:24
public static void main(String[] args){
// number to calculate the factorial int num = 4;
//fact variable will hold the result. //it must be initiated to 1 int fact = 1;
for(int i = 1; i <= num; i++) { }
}
}
fact = fact * i;
System.out.println(“Factorial of “+num+” : “+fact);
Chapter 3 • Loops in Java
Book 1.indb 35
35
11/6/2023 8:42:22 PM
Jump Statements Jump statements are control statements that transfer control of the execution of a program from one place to another. There are two jump statements in Java: break and continue.
The Break Statement The break statement is used to exit a loop. Syntax: break; Example 3.5 Consider the program that we wrote to print the first 10 natural numbers. Let’s add a break statement in this program. Example5.java
Output
class Example5{
1
public static void main(String[] args){
// for loop to print first 10 natural numbers for(int i = 1; i <= 10; i++) {
if(i==7) {
}
}
}
}
2 3 4 5 6
//exits the loop if i is equal to 7 break;
System.out.println(i);
In this program, the for loop runs until the condition i==7 is met. When i==7 is true, the break statement is executed and the loop is exited.
The Continue Statement The continue statement is used to skip a particular iteration. Syntax: continue; Example 3.6 Consider the program that we wrote to print the first 10 natural numbers. Let’s add a continue statement to this program.
Did You Know? Java’s “break” statement is used to exit a loop prematurely, while the “continue” statement skips the current iteration and proceeds to the next one.
36
Book 1.indb 36
11/6/2023 8:42:22 PM
Example6.java
Output
class Example6{ public static void main(String[] args){ // for loop to print first 10 natural numbers
1 2 3 4 5 6 8 9 10
}
}
for(int i = 1; i <= 10; i++) { if(i==7) { //skips the iteration if i is equal to 7 continue; } System.out.println(i); }
In this program, the for loop runs until the condition i==7 is met. When i==7 is true, the continue statement stops running the statements inside the loop for that iteration. The loop resumes from the next iteration.
Chapter Checkup A
Fill in the Blanks. Hints
loop
break
condition
loop control variable
Jump
statements are control statements that transfer control of the execution of a program from one 1 place to another. 2 A/An
executes a set of instructions until a termination condition is reached.
3 The
statement is used to exit a loop.
4 A for loop needs a/an
that acts as a counter.
5 The body of the while loop will run only until the B
Write T for True and F for False. 1
The condition of a while loop is an expression that returns a boolean value.
2
Loops are also known as iterative statements.
3
The continue statement is a type of jump statement.
4
The break statement is used to skip a particular iteration.
5
A for loop has two sections within parentheses separated by a semicolon.
Chapter 3 • Loops in Java
Book 1.indb 37
is true.
37
11/6/2023 8:42:22 PM
C
Answer the Following. 1
What are iterative statements? Name the three types of iterative statements.
2
Differentiate between the while and for loops.
3
What are jump statements?
4
Differentiate between the break statement and the continue statement.
5
Explain the structure of a for loop.
D
Apply Your Learning. 1
Write a program to find the sum of the following series: 1 + 4 + 7 + . . . . . . + 28.
2
Write a program to print even numbers between 1 and 20, using a for loop.
3
Write a program to print first 10 terms of the following series, using a while loop: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
4
Find the sum of odd numbers from 1 to 50, using a while loop.
5
Write a program to check if a number is prime, using a for loop.
6 Write a program that prints the multiplication table of a given number, using a for loop. For example, if the number is 5, the output should be:
5X1=5
5 X 2 = 10
.
.
.
5 X 10 = 50
38
Book 1.indb 38
11/6/2023 8:42:23 PM
4
Introduction to HTML
What Is HTML? HTML stands for HyperText Markup Language. HTML is a markup language used to design web pages. It defines the structure of a web page and tells the web browser how and where to display the content of the web page. A web page is a document placed on the World Wide Web (WWW) as a part of a website. The term ‘hypertext’ is a combination of two words ‘hyper,’ which means beyond, and ‘text,’ which means written words. The main goal of hypertext is to go beyond the linear reading process and navigate to the desired location on the web with the help of interconnected web pages. The term ‘markup language’ refers to a language which creates layout of web pages and applies formatting on them. It makes the objects on the web page like text, image, audio, etc. more interactive, and it also enriches the look and feel of the web pages. To create a web page in HTML, you need two main things:
• A Text Editor: Text editor is software used to write the code of HTML documents. Some of the popular text editors are Notepad, Notepad++, Sublime Text, etc.
• A Web Browser: A web browser is used to access and view web
pages. Examples of web browsers are Google Chrome, Apple Safari, Microsoft Edge, Opera, Mozilla Firefox, etc.
Did You Know?
The first web page was developed by Tim BernersLee, a British scientist, in 1991.
Basics of HTML An HTML document consists of HTML tags, elements, and attributes.
Tags A tag is a basic building block of an HTML document that specifies how the content is displayed on the web page. HTML provides several built-in tags. Each of these tags has a specific purpose. For example, the <p> tag is used to create a paragraph in a web page. Each tag has a name which is enclosed in angle brackets < and >. For example, <html>, <body>, <hr>, etc., are some tags in HTML. Most of the tags in HTML have opening and closing tags. Opening tag is the name of the tag enclosed in the angle brackets. Whereas, the closing tag has forward slash in the beginning of the tag name and enclosed in angle brackets. For example, <html> is the opening tag. </html> is the closing tag. The effect of a tag is restricted only to its closing tag. Between opening and closing tags, content is placed.
39
Book 1.indb 39
11/6/2023 8:42:23 PM
Elements The combination of opening tag, content and closing tag is known as element. For example, the paragraph element is as follows: <p> I am a paragraph. </p> There are two types of elements in HTML which are as follows:
• Container Elements: Container elements contain other elements or text within them. They have both an opening tag and a closing tag to enclose their content.
Examples: <html></html>, <head></head>, <body></body>.
• Empty Elements: Empty elements, also known as void elements or self-closing elements, do not contain any content. They do not require a closing tag. Examples: <br>, <hr>, <img>.
Attribute An attribute provides additional information about an HTML element and modifies its behaviour. Attributes are always placed inside the opening tags of HTML elements. The syntax to add an attribute is as follows: <element attribute=”value”>Content</element> Where,
• Element: The HTML element to which the attribute belongs. • Attribute: The name of the attribute. • Value: The value assigned to the attribute.
Did You Know? Multiple attributes can be used in an element.
For example,
<p align = “right”> I am a paragraph with right alignment </p> Here, align is the attribute of <p> element.
Think and Tell How are tags and attributes different?
Structure of An HTML Document
The structure of an HTML document is divided into two main parts: the head and the body. <html> <head> <title> Title of the Web page</title> </head>
Head
<body> Body of the web page </body>
Body
</html> The head contains information about the document, such as the title. The title appears on the title bar or tab of the web browser. The body contains the content of the web page, such as text, images, and videos. The content of the body is displayed in the browser window.
40
Book 1.indb 40
11/6/2023 8:42:23 PM
HTML document structure has four tags to describe the document structure, which are as follows: 1
The <html> and </html> tags enclose the entire document.
2
The <head> and </head> tags enclose the head section of the document.
3
The <title> and </title> tags enclose the title of the document.
4
The <body> and </body> tags enclose the body section of the document.
Basic Tags of HTML Some of the basic tags of HTML are as follows: Tag
Description
Example
<h1> to <h6> Used to create headings and subheadings on <h1> Heading 1 </h1> a web page. <h1> is the biggest heading and <h2> Heading 2 </h2> <h6> is the lowest heading <h3> Heading 3 </h3> <h4> Heading 4 </h4> <h5> Heading 5 </h5>
Output
Heading 1 Heading 2 Heading 3 Heading 4 Heading 5
<h6> Heading 6 </h6>
Heading 6
<sub>
Used to raise the text below the baseline
H2<sub>2</sub>O
H2O
<sup>
Used to raise the text above the baseline
A<sup>2</sup>
A2
<b>
Used to make the text bold
<b> Bold </b>
Bold
<i>
Used to make the text italic
<i> Italic </i>
Italic
<em>
Used to emphasise text
<em> Emphasised </em>
Emphasised
<a>
Used to create a hyperlink
<a href = ”www.google.com”> Home Home </a>
<p>
Used to create a paragraph
<p> I am a paragraph </p>
I am a paragraph
Example 4.1
Let’s create a web page using some of these tags. Code <html>
<head> <title> Text Formatting Example </title> </head> <body>
<h1> Welcome to My Web Page </h1>
<p> This is a simple paragraph with some <em> emphasised </em> text. We can also use superscript and subscript: </p> <p> The chemical formula for water is H<sub>2</sub>O, and the famous equation is E = mc<sup>2</sup>. </p>
<p> Feel free to explore the content on this page. Thank you for visiting! </p> </body> </html>
Chapter 4 • Introduction to HTML
Book 1.indb 41
41
11/6/2023 8:42:23 PM
Output
Welcome to My Web Page This is a simple paragraph with some emphasised text. We can also use superscript and subscript. The chemical formula for water is H 0, and the famous equation is E = mc2. 2 Feel free to explore the content on this page. Thank you for visiting!
Do It Yourself 4A 1
Write any three examples of container elements of HTML.
2
Write the name of the tag used for: a
Making the text bold
b
Making a paragraph
c
Making the text italic
Understanding CSS Cascading Style Sheets (CSS) is a language used to style the HTML elements. It allows us to change the look and feel of the web pages.
Selectors CSS uses selectors to target HTML elements. Selectors can target elements by tag name, class, ID, attribute, and more. For example, body {
font-family: sans-serif;
}
background-color: blue;
.highlight { }
color: red;
Here, .highlight is the class selector which can be used in HTML tag with the help of the class attribute.
Properties and Values CSS is used in a property-value pair. The colon (:) sign is used to separate the property from a value. CSS properties define the styles that are to be applied to the selected elements, and values specify the settings for those properties. For example,
p{
font-size: 24px;
}
color: #333333;
42
Book 1.indb 42
11/6/2023 8:42:23 PM
There are several properties of CSS. Let us discuss some of them in the following table: Property
Description
Example
color
Sets the colour of the text.
color: blue
background-color
Sets the background colour of the HTML element. background-color: red
font-family
Sets the font family of the text.
font-family: cambria
font-size
Sets the size of the text.
font-size: xx-small
font-weight
Sets the weight or thickness of the text.
font-weight: bold
padding
Sets the space around the content of the element. padding: 40px
margin
Sets the space around the element itself.
margin: 20px
border
Specifies the border around the element.
border: 2px
border-radius
Specifies the radius of the corners of the element border-radius: 5px border.
opacity
Specifies the transparency of the element.
opacity: 50
text-align
Aligns the text horizontally within a box.
text-align: centre
box-sizing
Controls how the sizing of an element is box-sizing: border-box calculated. There are two possible values for this property: content-box and border-box.
Note: x-small, small, medium, large, x-large, xx-large can also be used as values. Note: lighter, or any number can also be used
How to Use CSS in a Web Page CSS can be used in three ways in a web page which are as follows: 1
Inline CSS: It allows us to apply style to a particular element on a web page with the help of the style attribute. For example, <p style=”color: red; font-size: 15px;”>This is a paragraph</p>
2
Internal CSS: It allows us to apply style to the whole web page with the help of <style> element. <head> <style> p{ color: red; font-size: 15px; } </style> </head> <body> <p>This is a paragraph </p> <p>This is another paragraph </p> </body>
Chapter 4 • Introduction to HTML
Book 1.indb 43
43
11/6/2023 8:42:24 PM
3
External CSS: It allows us to style multiple pages with the help of <link> element. <head> <link rel=”stylesheet” href=”style.css”> </head> <body> <p>This is a paragraph </p> </body> The style.css file would contain the following CSS: p{ color: red; font-size: 15px; }
Example 4.2
Let us use some of these CSS properties, that we have learnt in the previous section, in the following web page: Code
<html> <head> <title> Text Formatting Example </title> <style> body{ background-color:lightgreen; } h1{ color: red; } </style> </head> <body> <h1> Welcome to My Web Page </h1> <p> This is a simple paragraph with some <em>emphasised</em> text. We can also use superscript and subscript: </p> <p> The chemical formula for water is H<sub>2</sub>O, and the famous equation is E = mc<sup>2</sup>. </p> <p> Feel free to explore the content on this page. Thank you for visiting! </p> </body> </html> Output
Welcome to My Web Page This is a simple paragraph with some emphasised text. We can also use superscript and subscript. The chemical formula for water is H 0, and the famous equation is E = mc2. 2 Feel free to explore the content on this page. Thank you for visiting!
Here, in this web page, the background colour is changed and the colour of the heading is also changed.
44
Book 1.indb 44
11/6/2023 8:42:24 PM
Adding Images The <img> tag of HTML allows us to add images to the web page. The attributes of the <img> tag are as follows: Attribute
Description
Alt
Used to specify the alternate text which appears only if the specified image is not loaded due to some reason.
Height
Used to specify the height of the image.
Src
Used to specify the path of the image.
Width
Used to specify the width of the image.
Apart from src, all attributes are optional to use with the <img> tag. Height and width of the image can also be set with the height and width properties of CSS. Example 4.3
Let us create a web page to display images of famous Indian mathematicians with information about them: Code <html> <head> <title>Famous Indian Mathematicians</title> <style> body { font-family: sans-serif; margin: 0; padding: 0; box-sizing: border-box; } h1 { background-color: lightgreen; color: green; text-align: center; padding: 1em; } .main { display: flex; justify-content: space-around; flex-wrap: wrap; padding: 20px; } .mathematician-card { border: 1px solid #ddd; border-radius: 8px; margin: 10px; padding: 15px; width: 300px; box-shadow: 0 4px 8px; } Chapter 4 • Introduction to HTML
Book 1.indb 45
45
11/6/2023 8:42:24 PM
Code .mathematician-card img { max-width: 100%;
}
border-radius: 4px;
</style>
</head> <body>
<h1>Famous Indian Mathematicians</h1> <div class = “main”>
<div class=”mathematician-card”>
<img src=”ramanujan.jpg” alt=”Srinivasa Ramanujan”> <h2>Srinivasa Ramanujan</h2>
<p>Contributions: Number Theory, Mathematical Analysis</p>
</div>
<div class=”mathematician-card”>
<img src=”shakuntala-devi.jpg” alt=”Shakuntala Devi”> <h2>Shakuntala Devi</h2>
<p>Contributions: Mental Calculation, Author of Mathematics Books</p>
</div>
<div class=”mathematician-card”>
<img src=”abhay-ashtekar.jpg” alt=”Abhay Ashtekar”> <h2>Abhay Ashtekar</h2>
<p>Contributions: Quantum Gravity, Loop Quantum Gravity</p>
</div>
</div>
</body> </html>
Output
Srinivasa Ramanujan
Shakuntala Devi
Contribution: Number Theory, Mathematical Analysis
Contribution: Mental Calulation, Author of Mathematics Books
Abhay Ashtekar Contribution: Quantum Gravity, Loop, Quantum Gravity
While creating this web page, place the images with the same names at the same location where the web page is saved.
46
Book 1.indb 46
11/6/2023 8:42:24 PM
Creating Links The <a> tag is used to create links in HTML. A link, also known as hyperlink, is a text with the functionality to navigate you to some other web page of the website. The <a> tag is also known as anchor tag. This tag helps us to interlink several web pages of a website, even we can link other websites too. The attributes of the <a> tag are as follows: Attribute
Description
href
It takes the URL of the web page that will open when the link is clicked.
download
It allows a file to download when the link is clicked. It does not take any value.
We can arrange the links with the help of <nav> tag. The <nav> tag allows us to create a set of links. Example 4.4
Let us create a navigation bar with the help of <a> and <nav> tags. Code <html> <head> <title>Home Page</title> <style> h1 { background-color: purple; color: white; text-align: center; padding: 1em; } nav { background-color: grey; overflow: hidden; } nav a { float: left; display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } nav a:hover { background-color: olive; color: white; } </style> </head> <body> <h1>Navigation</h1> <nav> Chapter 4 • Introduction to HTML
Book 1.indb 47
47
11/6/2023 8:42:24 PM
Code <a href=”https://uolo.com/index.html”>Home</a> <a href=”https://uolo.com/about-us.html”>About Us</a> <a href=”https://uolo.com/request-demo.html”>Contact</a> </nav> </body> </html> Output
When we hover over the links, the colour of the background of the link is changed.
Do It Yourself 4B 1
Write one or two lines of code for the following: a
To embed ‘flower.jpg’ image on a web page
b
To create a link with the text ‘Flower’ for downloading ‘flower.jpg’ image
2
Write the CSS code to set the border of an image as 10px.
Adding Audio HTML provides the <audio> tag to insert audio files to a web page. The <source> tag is used with the <audio> tag to specify the path of the audio file. There can be more than one <source> tag inside the <audio> tag. The browser chooses any one <source> tag at a time. Currently HTML supports MP3, WAV, and OGG audio formats.
48
Book 1.indb 48
11/6/2023 8:42:24 PM
Attributes of the <audio> tag are as follows: Attribute
Description
Autoplay
It specifies that the audio will start playing as soon as the web is loaded in the web browser.
Controls
It specifies that audio controls should be displayed (such as a play/pause button etc).
Loop
It specifies that the audio will start over again, every time it is completed.
Muted
It specifies that the audio output should be muted.
Src
It specifies the URL of the audio file.
Except src attribute, all attributes do not take any value. They are simply written in the opening tag. Example 4.5
Let’s create a web page to add audio file: Code
Output
<html> <head> <title> Adding Audio </title> </head> <body> <h1>Let’s Play Music</h1> <audio controls loop> <source src=”music.mp3”> </audio> </body> </html> The audio file is added to the web page with controls. You can pause the audio, increase/decrease the volume of sound, forward/reverse audio, etc.
Adding Video Similar to audio, HTML allows us to add video to a web page using the <video> tag. The <source> tag is used with the <video> tag to specify the path of the video file. There can be more than one <source> tag inside the <video> tag. The browser chooses any one <source> tag at a time. Currently HTML supports MP4, WebM, and OGG video formats. The attributes of the <video> tag are as follows: Attribute
Description
autoplay
It specifies that the video will start playing as soon as the web is loaded in the web browser.
controls
It specifies that video controls should be displayed (such as a play/pause button etc).
height
It specifies the height of the video player.
loop
It specifies that the video will start over again, every time it is completed.
muted
It specifies that the audio output of the video should be muted.
src
It specifies the URL of the video file.
width
It specifies the width of the video player.
Chapter 4 • Introduction to HTML
Book 1.indb 49
49
11/6/2023 8:42:25 PM
Except src, height, and width attributes, all attributes do not take any value. They are simply written in the opening tag. Example 4.6
Let’s create a web page to add a video: Code
Output
<html>
Let’s Play Video
<head> <style> video {
border: 5px groove darkblue; padding: 30px; width: auto;
height: auto;
}
</style>
<title> Adding Video </title> </head> <body>
<h1>Let’s Play Video</h1> <video controls>
<source src=”video.mp4”>
</video> </body> </html>
The video is displayed on the web page. You can pause the video, increase/decrease the volume of sound, forward/reverse the video, view the video on full screen, etc.
Discuss
What will happen if the specified audio/video is not found at the specified path?
Do It Yourself 4C 1
Match the following. A
2
B
CSS
Sets the background colour of the HTML element.
background-color
Aligns the text horizontally within a box.
margin
Allows us to change the look and feel of the web pages.
text-align
Sets the space around the element itself.
Write the names of any three attributes of the <audio> tag.
50
Book 1.indb 50
11/6/2023 8:42:25 PM
Coding Challenge
Take photos of any four national symbols of India and create a web page to display them. The name of each national symbol should appear at the top of the photo. Photos should work as hyperlinks, and when the user clicks on any photo, a web page appears containing the larger photo of it.
Chapter Checkup A
Fill in the Blanks. <sub>
Hints
inline
2
The combination of opening tag, content, and closing tag is known as
3
The
5
element
The
.
tag is used to raise the text below the baseline.
4 The attribute.
CSS allows us to apply style on a particular element on a web page with the help of style tag to insert audio files to a web page.
Tick () the Correct Option. 1
What is the need of a text editor while creating web pages?
a
To write the code of web pages
b
To view the web pages
c
Both a and b
d
None of these
2
The effect of a tag is restricted only to its
tag.
a
opening b
closing
c
the end of the web page
All of these
3
d
Which of the following elements is used to enclose the title of the web page?
a
<title> and </title>
b
<body> and </body>
c
<head> and </head>
d
<h1> and </h1>
4
Which of the following CSS properties is used to set the space around the content of the element?
a
margin b
padding
c
border d
opacity
5
Which of the following is the correct way to create a hyperlink?
a
<a href=”URL of the web page”> Text
b
<a src=”URL of the web page”> Text </a>
c
<a href=”URL of the web page”> Text </a>
d
<href=”URL of the web page” a> Text </a>
Chapter 4 • Introduction to HTML
Book 1.indb 51
<audio>
is a markup language used to design web pages.
1
B
HTML
51
11/6/2023 8:42:25 PM
C
Who Am I? 1
I am an HTML tag that is used to emphasise text.
2
I am a sign that is used to separate a CSS property from its value.
3
I am a method to apply CSS to all the web pages of a website simultaneously.
4
I am an attribute of the <a> tag that allows a file to download when the link is clicked. I do not take any value.
5 I am an attribute of the <video> tag which specifies that the video will start over again, every time it is completed. D
E
Write T for True and F for False. 1
HTML stands for Hypertext Making Language.
2
CSS is used in a property-value pair.
3
The <a> tag is also known as anchor tag.
4
The <src> tag is used with the <audio> tag to specify the path of the audio file.
5
The controls attribute of the <video> tag takes “play” as its value.
Answer the Following. 1
What is the meaning of the term ‘markup language’?
2
Write the syntax to define an attribute with a tag and explain each part.
3
What is the difference between padding and margin properties of CSS?
52
Book 1.indb 52
11/6/2023 8:42:25 PM
4
What is the role of autoplay and controls attributes in the <audio> tag?
5
Write the names of all the attributes of the <video> tag which do not require any value.
F
Apply Your Learning. 1
Write the HTML code to display the following output on a web page:
a3 − b3 Factorisation: (a − b) × (a2 + ab + b2)
2
Write the CSS code to create a box using <div> tag with the following specifications:
Height = 400px Width = 500px
Border size = 5px
Border colour = grey
3 Rohan has a video of his 5th birthday on his computer with the name ‘birthday.ogg’. He wants to create a web page to display his video. Would he be able to do the same in HTML? If yes, then write the name of the tag that can help him. 4 Write the code of <audio> tag to insert the ‘cartoon.mp3’ video to the web page. Ensure that the controls should not be visible on the audio.
Chapter 4 • Introduction to HTML
Book 1.indb 53
53
11/6/2023 8:42:26 PM
51
JavaScript
JavaScript was created by Brendan Eich in just 10 days while he was working at Netscape Communications Corporation. The initial name proposed for the language was “Mocha”. After then, the marketing team changed it to ‘LiveScript’. In December 1995, the language was renamed ‘JavaScript’ for trademark and other reasons.
What Is JavaScript? JavaScript is a scripting language that is commonly used for web development. It can be used to add dynamism and interactivity to web pages. It allows users to communicate with web pages and perform complicated actions on the pages. It also allows users to add content to a document dynamically without reloading the web page.
Did You Know? JavaScript is the third most popular language in the world.
Features of JavaScript The features of JavaScript are as follows: 1
It is a high-level language.
2
It is a versatile language used on the client-side as well as the server-side.
3
It is an interpreted language, executed line by line by the browser or runtime environment.
4
It is designed to be executed on various web browsers, ensuring cross-browser compatibility.
5
It is a light-weighted language that is easy to understand.
6
It is a case-sensitive language.
7
It is supported on several operating systems, including Windows, macOS, etc.
8
It provides good control to the users over the web browsers.
9
It is often used for event-driven programming, responding to user actions, such as clicks and keypresses.
10
It is easily integrated with HTML and CSS.
Applications of JavaScript Some of the applications are as follows: 1
Web Development: JavaScript is primarily used for creating dynamic and interactive web pages.
2
Game Development: JavaScript is used for browser-based game development.
3
Browser Extensions: JavaScript is commonly used for developing browser extensions that add functionality to web browsers.
4
Data Visualisation: JavaScript is used for creating interactive data visualisations and charts.
54
Book 1.indb 54
11/6/2023 8:42:26 PM
5
Real-time Applications: JavaScript is used for developing real-time applications such as chat applications, collaborative editing tools, and live streaming.
6
Web Animation: JavaScript is used to create animations and transitions on web pages.
Writing First Program Using JavaScript In an HTML document, JavaScript code is inserted between <script> and </script> tags. The <script> tag specifies that we are using a scripting language. Example 5.1 Code
Output
<html>
Welcome to Class 8
<body>
<script>
document.write(“Welcome to Class 8”) </script> </body> </html>
The document.write() function is used to display dynamic content through JavaScript. You can write the <script> element anywhere in the <body> element or in the <head> element.
JavaScript Output JavaScript can display output in different ways: innerHTML: JavaScript can use the “document.getElementById(id)” method to access an HTML element where the “id” attribute defines the HTML element and the innerHTML property defines the HTML content. document.write(): This method is used to display dynamic content through JavaScript. It should only be used for testing. window.alert(): By using this method, you can use an alert box to display data. Example 5.2 Code
Output
<html>
<body>
<script>
window.alert(12 + 55); </script> </body> </html>
JavaScript Syntax JavaScript syntax is the set of rules that define how a JavaScript program is written. All the components of a JavaScript program, including keywords, variables, operators, data types, expressions, and comments, must be correctly structured. Chapter 5 • JavaScript
Book 1.indb 55
55
11/6/2023 8:42:26 PM
Fundamentals of JavaScript The fundamental building blocks of a JavaScript program are keywords, variables, data types, operators, and comments.
Keywords Keywords are reserved words. Some of the keywords in JavaScript are let, var, const, if, else, eval, new, int, true, false, etc.
Variables In a programming language, variables are used to store data values. The let keyword is used to declare variables. The const keyword is used to declare constant variables which do not allow their value throughout the programs. An equal to sign (=) is used to assign values to variables. You must declare a variable before using it. The syntax to declare a variable is as follows: let <variable_name> = <variable_value>;
where, <variable_name> is the valid name for the variable and <variable_value> is the value you want to assign to the variable. For example, let a = 10;
You can also declare a variable first and then assign the value later. For example, let a;
a = 10;
Here, a is the name of the variable, and 10 is a value assigned to the variable a. It is recommended to put a semicolon at the end of each line in JavaScript code to terminate the line. However, it is not mandatory. Note that, JavaScript is case-sensitive, which means that the variable names num, Num, and NUM will be considered different. Example 5.3 Code
Output
<html>
JavaScript Variables
<body> <h2>JavaScript Variables</h2>
10
<p id=”var”></p> <script>
Did You Know? In older versions of JavaScript, the var keyword was used to declare variables. You can still use this keyword, but it is not recommended.
let x;
x = 10;
document.getElementById(“var”).innerHTML = x; </script> </body> </html>
Discuss
How is the let keyword different from the const keyword?
In this example, x is defined as a variable. Then, x is assigned the value 10.
56
Book 1.indb 56
11/6/2023 8:42:26 PM
Data Types Data type is an important concept in programming. A data type refers to a memory location on a computer to store a value. JavaScript has various data types, including Number, String, Boolean, etc. Numbers: It holds numeric values. let weight = 89.5; Strings: It holds a single character or a sequence of characters. let colour = “Black”; Booleans: It holds either true or false value. let z = true;
Did You Know? JavaScript is a dynamically typed language, which means it automatically determines the data type of a value. Hence, you can skip mentioning the data type.
Operators An operator is a symbol that is used to perform some operation on the variables. The variables used with the operators are called operands. The combination of variables and operators is known as an expression. JavaScript provides different types of operators, which are as follows: Arithmetic Operators: Arithmetic operators are used to perform arithmetic operations on numeric variables or values. There are different types of arithmetic operators like addition (+), subtraction (−), multiplication (*), division (/), modulus (%), etc. Assignment Operator: Assignment operator (=) assign values to JavaScript variables. Comparison Operators: These operators are used in logical expressions to determine their equality or differences in variables or values. The commonly used comparison operators are equal to (==), not equal (!=), less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=). One more comparison operator in JavaScript that compares value with data type is equal value and equal type (===). Example 5.4 Code
Output
<html>
Operator
<body>
75
<h2>Operator</h2> <p id=”opr”></p> <script>
let x = 80; let y = 5;
let z = x − y;
document.getElementById(“opr”).innerHTML = z; </script> </body> </html>
Chapter 5 • JavaScript
Book 1.indb 57
57
11/6/2023 8:42:26 PM
Comments JavaScript comments can be used to explain JavaScript code and make it more readable. JavaScript comments can also be used to prevent execution when testing alternative code. There are two types of comments used in JavaScript. Single-line Comments: Single-line comments start with //. Any text written after // within the same line will be ignored by JavaScript (that is, will not be executed). Example 5.5 Code
Output
JavaScript Comments
<html>
<body>
8
<h2>JavaScript Comments</h2> <script>
let x = 5;
// Declare x, give it the value of 5
document.write(x+3); </script> </body> </html>
Multi-line Comments: Multi-line comments start with /* and end with */. Any text written between /* and */ will be ignored by JavaScript. Example 5.6 Code
Output
<html>
8
<body>
<script> /*
Declared number will be added by 3 in the given code */
let x = 5;
document.write(x+3); </script> </body> </html>
58
Book 1.indb 58
11/6/2023 8:42:26 PM
Do It Yourself 5A 1
Match the following. Column A
Column B
Single-line comment
let
Keyword
===
Equal value and equal type operaor
/*
Text */
Multi-line comment 2
// Text
What will be the output of the following statement? //document.write(“Hello”);
Conditional Statements in JavaScript Using conditional expressions, we may tell the computer to check for a specific condition and take action accordingly. Curly braces are used to define a block in conditional statements. We have three types of conditional statements in JavaScript that allow us to make decisions in our programs. These include:
• if statement • if… else statement • if… else… if statement The if Statement
The ‘if’ statement is used to check a specific condition. If the condition is true, an “if-block” is run; otherwise, the code block will be skipped. The if keyword is used to write an “if statement”. The comparison operators are used to make a condition. Syntax: if (condition) { // block of code to be executed if the condition is true } Example 5.7 Code
Output
<html>
Value of a is less than 100
<body>
<script>
var a=20;
Chapter 5 • JavaScript
Book 1.indb 59
59
11/6/2023 8:42:26 PM
Code
Output
if(a<100){ document.write(“value of a is less than 100”); } </script> </body> </html> In the above code, the value of the variable a is checked to see if it is less than 100. The condition returns true, and the statement written inside the ‘if block’ is executed.
The if… else Statement The ‘if… else’ statement is the advanced form of the ‘if statement’. It checks a condition; if the condition is true, then the ‘if-block’ is executed. Otherwise, the ‘else-block’ is executed. Syntax:
if (condition) {
}
// block of code to be executed if the condition is true
else { }
//block of code to be executed if the condition is false
Example 5.8 Code
Output
<html> <body> <script> var a=35; if(a<50){ document.write(“a is less than 50”); } else { document.write(“a is greater than 50”); } </script> </body> </html>
a is less than 50
The if… else… if Statement Sometimes, we need to evaluate multiple conditions. In such cases, we use the if… else… if statement, which is also known as the if… else… if ladder. It allows us to check multiple conditions in a sequence, and JavaScript checks each condition until one of them is true. You can check any number of conditions using this statement. Syntax: if(condition1) {
// block of code to be executed if condition1 is true
60
Book 1.indb 60
11/6/2023 8:42:26 PM
} else if(condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
…
else{ }
// block of code to be executed if the condition1 and condition2 are false
Example 5.9 Code
Output
<html>
a is equal to 50
<body>
<script>
var a=50; if(a<50){
document.write(“a is less than 50”); }
else if(a==50){
document.write(“a is equal to 50”); }
else{
document.write(“a is greater than 50”); }
</script> </body> </html>
Solved Examples Example 5.10
Write a code in JavaScript to find out whether the number is even or odd. Code
Output
<html>
Given number a is odd
<body>
<script>
var a=51;
if(a%2==0){
document.write(“Given number a is even”); }
else{
Chapter 5 • JavaScript
Book 1.indb 61
61
11/6/2023 8:42:27 PM
Code
Output
document.write(“Given number a is odd”); }
</script> </body> </html>
Example 5.11 Write a program in JavaScript to check whether the number is positive or negative. Code <html>
<body>
Output
JavaScript Number is negative
Think and Tell What is the difference between getElementById() and window.alert()?
<h2> JavaScript</h2> <script>
var a=−30; if(a>0){
document.write(“Number is positive”); }
else{
document.write(“Number is negative”); }
</script> </body> </html>
Do It Yourself 5B 1
Write a code in JavaScript to calculate the area of a triangle.
62
Book 1.indb 62
11/6/2023 8:42:27 PM
2
Write a program to compute quotient and remainder of the expression (85796/52).
Chapter Checkup A
Fill in the Blanks. let
Hints
Brendan Eich
Mocha
was the original name of JavaScript when it was first created.
1 2
JavaScript was created by
3
Multi-line comments start with
. .
is used to declare variables.
4 B
/* */
Tick () the Correct Option. 1
Which of the following is the correct output for the following JavaScript code?
x=10;
if(x>9) {
document.write(9); }
else {
document.write(x); }
a
0 b
9
c
10 d
Undefined
2
Which of the following is not a conditional statement in JavaScript?
a
if statement b
if… else statement
c
if… else… if
if… elif… else
Chapter 5 • JavaScript
Book 1.indb 63
d
63
11/6/2023 8:42:27 PM
3 Which one of the following is known as the equality operator that is used to check whether the two values are equal or not? a
= b
==
c
>= d
None of these
4
Which of the following symbols is used for creating comments in the JavaScript?
a
\\ b
//
c
\* */ d
\* *\
C
Who Am I? 1
I am used to perform arithmetic operations on numbers.
2
I am a method used to display dynamic content through JavaScript.
3
I am scripting language used for developing real-time applications.
4
I am a decision-making statement that is used to evaluate multiple conditions.
D
E
Write T for True and F for False. 1
The let keyword is used to declare a constant variable.
2
JavaScript is used for web development.
3
The assignment operator is used to assign values to JavaScript variables.
4
An operator is a symbol that is used to perform some operation on the variables.
Answer the Following. 1
What is JavaScript?
2
Define some features of JavaScript.
3
Write the names of different types of JavaScript operators.
64
Book 1.indb 64
11/6/2023 8:42:27 PM
4
What is the if… else… if ladder?
F
Apply your Learning. 1 Mishika wants to display her name on a web page using JavaScript. Help her write a program in JavaScript to do so.
2
Write a JavaScript program to find the output of the following expressions:
5−6
10−5
false−6
true + 5
5 + “num”
3
Write a program in JavaScript to show different types of comments in JavaScript.
4 Ramesh has purchased 10 t-shirts for his garments shop for Rs.5,000. He sold them for Rs.7,000. Write a JavaScript program to find out whether he is at profit or loss. Also, display the profit/loss amount.
Chapter 5 • JavaScript
Book 1.indb 65
65
11/6/2023 8:42:27 PM
61
HTML Forms
In this chapter, you will study the most interactive and essential element of web development, i.e., HTML forms. Forms are used to collect information from users, such as their names, email addresses, and hobbies. In this chapter, you will learn to create forms and understand how they work.
What Are HTML Forms? HTML forms are commonly used when websites need to gather information from users. For example, if someone wants to buy a bag online, they would first fill their address details in one part of the form and then enter their payment information in another part to complete the purchase. An HTML <form> element is used to create fields where users can provide information in an interactive way. It includes fields where users can type text, numbers, email addresses, and passwords, and indicate choices like selecting check boxes or clicking buttons.
Form Structure In HTML, the structure of a form is how you organise and align the various elements that make up the form. A basic form consists of several elements. Let us learn about these elements and options.
The <form> Element The <form> element is a container for all form elements. It helps define where the form begins and ends on a web page. Example: <form>
<-- Form elements -->
</form>
The <input> Element The <input> element is used to create various fields to collect different types of information from users, such as text, email addresses, passwords, and more. The <label> element is used to attach a text with the input fields. Some common types of input fields are: 1
Text Input: It is used to take textual information from the user like name, age, roll number, etc. Use type=”text” attribute: Example 6.1 Code
Output
<label for=”first_name”>First Name:</label> <input type=”text” id=”first_name” name=”first_name”>
66
Book 1.indb 66
11/6/2023 8:42:27 PM
2
Email Input: It is used to take the email address as information from the user. It verifies the format of the email address, which means you must enter the email address in the correct format. It shows a message if you enter an incorrect email. It also gives suggestions of email addresses that you have used earlier in the web browser. Use type=”email” attribute: Example 6.2 Code <label for=”email”>Email:</label> <input type=”email” id=”email” name=”email”> Output
3
Password Input: It is used to take sensitive information like passwords, bank account numbers, etc., from the user. The characters you entered in this field appear in the form of stars or dots. An eye icon also appears in this field which allows you to view the text in readable form. Use type=”password” attribute: Example 6.3 Code
Output
<label for=”password”>Password:</label> <input type=”password” id=”password” name=”password”> 4
Date Input: It is used to take date as input from the user. It displays a calendar to select the date. Use the type=”date” attribute: Example 6.4 Code
Output
<label for=”dob”>Date of Birth:</label> <input type=”date” id=”dob” name=”dob” required>
5
Radio Buttons: The Radio button option allows users to select one option from a list. Use the type=”radio” attribute:
Chapter 6 • HTML Forms
Book 1.indb 67
67
11/6/2023 8:42:28 PM
Example 6.5 Code
Output
<label>Gender:</label>
<input type=”radio” id=”male” name=”gender” value=”male”> <label for=”male”>Male</label>
<input type=”radio” id=”female”
name=”gender” value=”female”>
<label for=”female”>Female</label>
<input type=”radio” id=”other” name=”gender” value=”other”> <label for=”other”>Other</label> 6
Check Boxes: The check box option allows users to select multiple options from a list. Use the type=”checkbox” attribute: Example 6.6 Code
Output
<label>Interests:</label>
<input type=”checkbox” id=”sports” name=”interests” value=”sports”>
<label for=”sports”>Sports</label>
<input type=”checkbox” id=”music” name=”interests” value=”music”>
<label for=”music”>Music</label>
<input type=”checkbox” id=”movies” name=”interests” value=”movies”>
<label for=”movies”>Movies</label>
The <textarea> Element The <textarea> element is used for long text input, such as comments or messages: Example 6.7 Code <label for=”address”>Address:</label> <textarea id=”address” name=”address” rows=”4” required>
Output
Did You Know? How is a text input field different from a password input box?
The <button> Element The <button> element is used to create buttons within forms. You can use it to perform any action on the form. The type attribute is a must to use with the <button> element. It takes any one value out of button, submit, and reset values.
68
Book 1.indb 68
11/6/2023 8:42:28 PM
Example 6.8 Code
Output
<button type=”button”> Login </button>
<button type=”button”> Cancel </button>
The <select> Element The <select> element is used to create drop-down menus. The <option> element is used in combination with the <select> element to create items in the drop-down menu. Example 6.9 Code
Output
<label for=”course”>Course:</label>
<select id=”course” name=”course” required>
<option value=”math”>Mathematics</option> <option value=”science”>Science</option> <option value=”history”>History</option>
<option value=”english”>English</option>
</select>
Think and Tell Imagine you are designing a website for a local library. The librarian wants to use an HTML form to allow users to request the issuing of books. Think about the various form elements you would include in this form.
Creating and Displaying a Form Example 6.10 Code <html> <head> <title>Student Details Form</title> </head> <body> <h1>Student Details</h1> <form> <label for=”first_name”>First Name:</label> <input type=”text” id=”first_name” name=”first_name” required><br><br> <label for=”last_name”>Last Name:</label> <input type=”text” id=”last_name” name=”last_name” required><br><br> <label for=”dob”>Date of Birth:</label> <input type=”date” id=”dob” name=”dob” required><br><br> Chapter 6 • HTML Forms
Book 1.indb 69
69
11/6/2023 8:42:28 PM
Code <label for=”email”>Email:</label> <input type=”email” id=”email” name=”email” required><br><br> <label for=”phone”>Phone Number:</label> <input type=”tel” id=”phone” name=”phone” required><br><br> <label for=”address”>Address:</label> <textarea id=”address” name=”address” rows=”4” required></textarea><br><br> <label for=”course”>Course:</label> <select id=”course” name=”course” required> <option value=”math”>Mathematics</option> <option value=”science”>Science</option> <option value=”history”>History</option> <option value=”english”>English</option> </select><br><br> <label for=”gender”>Gender:</label> <input type=”radio” id=”male” name=”gender” value=”male” required> <label for=”male”>Male</label> <input type=”radio” id=”female” name=”gender” value=”female” required> <label for=”female”>Female</label> <input type=”radio” id=”other” name=”gender” value=”other” required> <label for=”other”>Other</label><br><br> <button type=”submit” value=”Submit”>Submit</button> </form> </body> </html> Output
70
Book 1.indb 70
11/6/2023 8:42:28 PM
Form Attributes Forms can have various attributes to control the behaviour of a form:
• Action: Specifies the URL to which form data will be submitted. • Method: Specifies the HyperText Transfer Protocol (HTTP) method to be used (either “GET” or “POST”). GET is better for submitting non-sensitive information, whereas POST is used to submit sensitive information.
• Name: Assigns a name to the form for easy identification. • Target: Specifies where to display the response after form submission (e.g., in the same window or in a new one). It takes any one value from the _blank, _self, _parent and _top values.
Did You Know? HTML forms not only collect user data but can also be used for interactive quizzes, surveys, and feedback on websites. They are versatile tools for engaging with online visitors.
Here is an example of a form with attributes: <form action=”submit_student_details.php” method=”post” target=”_blank”> The form action is set to ‘submit_student_details.php’, which is where you can process the form data on the server side. The form method is set to ‘POST’, signifying the HTTP method used.
Form Validation Form validation is crucial to ensure that users provide the correct type of information. HTML introduced built-in form validation, using attributes like required, min, max, and pattern. For example:
<label for=”age”>Age:</label>
<input type=”number” id=”age” name=”age” required min=”18” max=”99”> The required attribute makes the field mandatory, and min and max specify the acceptable value ranges. The pattern attribute can be used to enforce a specific format such as a valid email address.
Setting Properties of a Form Using Internal CSS Setting properties of a form using internal CSS is also known as embedded CSS or inline CSS. You can make your HTML forms look attractive and arrange them on your web page by using the <style> element. This <style> element is placed in the <head> section of your HTML document. Steps to set properties of a form using internal CSS are: 1
Open an HTML Document: Start by creating a standard HTML document structure, including the <!DOCTYPE html>, <html>, <head>, and <body> elements.
2
Include the <style> Element: Inside the <head> section of your HTML document, include a <style> element. This element is where you will define the CSS rules for styling your form elements.
3
Select the Form Element: To target the form you want to style, use the form selector. For example, to style all forms in your document, you can use form {}. To style a specific form, you can use an ID or class selector like #myForm {}.
4
Define CSS Properties: Within the selected form CSS block, you can define various CSS properties to control the appearance of the form. Common properties include width, margin, padding, background-colour, border, border-radius, font-size, colour, and many more. You can style form elements individually or collectively.
Chapter 6 • HTML Forms
Book 1.indb 71
71
11/6/2023 8:42:28 PM
5
Style Form Elements: Inside a form block, you can target specific form elements such as labels, input fields, buttons, and other related elements. Use CSS selectors such as label {}, input[type=”text”] {}, and input[type=”submit”] {} to style these elements individually.
6
Save and Apply: When you have defined your internal CSS rules, save the HTML document. When you load the HTML document in a web browser, the CSS styles you have defined will be applied to the form elements. Example 6.11 Code <html> <head> <title>Form Styling</title> <style> /* Internal CSS styles for the form */ form { width: 400px; /* Set the width of the form. */ margin: 0 auto; /* Center-align the form. */ padding: 50px; /* Add some padding for spacing. */ background-color: #f2f2f2; /* Set the background colour.*/ border: 1px solid #ccc; /* Add a border. */ } /* Style for form labels */ label { display: block; /* Display labels as block elements for better spacing. */ margin-bottom: 10px; /* Add some space between labels */ font-weight: bold; /* Make labels bold. */ } /* Style for form input fields */ input[type=”text”], input[type=”email”] { width: 100%; /* Set input fields to 100% width. */ padding: 10px; /* Add padding for input fields. */ margin-bottom: 15px; /* Add space between input fields. */ border: 1px solid #ccc; /* Add a border to input fields. */ } /* Style for the submit button */ input[type=”submit”] { background-color: #007bff; /* Set a background colour for the button. */ color: #fff; /* Set text color to white. */ padding: 10px 20px; /* Add padding for the button. */ border-radius: 3px; /* Add rounded corners to the button. */ } </style> </head> <body> <form> <label for=”name”>Name:</label> <input type=”text” id=”name” name=”name”> <label for=”email”>Email:</label> <input type=”email” id=”email” name=”email”> <button type=”submit” value=”Submit”>Submit</button> </form> </body> </html>
72
Book 1.indb 72
11/6/2023 8:42:28 PM
Output
Did You Know? HTML forms can be styled extensively using CSS to match website design and branding for creating visually appealing and cohesive user interfaces.
Do It Yourself 6A 1
Who Am I? a
I am a button that allows users to select one option from a list.
b
I am a form attribute that specifies the URL to which the form data will be submitted.
c I am an HTML element that makes a form look attractive, and I am placed in the <head> section of the HTML document. 2
Answer the Following. a
Explain the ‘method’ attribute of a form.
b
What is the use of radio buttons in an HTML form?
Chapter Checkup A
Fill in the Blanks. Hints 1 HTML options.
<textarea>
<form>
radio
required
is used to create a space where users can provide information by using various interactive
2
The
3
The type attribute
4
The
5
Setting properties of a form using internal CSS is also known as
Chapter 6 • HTML Forms
Book 1.indb 73
inline
element is used for long text input, such as comments or messages. is used for radio buttons, allowing users to select one option from a list. attribute makes a field mandatory in an HTML form. CSS.
73
11/6/2023 8:42:28 PM
B
Tick () the Correct Option. 1
Which of the following HTML elements is used to create a container for form elements?
a
<input>
b
<form>
c
<label>
d
<select>
2
Which of the following input types is used for collecting the name of a student?
a
b
text
c
password
d
radio
3
Which of the following elements helps create a drop-down menu in HTML forms?
a
<input>
b
<select>
c
<textarea>
d
<button>
4
Which attribute can be used to apply a specific format?
a
required
b
pattern
c
validate
d
specific
5
What is the purpose of the <button> element in HTML forms?
a
To display text
b
To create hyperlinks
c
To submit the form
d
To add images
C
D
Write T for True and F for False. 1
Form validation is crucial to ensure that users provide correct information.
2
The <input> element can collect various types of input, including text, email addresses, and passwords.
3
Check boxes allow users to select only one option from a list.
4
The ‘action’ attribute in a <form> element specifies where the form data will be submitted.
5
HTML introduced in-built form validation, using attributes like ‘required’ and ‘min’.
Answer the Following. 1
What is the primary purpose of the HTML <form> element in web development?
2
What is the purpose of form validation in HTML? Name the attributes that support form validation.
74
Book 1.indb 74
11/6/2023 8:42:29 PM
3
How can internal CSS (embedded) be used to style HTML forms?
4
Name the various attributes that control the behaviour of a form.
5
What is the <input> element? Explain any two <input> fields with their syntax.
E
Apply Your Learning. 1 Create a simple HTML form for receiving parents’ feedback on a school event. Include fields for the student and parent names, class, section, email address, and comments. Apply form validation to ensure that all fields are filled correctly. Use internal CSS to style the form. Customise the background colour, font styles, and appearance of the ‘Submit’ button on the form.
2 Imagine that you are conducting a survey about students’ favourite school subjects. Design an HTML form with radio buttons for subjects such as Mathematics, Science, History, and English. Allow the students to select their favourite subject and submit their choice. 3 Create a basic HTML form for an ice-cream parlour where customers can indicate their preferred ice-cream flavours. The HTML form should include check boxes with these options: chocolate, vanilla, choco-chip, strawberry, and butterscotch. Ensure that users can select multiple flavours and provide a ‘Submit’ button at the end to complete the submission process.
Chapter 6 • HTML Forms
Book 1.indb 75
75
11/6/2023 8:42:29 PM
Sa
le
sS
am
pl
e
About the Book This coding book is supplementary to the main “Mel n Conji” content book. This book represents a 21st-century approach to learning coding concepts and developing computational thinking and problem-solving skills. To prepare students for the digital age, the curriculum is interwoven with well-thought-out concept graduation with real-life examples and practice problems.
Special Features • Illustrative approach: Concepts in coding and computer science are delivered through pictorial representations and learner-friendly approaches. • Learning through real-life examples: Age-appropriate examples that enable learners to relate to the concept and learn about the unknown from the known. • Extensive practice: Multiple practice scenarios to reinforce learnings. • Coding challenges: Includes projects through which learners can demonstrate their learning outcomes in coding and computer science.
About Uolo Uolo partners with K-12 schools to bring technology-based learning programs. We believe pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. Uolo is trusted by over 10,000 schools across India, South East Asia, and the Middle East.
Singapore
|
Gurugram
CS_CB_Coding_ICSE_Grade8_Cover.indd All Pages
|
Bengaluru
|
hello@uolo.com `xxx
© 2024 Uolo EdTech Pvt. Ltd. All rights reserved.
NEP 2020 based
|
ICSE compliant
|
Technology powered
06/11/23 4:29 PM