ICSE_G8_Coding_AY25

Page 1


Revised Edition

ICSE

Computer Science Java II Web Development III Tekie

Acknowledgements

Academic Authors: Jatinder Kaur, Ayushi Jain, Anuj Gupta, Simran Singh

Creative Directors: Bhavna Tripathi, Mangal Singh Rana, Satish

Book Production: Rakesh Kumar Singh, Sanjay Kumar Goel

Project Lead: Jatinder Kaur

VP, Learning: Abhishek Bhatnagar

All products and brand names used in this book are trademarks, registered trademarks or trade names of their respective owners.

© Uolo EdTech Private Limited

First published 2023

Second published 2024

Third published 2025

This book is sold subject to the condition that it shall not by way of trade or otherwise, be lent, resold, hired out, or otherwise circulated without the publisher’s prior written consent in any form of binding or cover other than that in which it is published and without a similar condition including this condition being imposed on the subsequent purchaser and without limiting the rights under copyright reserved above, no part of this publication may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of both the copyright owner and the above-mentioned publisher of this book.

Book Title: Tekie ICSE Computer Science Java II Web Development III

ISBN: 978-81-981317-1-3

Published by Uolo EdTech Private Limited

Corporate Office Address:

85, Sector 44, Gurugram, Haryana 122003

CIN: U74999DL2017PTC322986

Illustrations and images: www.shutterstock.com, www.stock.adobe.com and www.freepik.com

All suggested use of the internet should be under adult supervision.

Preface

Standing at the forefront of the digital and AI revolution, the importance of coding and computational skills has reached unprecedented heights. In today’s professional landscape, whether it is in the fields of medicine, space exploration, education, science, or business, no sector remains untouched by this transformative wave. To thrive in the 21st century, basic computer literacy is no longer sufficient. Learners must evolve into “digital natives” who can fluently read, write, and communicate in the languages that machines and AI comprehend. Recognising this imperative, the National Education Policy of 2020 (NEP 2020) has strongly recommended the integration of coding skills, computational thinking, critical analysis, and problem-solving abilities into the curriculum. Moreover, forward-looking subjects like AI, Data Science, Computer Applications, and IT have been introduced as elective subjects from grade 9 onwards. It would not be surprising if further transformative measures are taken even at the elementary education level.

Inspired by these insights, Uolo has introduced an innovative 360-degree program for a codingfocused computer science curriculum, known as Tekie, spanning grades 1 to 8. The program provides an experiential learning approach, going beyond theoretical knowledge. It not only covers theoretical aspects of computer science and coding, but includes hands-on activities and technology-based projects that enable students to experience computer science first hand. The program includes chapters that provide a deeper immersion in computer science that both learners and teachers may find interesting.

This coding book is a part of the larger Tekie program that also includes a main computer science textbook, covering the basics of computing, the latest technologies, and essential computer tools.

In addition to the textbooks, we provide a digital platform where students can actively engage in practical activities and hands-on learning projects. This platform is designed to enhance the learning process by allowing students to experiment and apply their knowledge in a real-world context.

We have meticulously aligned our activities with the guidelines of the National Education Policy (NEP) 2020, which emphasises a holistic approach to learning. This approach is aimed at developing critical thinking, logical reasoning, and practical skills among students. By integrating these elements into our coding program, we aim to prepare students for the future, equipping them with the necessary skills to navigate and excel in the ever-evolving world of technology.

Our mission is to cultivate a passion for coding and computer science among young learners, making the learning process enjoyable and impactful. We are confident that this series will not only help students grasp the fundamentals of coding but also inspire them to explore the endless possibilities that technology offers.

We invite you to embark on this exciting journey of learning and discovery. Let’s empower the next generation with the skills and knowledge they need to thrive in a digital world.

Creating a Project

from the

It is below the stage and next to the Sprites pane. You can use it to add, upload, edit, or delete backdrops. 11 Go button and Stop button: The green flag is the Go button. You click it to run the script. The red button is the Stop button. You click it to stop the running script.

Did You Know: Interesting facts related to the topic

Discuss: A multi-faceted probing question related to the concept that arouses curiosity

3

Think and Tell

Code Snippets: Complete code for each activity with output facilitating hands-on learning and immediate feedback

Chapter Checkup

Why do we need to repeat 360 times to draw a full circle?

Do It Yourself 4A

Think and Tell: Analysis, reflection, and text-to-self connection-based prompts for discussion in class

A Fill in the Blanks.

1 What will be the output when you run the given script?

It Yourself: Short exercises between the chapter to pause and assess comprehension

Hints thickness when I start as a clone delete this clone rotation clones is when an object moves around its centre. are the exact same copies of a sprite.

Test Papers: Designed to evaluate understanding of core concepts and application of skills 1

Chapter Checkup

Chapter Checkup: Chapter-end practice exercises aligned to different levels of Bloom’s Taxonomy

Apply your learning: Intellectually stimulating questions designed for higher-order thinking and analysis

Coding Challenge: Hands-on challenges to encourage and actively engage with the concepts learnt throughout the chapter

Fill in the Blanks.

The block runs the attached script when a sprite is cloned. block helps us remove a clone when it is no longer needed.

5 The block sets the of the sprite’s pen. F Apply Your Learning.

Hints thickness when I start as a clone delete this clone rotation clones

1 is when an object moves around its centre.

2 are the exact same copies of a sprite.

3 The block runs the attached script when a sprite is cloned.

4 The block helps us remove a clone when it is no longer needed.

5 The block sets the of the sprite’s pen.

2 are the exact same copies of a sprite.

1 Shreya is making a project to show the Earth rotating in space. Help her write the script to make the Earth sprite rotate. A. Fill in the blanks.

F Apply Your Learning.

3 The block runs the attached script when a sprite is cloned.

4 The block helps us remove a clone when it is no longer needed.

1 Shreya is making a project to show the Earth rotating in space. Help her write the script to make the Earth sprite rotate.

5 The block sets the of the sprite’s pen.

F Apply Your Learning. 1

Test Paper (Based on Chapters 1 to 5)

A. Fill in the blanks.

1 is a way of giving instructions to tell a computer what to do.

2 The block repeats the instructions inside it forever, unless the Stop button is clicked.

3 A is a character or object that you can move around on the stage and make this object do things.

4 A is a measure of how much you turn.

unless the Stop button is clicked. Test Paper (Based on Chapters 1 to 5)

• 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

• User

• Introduction to Loops

• What Is HTML?

• Basics of HTML

• Basic Tags of HTML

• Understanding CSS

• Adding Images

• Creating Links

• Adding Audio

Adding Video

• What Is JavaScript?

• Writing First Program Using JavaScript

• Fundamentals of JavaScript

• Conditional Statements in JavaScript

• What Are HTML Forms?

• Form Structure

• Creating and Displaying a Form

• Form Attributes

• Form Validation

• Setting Properties of a Form Using Internal CSS

* This chapter is not a part of the prescribed ICSE curriculum. It has been added after consideration of the latest trends in the computer science field. Teaching this chapter or including it in the assessment process is entirely at the discretion of the school and the subject teacher.

Fundamentals of Java 1

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.

A platform is where a program runs. Java is a platform because it includes the Java Virtual Machine (JVM), the Java runtime environment (JRE), and the Java Development Kit (JDK). Java provides a runtime environment (JRE) and an application programming interface (API), but the term 'Java platform' covers more, including the JVM and JDK, for developing and running Java applications.

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.

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-readable bytecode, 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 platform-independent interpreter, to produce the final output.

Compile Time

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

Advantages of OOPs

1 OOP can lead to faster development of programs.

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.

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, choice, or result. It is better to use descriptive names in order to make your programs easy to understand and maintain.

Car 1
Car 3
Car 2
Car 4

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

//Program to print “Hello World!”.

class Welcome{ public static void main (String args[])

{ System.out.printIn(“Hello, Java!”); { } Documentation

Let us understand the meaning of each part in detail.

Documentation Statement

Class Definition

The main Method

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.

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 code 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!” class Welcome{ public static void main(String[] args) { System.out.println(“Hello, Java!”);

Hello, Java!

Example 1.1

Program to display names.

Names.java Output

//Program to print “Hello, Java!”

class Names{

public static void main(String[] args)

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

My name is John. My best friend’s name is Adam.

Sum.java Output

class Sum{

public static void main(String[] args){

System.out.println(24 + 26);

In Example 1.1, the + operator is used to add two numbers. 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{

public static void main(String[] args){

System.out.print(“Welcome to the world of Java!”); System.out.print(“Hope you are having fun!”); }

Welcome to the world of Java!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, 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.

Example 1.4

Program to display the product of two numbers.

Product.java Output

class Product{

public static void main(String[] args){ System.out.println(“30 x 50 = “ + 30 * 50); } }

Example 1.5

30 x 50 = 1500

Program to calculate the area of a rectangle whose width is 5 and height is 10.

Area.java

public class Area{

public static void main(String[] args){ System.out.print(“Area of rectangle = “ + 5 * 10); } }

Syntax

Output

Area of rectangle = 50

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

Think and Tell

Do you think knowing syntax is required for learning every language?

Main.java Output

class Main{

public static void main(String[] args){ System.out.print(Hello!);

/tmp/cGx28261UN/Main.java:3: error: ’)’ expected System.out.print(Hello!);

1 error

• Missing the semicolon symbol at the end of any instruction.

Main.java Output

public class Main

{ public static void main(String[] args) { System.out.print(“Hello”)

Data Types

/tmp/cGx28261UN/Main.java:3: error: ’;’ expected System.out.print (“Hello!”)

error

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.

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.

In simple words, variables are names given to the memory location where your value is stored.

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

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 Variable name Semicolon int count ;

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;

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.

Syntax: <data type> <variable name> = <value>;

Data type Variable name

Semicolon int count = 4 ;

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

class Main{ public static void main(String[] args){ int number; number = 5;

System.out.println(“Number is “ + number); } }

Output

Number is 5

In the program above, we have initialised the number variable with 5 in line 4, and in line 5, 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 : Store letters and numbers within double quotes.

• Integer variables : Store numbers without decimal values.

• Float variables : Store numbers with decimal values.

• Character variables : Store a single character such as “a” or “b”.

• Boolean : Stores only true or false values.

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{

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

Sum is 21

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{

public static void main(String[] args){ int var = 10; System.out.println(“Local Variable “ + var);

Local Variable 10

Instance Variable

A variable declared inside a class but outside the body of methods is called an instance variable. It is not declared static. Instance variables cannot be accessed directly. You have to create an instance of the class. The new operator is used to create an instance of the class, which is used to access the instance variables. You will learn more about it in the next chapter.

Example 1.9

Simple.java Output

class Simple{ int a = 10; float f = a; public static void main(String[] args){ Simple obj = new Simple(); System.out.println(obj.a); System.out.println(obj.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{ public static void main(String[] args){ int 1num = 5; } } /tmp/cGx2826UN/Main.java:3: error: not a statement      int 1num = 5;

/tmp/cGx2826UN/Main.java:3: error: ‘;’ expected      int 1num = 5;

2 errors

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.

For example: “Name of the company” can be written as “nameOfTheCompany”. As this represents the camel’s hump, we call it Camel-case.

Example 1.11

capitalise the first letter of all the following words first word lower case

Program to store whole numbers in byte, short, int, and long variables.

Main.java Output

class Main{

public static void main(String[] args){

byte numByte = 64;

System.out.println(“A byte-sized number is “ + numByte); short numShort = 32000;

System.out.println(“A short-sized number is “ + numShort); int numInt = -2010097456;

System.out.println(“A int-sized number is “ + numInt); long numLong = 1956789034264578326L;

System.out.println(“A long-sized number is “ + numLong);

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 numFloat = 645.6743f; System.out.println(“A float-sized decimal number is “ + numFloat);

double numDouble = 3229.006538971d; System.out.println(“A double-sized decimal number is “ + numDouble); }

A byte-sized number is 64

A short-sized number is 32000

A int-sized number is -2010097456

A long-sized number is 1956789034264578326

A float-sized decimal number is 645.6743

A double-sized decimal number is 3229.006538971

Example 1.13

A Java program to store your name in a variable and display it in the output.

Main.java Output

class Main{

public static void main(String[] args){

String myName = “John”; System.out.println(“My name is “ + myName); } } My name is John

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

++ Increment Increases the value of a variable by 1.

Decrement Decreases the value of a variable by 1.

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

+ Addition Adds two values together.

- Subtraction Subtracts one value from another.

* Multiplication Multiplies two values.

/ Division Divides one value by another.

% Modulus Returns the remainder.

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

== Equal to

!= Not equal

> Greater than

Operator Name Example

< Less than x < y

>= Greater than or equal to x

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

&& Logical and Returns true if both statements are true.

|| Logical or Returns true if one of the statements is true.

! Logical not

BEDMAS Rule

Reverse the result, returns false if the result is true. !(x

Java performs the following operations in order to solve a mathematical expression:

1 Brackets (B)

4 Multiplication (M)

Example

9 + 7 * (8 − 4) / 2 − 3

2 Exponents (E)

5 Addition (A)

= 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

class Main{

public static void main(String[] args){ int side = 5; int area = side * side; int perimeter = 4 * side; System.out.println(“Area: “ + area); System.out.println(“Perimeter: “ + perimeter); } }

3 Division (D)

6 Subtraction (S)

Output

Area: 25

Perimeter: 20

Example 1.15

Program to show the difference between using a unary operator before and after a variable.

Main.java Output

class Main{

public static void main(String[] args){ int num1 = 5;

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

Value of num1++ is 5

Value of num1 is 6

Value of ++num2 is 6

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 8, Java increases num2 to 6 (5 + 1) and displays the new value.

Chapter Checkup

A Fill in the Blanks.

logical  class  instance  arithmetic  block of code

1 In Java, a is a blueprint for creating objects.

2 A variable that is associated with an instance of a class is called a/an variable.

3 The scope of a local variable is limited to the in which it is declared.

4 operators perform mathematical operations in Java.

5 In Java, the “&&” operator is an example of a/an operator.

B Tick () the Correct Option.

1 Which keyword is used to create a class in Java? a define b   class c   create d   make

2 What type of variable is declared with a static keyword in Java?

a Local variable

c   Static variable

3 The == operator in Java is an example of a:

b   Instance variable

d   Dynamic variable

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.

2 I’m a rule in Java to make calculations.

3 I’m an operator in Java that is used for comparing values.

4 I’m a logical operator in Java that returns true if both statements are true.

5 I’m a type of operator that work with a single variable.

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

E Answer the Following.

1 Explain the difference between a local variable and an instance variable in terms of scope.

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 calculate the total marks obtained in five subjects.

4 Compare the marks obtained in two subjects, using a relational operator and print the result.

5 Display the result of the person based on the total marks obtained in question 3.

Conditional Statements in Java 2

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.

Example 2.1

Program to read your name as input and print it.

Main.java Output

import java.util.Scanner; class Main{

public static void main(String[] args){

Scanner myObj = new Scanner(System.in); 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.

Enter your name Amita

Username is: Amita

Main.java Output

import java.util.Scanner; 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(); System.out.println(“Name: “ + name); System.out.println(“Age: “ + age); System.out.println(“Salary: “ + salary);

Conditions

Enter name, age and salary: Amita

36

85000

Name: Amita

Age: 36

Salary: 85000.0

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.

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.

How does Java decide which branch of code to execute when using an if-else statement?

In this chapter, we will learn the following control flow statements for decision-making 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!

if (condition)

{ //Task to be performed if the condition becomes true.

}

keyword

condition opening braces closing braces

if (Age>= 18) { }

System.out.println(”Eligible to Vote!”);

If Age>=18

True

Eligible to Vote

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

class Main{ public static void main(String[] args){ int x = 20; int y = 18; if(x > y) {

Output

System.out.println(“x is greater than y”); } } } 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.

Example 2.4

A program to check whether the number is even.

Main.java Output

class Main{

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 number is even

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.

Syntax: if (condition) { //Task to be performed if the condition becomes true. } else{ //Task to be performed if the condition becomes false.

keyword

condition

Statement(s) to be executed when the condition is true

if (Age>= 18) { } else { }

System.out.println(”Eligible to Vote!”);

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{

public static void main(String[] args){ int time = 20;

if(time < 18) {

System.out.println(“Good day.”); } else{

System.out.println(“Good evening.”); } } } Good evening.

Example 2.6

A program to check whether a number is even or odd.

Main.java Output

class

Main{

public static void main(String[] args){ int number = 99;

if(number%2 == 0) {

System.out.println(“The number is even”);

The number is odd

Main.java

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.

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.

}

Nested if block

Outer else block } else { System.out.println(“c is the largest number”); } } } if (a>c) {

if (a>c) { System.out.printIn(“a 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

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 “The largest number is: 30”.

Example 2.7

A program to check the largest of three numbers.

Main.java Output

import java.util.Scanner; class Main { public static void main(String[] args) { Scanner myObj = new Scanner (System.in);

The largest number is: 30 else { //Task to be performed if condition1 and condition 3 is false. }

Enter the values for a, b, and c: 10

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{ 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”); }

a is 10 and b is 20

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

< 10

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.

Outer if-else block

Inner if-else block

if (time<10) { System.out.println(”Good morning.”); } else if (time<18) { System.out.println(”Good day .”); } 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{ 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.

Good evening.

Main.java Output

class Main{ public static void main(String[] args){ int i = 30; i is greater than or equal to 30 Statement(s) after if-else-if ladder

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 nextLine()   object   nested   else   Scanner

1 To get input from a user, we have to use the class.

2 method reads a string value from the user.

3 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 To use any of the Scanner class methods, we must first create a/an of the class.

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

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

1

Loops in Java 3

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

2 do-while

3 for

In this chapter, we will learn about the while and for loops.

While Loop

Think and Tell

What is the concept of loop control variable in loops?

A while loop repeats a statement or a block of statements as long as the looping condition remains true.

//variable initialization while (condition)

{ //body of the loop

//increment/decrement statement

} int i=10; while (i>1) {

condition variable initialization

decrement keyword body of loop

System.out.println(i);

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{ 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);

Example1.java Output

//increases i by 1 after each loop i++;

Example 3.2

Program to print the odd numbers between 1 to 10.

Example2.java Output

class Example2{

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

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

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 { public static void main(String[] args) { for ( int i = 1; i <= 10;  i++){

Example 3.4

Program to find the factorial of a number.

Example4.java Output

class Example4{

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

Factorial of 4:24

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{

public static void main(String[] args){ // for loop to print first 10 natural numbers for(int i = 1; i <= 10; i++)

{ if(i==7)

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

Example6.java Output

class Example6{

public static void main(String[] args){

// for loop to print first 10 natural numbers

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

1 statements are control statements that transfer control of the execution of a program from one 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 is true.

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.

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:

5 X 1 = 5

5 X 2 = 10 . .

5 X 10 = 50

Introduction to HTML 4

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.

Basics of HTML

An HTML document consists of HTML tags, elements, and attributes.

Tags

Did You Know?

The first web page was developed by Tim BernersLee, a British scientist, in 1991.

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.

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.

For example,

<p align = “right”> I am a paragraph with right alignment </p> Here, align is the attribute of <p> element.

Structure of An HTML Document

Did You Know?

Multiple attributes can be used in an element.

Think and Tell

How are tags and attributes different?

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>

<body>

Body of the web page

</body>

</html>

Head Body

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.

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

<h1> to <h6> Used to create headings and subheadings on a web page. <h1> is the biggest heading and <h6> is the lowest heading

<h1> Heading 1 </h1>

<h2> Heading 2 </h2>

<h3> Heading 3 </h3>

<h4> Heading 4 </h4>

<h5> Heading 5 </h5>

<h6> Heading 6 </h6>

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5

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 </a> Home

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

<html> <head>

<title> Text Formatting Example </title> </head> <body>

<h1> Welcome to My Web Page </h1>

Code

<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 H2O, and the famous equation is E = mc2

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

There are several properties of CSS. Let us discuss some of them in the following table:

Property

Description

color Sets the colour of the text.

Example

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

Note: x-small, small, medium, large, x-large, xx-large can also be used as values.

font-weight Sets the weight or thickness of the text. font-weight: bold

Note: lighter, or any number can also be used

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. border-radius: 5px

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 calculated. There are two possible values for this property: content-box and border-box.

box-sizing: border-box

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>

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:

<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 H20, and the famous equation is E = mc2

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.

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

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

While creating this web page, place the images with the same names at the same location where the web page is saved.

Srinivasa Ramanujan Contribution: Number Theory, Mathematical Analysis
Shakuntala Devi Contribution: Mental Calulation, Author of Mathematics Books
Abhay Ashtekar Contribution: Quantum Gravity, Loop, Quantum Gravity

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>

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.

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.

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>

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

Let’s Play Video

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.

Do It Yourself 4C

1 Match the following.

CSS

Discuss

What will happen if the specified audio/video is not found at the specified path?

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.

2 Write the names of any three attributes of the <audio> tag.

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.

Hints

<sub>  HTML  <audio>  inline  element

1 is a markup language used to design web pages.

2 The combination of opening tag, content, and closing tag is known as .

3 The tag is used to raise the text below the baseline.

4 The CSS allows us to apply style on a particular element on a web page with the help of style attribute.

5 The tag to insert audio files to a web page.

B 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

c   Both a and b

b   To view the web pages

d   None of these

2 The effect of a tag is restricted only to its tag.

a opening

c   the end of the web page

b   closing

d   All of these

3 Which of the following elements is used to enclose the title of the web page?

a <title> and </title>

c   <head> and </head>

b   <body> and </body>

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

c   border

b   padding

d   opacity

5 Which of the following is the correct way to create a hyperlink?

a <a href=”URL of the web page”> Text

c   <a href=”URL of the web page”> Text </a>

b   <a src=”URL of the web page”> Text </a>

d   <href=”URL of the web page” a> Text </a>

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

E 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?

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.

1

JavaScript 5

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.

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.

Did You Know?

JavaScript is the third most popular language in the world.

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.

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

<html> <body> <script> document.write(“Welcome to Class 8”) </script> </body> </html>

Output

Welcome to Class 8

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

<html> <body> <script> window.alert(12 + 55); </script> </body> </html>

JavaScript Syntax

Output

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.

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>

<body>

<h2>JavaScript Variables</h2> <p id=”var”></p>

<script> let x; x = 10; document.getElementById(“var”).innerHTML = x; </script>

</body> </html>

JavaScript Variables

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.

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.

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;

Operators

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.

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

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

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 <html> <body>

<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> <body> <script> /*

Declared number will be added by 3 in the given code */ let x = 5; document.write(x+3); </script> </body> </html>

Do It Yourself 5A

1 Match the following.

Column A

Single-line comment let

Keyword ===

Equal value and equal type operaor /* Text */

Multi-line comment // Text

2 What will be the output of the following statement? //document.write(“Hello”);

Conditional Statements in JavaScript

Column B

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

<html> <body> <script> var a=20;

Output

Value of a is less than 100

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

} 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> <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> a is equal to 50

Solved Examples

Example 5.10

Write a code in JavaScript to find out whether the number is even or odd.

Code

<html> <body> <script> var a=51; if(a%2==0){ document.write(“Given number a is even”); } else{

Output

Given number a is odd

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 Output <html> <body>

JavaScript

Number is negative

<h2> JavaScript</h2> <script> var a=−30; if(a>0){ document.write(“Number is positive”); } else{ document.write(“Number is negative”); } </script> </body> </html>

1 Write a code in JavaScript to calculate the area of a triangle.

What is the difference between getElementById() and window.alert()? Think and Tell

2 Write a program to compute quotient and remainder of the expression (85796/52).

Chapter Checkup

A Fill in the Blanks.

1 was the original name of JavaScript when it was first created.

2 JavaScript was created by .

3 Multi-line comments start with .

4 is used to declare variables.

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 d   if… elif… else

Hints let  /* */  Brendan Eich  Mocha

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

E Answer the Following.

1 What is JavaScript?

2 Define some features of JavaScript.

3 Write the names of different types of JavaScript operators.

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.

1

HTML Forms 6

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

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

<label for=”dob”>Date of Birth:</label>

<input type=”date” id=”dob” name=”dob” required>

Output

5 Radio Buttons: The Radio button option allows users to select one option from a list. Use the type=”radio” attribute:

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 Output

<label for=”address”>Address:</label>

<textarea id=”address” name=”address” rows=”4” required>

The <button> Element

Did You Know?

How is a text input field different from a password input box?

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.

Example 6.8

Code

<button type=”button”> Login </button> <button type=”button”> Cancel </button>

The <select> Element

Output

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

<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

Output

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

<html> <head>

<title>Student Details Form</title> </head> <body>

<h1>Student Details</h1> <form>

Code

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

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>

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.

Here is an example of a form with attributes:

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.

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

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

<html> <head>

<title>Form Styling</title> <style>

Code

/* 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>

Output

Do It Yourself 6A

1 Who Am I?

a I am a button that allows users to select one option from a list.

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.

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 inline  <textarea>  <form>  radio  required

1 HTML is used to create a space where users can provide information by using various interactive options.

2 The element is used for long text input, such as comments or messages.

3 The type attribute is used for radio buttons, allowing users to select one option from a list.

4 The attribute makes a field mandatory in an HTML form.

5 Setting properties of a form using internal CSS is also known as CSS.

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 email b   text

c   password

d   radio

3 Which of the following elements helps create a drop-down menu in HTML forms?

a <input>

c   <textarea>

4 Which attribute can be used to apply a specific format?

b   <select>

d   <button>

a required b   pattern

c   validate d   specific

5 What is the purpose of the <button> element in HTML forms?

a To display text

c   To submit the form

C Write T for True and F for False.

b   To create hyperlinks

d   To add images

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

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

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.

A. Fill in the blanks.

1 A language that is formed using and is called a low-level language.

2 The if statement is used to execute a statement only when the given condition becomes .

3 property is used to align the text horizontally within a box.

4 The element is used to create buttons within forms.

B. Tick () the correct option.

1 A loop repeats a statement or a block of statements as long as the looping condition remains true.

a  for b  while

c  do-while d  nested

2 sets the space around the content of the element.

a  Margin b  Border

c  Opacity d  Padding

3 operators are used in logical expressions to determine their equality or differences in variables or values.

a  Arithmetic b  Assignment

c  Comparison d  All of these

C. Write T for True and F for False.

1 A class is a blueprint or template for creating objects.

2 Several else-if blocks are possible in Java.

3 The continue statement is used to exit a loop.

4 The combination of opening tag, content and closing tag is known as element.

D. Answer the following questions.

1 What is a compiler?

2 Describe the nextBoolean() methods used in Java.

3 What are jump statements?

4 Define CSS.

E. Apply your learning.

1 What will be the output of the given program? class Product{ public static void main(String[] args){ System.out.println(“20 x 50 = “ + 20 * 50); } }

2 Manish’s teacher asked him about a form attribute that specifies the URL to which the form data will be submitted. Help him give the answer.

About the Book

This coding book is supplementary to the main “Mel and 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 progression, real-life examples, and practice problems.

Special Features

• Project-based learning: Engaging hands-on projects encouraging practical application of computer science and coding.

• Code snippets: Complete code for each activity with output facilitating hands-on learning and immediate feedback.

• Coding challenges: Includes projects through which learners can demonstrate their learning outcomes in coding and computer science.

• Test Papers: Designed to evaluate understanding of core concepts and application of skills.

About Uolo

Uolo partners with K-12 schools to provide technology-enabled learning programs. We believe that pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. Uolo is trusted by over 15,000+ schools across India, Southeast Asia, and the Middle East.

hello@uolo.com

ISBN 978-81-981317-1-3

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.