Sei sulla pagina 1di 113

Participation Guide for Students

Centum- Foundation Student’s Participation Guide

1
Centum- Foundation Student’s Participation Guide

How to use the participant Guide

This Participant Guide is designed as an aid for you to use during the Arise by Aricent
Project. It will facilitate you in your theoretical and practical sessions. After reading
this guide, it’s easy to focus on the contents and topics which are being delivered to
you in classroom sessions. It will track of all of things that are covered during your
training program, you can jog your memory by referring to the content summaries
provided here. Or you can refer to the summaries afterwards as you continue to reflect
on the Lab sessions. Every session has some technical questionnaire at the end. Please
make use of the material provided here as you see fit to enhance your experience with
the course. Here is some more detailed information about what you will find in this
guide.

Part Overview

This part is specifically designed to provide an Overview of topics covered during the
Face to Face training, that gives a sense of ground covered in that particular session
of course curriculum. The main idea for individual sessions is quick navigation to the
session contents.

Questions for Reflection

At the end of every session, you will find some objective or subjective questions,
which will help you to elaborate your fundamental concepts covered during classroom
training sessions.

2
Centum- Foundation Student’s Participation Guide

Contents

Java Introduction and fundamentals ............................................................................................................... 4


Java OOPs concepts ....................................................................................................................................... 25
Exception Handling in Java............................................................................................................................. 38
Arrays ............................................................................................................................................................. 44
Strings in Java ................................................................................................................................................. 49
Multithreading in Java ................................................................................................................................... 52
Collection Framework .................................................................................................................................... 58
RDBMS ........................................................................................................................................................... 64
SQL ................................................................................................................................................................. 71
JDBC ............................................................................................................................................................... 80
HTML5+CSS+Bootstrap .................................................................................................................................. 85
Introduction to Bootstrap .............................................................................................................................. 90
Introduction to Angular ................................................................................................................................. 95
J2EE ................................................................................................................................................................ 99

3
Centum- Foundation Student’s Participation Guide

Java Introduction and fundamentals

Module Overview
Welcome to the module, Introduction to Java. This module introduces object-
oriented concepts and the Java programming language. The module begins with a brief
explanation of object-oriented concepts. It introduces Java as a platform and as a
programming language. It further explains the Java Development Kit (JDK), Java
Virtual Machine (JVM), and demonstrates how to write and execute a Java application
program. Finally, it provides an overview on writing comments in Java programs.
In this module, you will learn about:
History of Java
Versions of Java
Getting Started with Java
Introduction to JDK
Java Virtual Machine
Writing a Java program
Eclipse IDE installation
Using Comments in Java
The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry
4
Centum- Foundation Student’s Participation Guide

at the time. The history of java starts from Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for digital devices
such as set-top boxes, televisions etc. But, it was suited for internet programming.
Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted and Dynamic".
Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-
top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many
countries like U.S.A., France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) Why had they chosen java name for java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary", "Silk",
"jolt", "DNA" etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to
say.
According to James Gosling "Java was one of the top choices along with Silk". Since
java was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in (January 23, 1996).

5
Centum- Foundation Student’s Participation Guide

Java has three different development environments:


JSE: Java Platform, Standard Edition or Java SE is a widely used platform for
programming in the Java language. It is the Java Platform used to deploy portable
applications for general use.
JEE: The Java platform Enterprise Edition differs from the Java Standard Edition
Platform (JSE) in that it adds libraries which provide functionality to deploy fault-
tolerant, distributed, multi-tier Java software, based largely on modular components
running on an application server.
JME: Java Platform, Micro Edition, or Java ME, is a Java platform designed for
embedded systems (mobile devices are one kind of such systems). Target devices
range from industrial controls to mobile phones (especially feature phones) and set-
top boxes.
Evolution of Java
Java has, over the years, undergone a series of changes and evolved into the robust
language that it is today. The different stages of evolution of Java are:
Java Origins: Embedded Systems (1991-1994)
In 1991, a team of engineers from Sun Microsystems wanted to design a language for
electronic devices, such as television, ovens, washing machines, and so on. Thus, the
basic objective behind developing the language was to create software that could be
embedded in consumer electronic devices. In C and C++ languages the compilers were
targeted for a particular CPU.
Compilers are expensive and a lot of time is required to create these. Hence, it was not
possible to have compilers for every CPU. An easy and cost efficient way was needed
for creating compilers. In addition, the software had to be small, fast, efficient and
platform independent, that is, a code that could run on different CPUs under different
environments. Efforts were taken to produce a portable, platform independent
language, and the result of this led to the creation of Java. James Gosling and a team
of other programmers were the pioneers behind this development. It was initially
called ‘Oak’, but was later renamed to Java.
Java: A Client-side Wonder (1995-1997)
In 1995, Web pages did not have dynamic capability. Java provided this capability.
Later, Java gained popularity and served as ideal software for network computers.
Java: Moved into the Middle-tier (1997 to Present)

6
Centum- Foundation Student’s Participation Guide

In the late 1990’s, Sun revised middle-tier capabilities for Java to ensure that it runs
on Web/Application Servers. In 1997, Sun defined Servlets for Java to generate
dynamic HTML Web pages. Sun also defined Enterprise JavaBeans (EJB) so that
business logic can be developed in Java. In 1999, Sun offered a middle-tier solution
for Java called Java 2 Enterprise Edition (J2EE).
Future
In future, Java may gain more success on the client-side. Improved Java performance
and the introduction of Java 2 Micro Edition have opened the door for increased use
of Java in embedded devices.
Java Architecture
There are three main components of Java
JDK: java development kit
It is responsible for development and execution of Java application.
It contains JRE + development tools.

JRE: Java Runtime environment:


It is responsible to execute Java application.
It implements JVM and physically exists.
It contains JVM and Library files (jar files)
7
Centum- Foundation Student’s Participation Guide

JVM: Java virtual Machine


It is responsible to provide runtime environment in which java bytecode can be
executed.
It is available for different hardware and software platforms.
Although JAVA is platform independent, JDK, JRE and JVM are platform dependent.
JVM performs:
Code loading
Verifying code
Execute code
Provides runtime environment

JVM Components

8
Centum- Foundation Student’s Participation Guide

Class loader Is a subsystem of JVM which is used to load class files


during application execution

Class area This memory area is used to provide space for class data.

Heap This memory area is related with DMA and is used for
object data

Stack It contains frames and related with local and partial data.
Every method invocation is related with a separated
thread. After the termination of method, this memory
will be de-allocated.

PC register It contains the address of currently executing instruction


of JVM

Native method stack All the native methods those are being used in JAVA
application will be stored in this memory area.

Execution engine It is responsible for executing the code. It has Interpreter


and JIT compiler. Interpreter reads the code line by line
and executes it. JIT is used for better performance.

Environment to compile and execute


Download the latest version of Java from:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Download Java based on the type of OS
Windows
Linux
Mac OS
Solaris
Install JDK
9
Centum- Foundation Student’s Participation Guide

Set the PATH variable as follows on Microsoft Windows:


Click Start, then Control Panel, then System.
Click Advanced System settings, then Environment Variables.
Add the location of the bin folder of the JDK installation for the PATH variable in
System Variables e.g.
PATH= C:\Java\jdk1.7.0\bin;%PATH%

Java Hello World Program


To keep things simple and working for students, here is the sample hello world
program that you can use:

Compile and Run Java Hello World Program


Open Command Prompt and go to the directory where java hello world program file
is saved. Then run below commands in order.

Variables and Constants


It's common to encounter the following definition of a variable. A variable is a
container which holds values that are used in a Java program.
All variables are divided into 4 groups:
Variables of an integer type (among these are byte, short, int, long)
Floating point variables (among these are float, double)
Symbols (char)
Logic variables (boolean)
10
Centum- Foundation Student’s Participation Guide

Data Type and Range

Before using a variable, you need to declare it. A variable is declared in the
following manner:

11
Centum- Foundation Student’s Participation Guide

It’s necessary to mention that if the name of a variable consists of two or more words
it should be written as one word (without spaces), like the humps of a camel. This
style of writing is called CamelStyle.
Java Access Modifiers
We can use java access modifiers with Classes as well as Class variables and methods.
We are allowed to use only “public” or “default” access modifiers with java classes.
If a class is “public” then we can access it from anywhere, i.e. from any other class
located in any other packages etc.
We can have only one “public” class in a source file and file name should be same as
the public class name.
If the class has “default access” then it can be accessed only from other classes in the
same package.
Control Flow Statements in Java
Decision making in programming is similar to decision making in real life. In
programming also we face some situations where we want a certain block of code to
be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of
program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.
Java’s Selection statements:
➢ if
➢ if-else
➢ nested-if
➢ if-else-if
➢ switch-case
➢ jump – break, continue, return

12
Centum- Foundation Student’s Participation Guide

These statements allow you to control the flow of your program’s execution based
upon conditions known only during run time.
If Construct: if statement is the most simple decision making statement. It is used to
decide whether a certain statement or block of statements will be executed or not i.e.
if a certain condition is true then a block of statement is executed otherwise not.

If-else: if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something
else if the condition is false. Here comes the else statement. We can use the else
statement with if statement to execute a block of code when the condition is false.
Syntax:

Nested-if: A nested if is if statement that is the target of another if or else. Nested if


statements means if statement inside if statement. Yes, java allows us to nest if
statements within if statements i.e. we can place if statement inside another if
statement.

Syntax:

13
Centum- Foundation Student’s Participation Guide

if-else-if ladder: In this type of construct a user can decide among multiple options.
Here if statements are executed from the top down. As soon as one of the conditions
controlling the flow of program is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed.
Syntax:

switch-case: The switch statement is a multi-way branch statement. It provides an


easy way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:

14
Centum- Foundation Student’s Participation Guide

Note:
Expression can be of type byte, short, int char or an enumeration. Beginning with
JDK7, expression can also be of type String.
Duplicate case values are not allowed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
The break statement is optional. If omitted, execution will continue on into the next
case.

Jumping Statements: Java supports three jump statement: break,


continue and return. These three statements transfer control to other part of the
program.
Break: In Java, break is majorly used for:
Terminate a sequence in a switch statement (discussed above).
To exit a loop.
Used as a “civilized” form of goto.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the
innermost loop.

15
Centum- Foundation Student’s Participation Guide

Continue: Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder of the code
in its body for this particular iteration. This is, in effect, a goto just past the body of
the loop, to the loop’s end. The continue statement performs such an action.

Return: The return statement is used to explicitly return from a method. That is, it
causes a program control to transfer back to the caller of the method.

Loops in Java
Looping in programming languages is a feature which facilitates the execution of a
set of instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide similar
basic functionality, they differ in their syntax and condition checking time.
16
Centum- Foundation Student’s Participation Guide

While loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
Syntax:

While loop starts with the checking of condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason it is also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for
the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.

for loop: for loop provides a concise way of writing the loop structure. Unlike a
while loop, for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug structure
of looping.
Syntax:

Initialization condition: Here, we initialize the variable in use. It marks the start of a
for loop. An already declared variable can be used or a variable can be declared, local
to loop only.

17
Centum- Foundation Student’s Participation Guide

Testing Condition: It is used for testing the exit condition for a loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to
the execution of the loop statements.
Statement execution: Once the condition is evaluated to true, the statements in the
loop body are executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination: When the condition becomes false, the loop terminates marking
the end of its life cycle.

Enhanced For loop


Java also includes another version of for loop introduced in Java 5. Enhanced for loop
provides a simpler way to iterate through the elements of a collection or array. It is
inflexible and should be used only when there is a need to iterate through the elements
in sequential manner without knowing the index of currently processed element.
Syntax:

Example:

18
Centum- Foundation Student’s Participation Guide

do while: do while loop is similar to while loop with only difference that it checks for
condition after executing the statements, and therefore is an example of Exit Control
Loop.
Syntax:

do while loop starts with the execution of the statement(s). There is no checking of
any condition for the first time.
After the execution of the statements, and update of the variable value, the condition
is checked for true or false value. If it is evaluated to true, next iteration of loop starts.

19
Centum- Foundation Student’s Participation Guide

When the condition becomes false, the loop terminates which marks the end of its life
cycle.
It is important to note that the do-while loop will execute its statements at least once
before any condition is checked, and therefore is an example of exit control loop.

Operators in Java
An operator, in Java, is a special symbols performing specific operations on one, two
or three operands and then returning a result. The operators are classified and listed
according to precedence order. Java operators are generally used to manipulate
primitive data types. The Java operators are classified into eight different categories:
assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional
and type comparison operators.

Java provides many types of operators which can be used according to the need. They
are classified based on the functionality they provide. Some of the type of operators
are-
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator
Bitwise Operators
Shift Operators

Java programs are organized in the form of classes. Every class is part of some
package. Java scope rules can be covered under following categories.

Member Variables (Class Level Scope)


These variables must be declared inside class (outside any function). They can be
directly accessed anywhere in class. Let’s take a look at an example:
20
Centum- Foundation Student’s Participation Guide

We can declare class variables anywhere in class, but outside methods.


Access specified of member variables doesn’t affect scope of them within a class.
Member variables can be accessed outside a class with following rules

Local Variables (Method Level Scope)


Variables declared inside a method have method level scope and can’t be accessed
outside the method.
********************************************************************

Check Your Progress


Exercise 1
You have been given a computer system that will be used for Java SE latest version
software development. You must validate that the Java SE Development Kit is
installed, the Eclipse latest version is installed and correctly configured to use JDK.
Write the steps.
Exercise 2
Create a class named Employee having following fields:
Field Use Recommended field type
Employee-id int
Employee-name String
Employee-SSN String
Employee-salary double

Ensure use setters and getters to assign and print the result.
Create a class with main method to test the Employee class, compile and run your
application through cmd.
Exercise 3
John needs to write a program to calculate the total distance travelled by a vehicle. To
calculate the distance, John can use the following formula:
Distance=ut + (at2) /2

21
Centum- Foundation Student’s Participation Guide

Here, u is the initial velocity (meters per second), a is the acceleration (meters per
second2) and t is the time (seconds). Help John to perform the desired task.
Exercise 4
Write a program to display the postfix and prefix values of the number 5, by using
increment operators.
Exercise 5
Write a program to create a class named EmployeeDetails and display a menu similar
to the following menu:
-----------------------Menu---------------------
Enter Data
Display Data
Exit
Choose the option:

Thereafter, invoke the respective method according to the given menu input. The
methods will contain appropriate messages, such as the displayData() method will
contain the message, displayData method is invoked.

Exercise 6
Write a program to create a class that stores the train reservation details. In addition,
define a method that will display the stored details.
Exercise 7
The maximum points you can get in the written exam to my lecture is 120. At 60
points you have passed the exam (grade 4.0). For every additional 5 points the next
better grade. Because of jurisdictional problems, the grade 4.3 does not exist (it is 4.7,
too, in that case). It is possible to get 0.5 points for your solutions in the exam. The
following table shows the mapping between points and their grades:
grade points
5.0 0 - 49.5
4.7 50 - 59.5
22
Centum- Foundation Student’s Participation Guide

4.0 60 - 64.5
3.7 65 - 69.5
3.3 70 - 74.5
3.0 75 - 79.5
2.7 80 - 84.5
2.3 85 - 89.5
2.0 90 - 94.5
1.7 95 - 99.5
1.3 100 - 104.5
1.0 105 - 120
Implement a Java-function that returns the grade for the points reached in the exam
and prints out the grade for all points from 0 to 120 (in steps of 0.5).
Exercise 8

HarmonicSum (Loop):

Write a program called HarmonicSum to compute the sum of a harmonic series, as


shown below, where n=50000. The program shall compute the sum from left-to-
rightas well as from the right-to-left. Obtain the difference between these two sums
and explain the difference. Which sum is more accurate?

Exercise 9
Check Your Progress

CozaLozaWoza (Loop & Condition):

23
Centum- Foundation Student’s Participation Guide

Write a program called CozaLozaWoza which prints the numbers 1 to 110, 11


numbers per line. The program shall print "Coza" in place of the numbers which are
multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7, "CozaLoza" for
multiples of 3 and 5, and so on. The output shall look like:
1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11
Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22
23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza
......

24
Centum- Foundation Student’s Participation Guide

Java OOPs concepts

In this section, we will learn about basics of OOPs. Object Oriented Programming is
a paradigm that provides many concepts such as inheritance, data
binding, polymorphism, inheritance etc.
Simula is considered as the first object-oriented programming language. The
programming paradigm where everything is represented as an object, is known as truly
object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming language.
The popular object-oriented languages are Java, C#, PHP, Python, C++ etc.
The main aim of object oriented programming is to implement real world entities i.e.
object, classes, abstraction, inheritance, polymorphism etc.
OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some
concepts:
➢ Object
➢ Class
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Encapsulation

25
Centum- Foundation Student’s Participation Guide

Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Object can be defined as an instance of a class. An object contains an address and
takes up some space in memory. Objects can communicate without knowing details
of each other's data or code, the only necessary thing is that the type of message
accepted and type of response returned by the objects.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which we can create an individual
object. Class doesn’t store any space.
Inheritance
When one object acquires all the properties and behaviors of parent object, it is known
as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Java Naming conventions

26
Centum- Foundation Student’s Participation Guide

Java naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method etc.
All the classes, interfaces, packages, methods and fields of java programming
language are given according to java naming convention.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for
yourself and for other programmers. Readability of Java program is very important. It
indicates that less time is spent to figure out what the code does.

CamelCase in java naming conventions


Java follows CamelCase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter
always e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.
Object and Class in Java
In this section, we will learn about java objects and classes. In object-oriented
programming technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java

27
Centum- Foundation Student’s Participation Guide

An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tangible and intangible). The example
of intangible object is banking system.
An object has three characteristics:
State: represents data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects
are created. So object is the instance (result) of a class.
Object Definitions:
Object is a real world entity.
Object is a run time entity.
Object is an entity which has state and behavior.
Object is an instance of a class.
Class in Java

28
Centum- Foundation Student’s Participation Guide

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
➢ fields
➢ methods
➢ constructors
➢ blocks
➢ nested class and interface
Syntax to declare a class:

Instance variable in Java


A variable which is created inside the class but outside the method, is known as
instance variable. Instance variable doesn't get memory at compile time. It gets
memory at run time when object (instance) is created. That is why, it is known as
instance variable.
Method in Java
In java, a method is like function i.e. used to expose behavior of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword in Java
The new keyword is used to allocate memory at run time. All objects get memory in
Heap memory area.
Object and Class Example: main within class
In this example, we have created a Student class that has two data members, id and
name. We are creating the object of the Student class by new keyword and printing
the objects value.
Here, we are creating main () method inside the class.
29
Centum- Foundation Student’s Participation Guide

File: Student.java

Ways to initialize object


There are 3 ways to initialize object in java.

1. By reference variable:

30
Centum- Foundation Student’s Participation Guide

2. By method

3. By constructor

31
Centum- Foundation Student’s Participation Guide

Constructor in Java
In Java, constructor is a block of codes similar to method. It is called when an instance
of object is created and memory is allocated for the object.
It is a special type of method which is used to initialize the object.
When a constructor is called
Every time an object is created using new () keyword, at least one constructor is called.
It is called a default constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
Rules for creating java constructor
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors
There are two types of constructors in java:
Default constructor (no-arg constructor): Constructor without having any parameter
is called as Default constructor.
Syntax:

Parameterized constructor: Constructor having the number of parameters, is called as


parameterized constructor.

32
Centum- Foundation Student’s Participation Guide

Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of parent class. Moreover, you can add new methods and fields in your
current class also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

33
Centum- Foundation Student’s Participation Guide

Reusability: As the name specifies, reusability is a mechanism which facilitates you


to reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in previous class.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class
and the new class is called child or subclass.

Types of Inheritance
➢ Single inheritance
➢ Multiple inheritance (Does not exists in Java)
➢ Multi-level inheritance
➢ Hierarchical inheritance
➢ Hybrid inheritance
Method overloading in Java
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a (int int) for two parameters,
and b (int, int, int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
34
Centum- Foundation Student’s Participation Guide

Method overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
In other words, if subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
Method must have same name as in the parent class
Method must have same parameter as in the parent class.
Must be IS-A relationship (inheritance).
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by
different ways. Polymorphism is derived from 2 greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means many
forms.
There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism.
Here, we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call
to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

35
Centum- Foundation Student’s Participation Guide

Let's first understand the upcasting before Runtime Polymorphism.


Upcasting
When reference variable of Parent class refers to the object of Child class, it is known
as upcasting. For example:

A a=new B (); //upcasting

********************************************************************

Check Your Progress


Exercise 1
Write a program that stores the details of the Software and Hardware books. The
Software book includes the software version and software name. The Hardware book
includes the hardware category and publisher. However, both the books include some
common details, such as author name, title, price and number of pages. Therefore, you
need to store and display the book details by implementing the code reusability in the
program.
Exercise 2
Write a program to store the details of football team players, such as name, age,
number of matches played, ranking and number of goals made. For this, you need to
store the details of 15 players, which include goal-keeper and extras. In addition, you
need to create three separate lists of 11 players for the triangular tournaments.
Moreover, you need to arrange players according to their ranking in the respective
lists.
Exercise 3
What will be the output of following code?
36
Centum- Foundation Student’s Participation Guide

37
Centum- Foundation Student’s Participation Guide

Exception Handling in Java

The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between
checked and unchecked exceptions.
The definition of exception
Tradition definition: Exception is an abnormal condition.
Technical definition: In java, exception is an event that disrupts the normal flow of
the program. It is an object which is thrown at runtime.
Why we use exceptions in program?
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is
why we use exception handling.
Hierarchy of Java Exception classes

Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types
of exceptions:

38
Centum- Foundation Student’s Participation Guide

Checked Exception
Unchecked Exception
Error
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
➢ try
➢ catch
➢ finally
➢ throw
➢ throws
Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
Java try block must be followed by either catch or finally block.
Syntax of try-catch block

39
Centum- Foundation Student’s Participation Guide

Syntax of try-finally block

Java catch block


Java catch block is used to handle the Exception. It must be used after the try block
only.
We can use multiple catch block with a single try.
Working of Java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.

40
Centum- Foundation Student’s Participation Guide

Java finally block


Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Note: Why use java finally
Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.

Java throw keyword


The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
The syntax of java throw keyword is given below.
41
Centum- Foundation Student’s Participation Guide

throw exception;
throw new IOException(“This is Input Output Exception”);

********************************************************************

Check Your Progress

Exercise 1
Explain the differences between checked and unchecked exceptions in java?
Exercise 2
Demonstrate that a derived-class constructor cannot catch exceptions thrown by its
base-class constructor.
Exercise 3
Write a program to handle custom Exception as per the following conditions given:
Create a class Student having following fields:
Field Use Recommended field type
Student-id int
Student-name String (the length should be in between
3-10 characters)
Student-age int (in between 15-18)
Student-marks of 5 subjects Array (in between 0-100)

Assume appropriate Error messages as per the conditions. If no exception then display
output in presentable format.
Exercise 4
What will be the output of following code?

42
Centum- Foundation Student’s Participation Guide

43
Centum- Foundation Student’s Participation Guide

Arrays

Unlike C++, arrays are first class objects in Java. For example, in the following
program, size of array is accessed using length which is a member of arr [] object.

An array holds elements that have the same data type.


2) Array elements are stored in subsequent memory locations.
3) Two-dimensional array elements are stored row by row in subsequent memory
locations.
4) Array name represents the address of the starting element.
5) Array size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.
6) Array consumes memory at the time of compilation of program, it is also called as
static memory allocation.
7) The memory of Array cannot be modified once it is allocated.
Default array values in Java
If we don’t assign values to array elements, and try to access them, compiler does not
produce error as in case of simple variables. Instead it assigns values which aren’t
garbage.
Below are the default assigned values.
boolean : false
int : 0
44
Centum- Foundation Student’s Participation Guide

double : 0.0
String : null
User Defined Type : null
Types of Arrays in Java
Single dimensional array: Elements are arranged in linear fashion. Only one index is
required to access the element.

Multi-dimensional array: Elements are stored in form of multiple rows and columns.
To access any element, we need two indices.

Working with matrices:

Working with Matrices

• Filling by list - Just as working with a one-dimensional array, it is possible to fill a


two dimensional array by using a list at the time the array is declared.

Notice the "sets" of braces "within" the list denoting the "array of arrays".

int [ ] [ ] scores = {
{ 20, 18, 22, 20, 6},
{ 18, 20, 18, 21, 20},
{ 16, 18, 16, 20, 24 },
{ 25, 24, 22, 24, 25 }
};

45
Centum- Foundation Student’s Participation Guide

• No filling when declared - When an array is created it is automatically filled with


a zero (for numerical values), a false (for boolean values) or null (for String values).

• Filling with user input - When working with two-dimensional arrays (such as
accessing, filling, printing, etc.), it is necessary to use nested loops. The outer loop
controls the number of rows and the inner loop controls the number of columns.

// Filling the matrix


for (row = 0; row < 4; row ++ ) {
for ( column = 0; column < 5; column + + )
{
scores [ row ] [ column ] = Console.readInt ("Enter score " + column + "for
contestant " + row );
}
}

Jagged array: In this type of array, all the rows contain different number of elements.
Student.java

46
Centum- Foundation Student’s Participation Guide

StudentArray.java

********************************************************************

Check Your Progress


Exercise 1
Write a menu driven program which has following options:
(1) Insert element
(2) Delete element
(3) Update element
(4) Display array
(5) Exit
Write a program to use above options step by step using choice from user. Handle the
situations of Overflow, underflow, element not found etc.
Elements must be stored in array in ascending order.
Program will continue till user enter choice for Exit. (Hint: use infinite loop)

Exercise 2
Write a Java program to display Transpose matrix.

47
Centum- Foundation Student’s Participation Guide

Exercise 3
Write a Java program to display upper triangular matrix.

Exercise 4
Write a Java program to swap two rows and columns in Matrix.

Exercise 5
Write a Java program to display the largest number row wise and column wise and
display it in presentable manner.

48
Centum- Foundation Student’s Participation Guide

Strings in Java
Strings, which are widely used in Java programming, are a sequence of characters. In
Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String
object with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and
a constructor. The String class has 11 constructors that allow you to provide the initial
value of the string using different sources, such as an array of characters.
Note − The String class is immutable, so that once it is created a String object cannot
be changed. If there is a necessity to make a lot of modifications to Strings of
characters, then you should use String Buffer & String Builder Classes.
StringBuffer class in Java
String Class in Java

StringBuffer is a peer class of String that provides much of the functionality of


strings. String represents fixed-length, immutable character sequences while
StringBuffer represents grow able and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended
to the end. It will automatically grow to make room for such additions and often has
more characters pre-allocated than are actually needed, to allow room for growth.

StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-synchronized. It
is available since JDK 1.5.
Difference between StringBuffer and StringBuilder

49
Centum- Foundation Student’s Participation Guide

There are many differences between StringBuffer and StringBuilder. A list of


differences between StringBuffer and StringBuilder are given below:

********************************************************************

Check Your Progress

Exercise 1
Write down the differences among String, StringBuilder and StringBuffer classes in
Java.
Exercise 2
Write a java program to remove a particular character from the given String.
Exercise 3
Write a java program to convert a string into:
Lowercase
Uppercase
Title Case
Sentence Case
Exercise 4
An anagram is a word or a phrase made by transposing the letters of another word or
phrase; for example, "parliament" is an anagram of "partial men," and "software" is
an anagram of "swear oft." Write a program that figures out whether one string is an
anagram of another string. The program should ignore white space and punctuation.
50
Centum- Foundation Student’s Participation Guide

Exercise 5
Write a program that computes your initials from your full name and displays them.

51
Centum- Foundation Student’s Participation Guide

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously.


Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a
single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process have its own address in memory i.e. each process allocates separate
memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
52
Centum- Foundation Student’s Participation Guide

Cost of communication between the thread is low.


What is Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a separate
path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
New: The thread is in new state if you create an instance of Thread class but before
the invocation of start () method.
Runnable: The thread is in runnable state after invocation of start () method, but the
thread scheduler has not selected it to be the running thread.
Running: The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked): This is the state when the thread is still alive, but is
currently not eligible to run.
Terminated: A thread is in terminated or dead state when its run () method exits.

53
Centum- Foundation Student’s Participation Guide

Creating Threads in Java


There are two ways of creating Threads in Java:
By extending Thread class
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r, String name)
By implementing Runnable interface.
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run ().
public void run (): is used to perform action for a thread.

54
Centum- Foundation Student’s Participation Guide

start() method of Thread class is used to start a newly created thread. It performs
following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run () method will run.

********************************************************************

Check Your Progress


Exercise 1
What will be the output of following code?

Exercise 2

55
Centum- Foundation Student’s Participation Guide

Exercise 3

Exercise 4

Exercise 5

56
Centum- Foundation Student’s Participation Guide

57
Centum- Foundation Student’s Participation Guide

Collection Framework

A Collection is a group of individual objects represented as a single unit. Java provides


Collection Framework which defines several classes and interfaces to represent a
group of objects as a single unit.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are
two main root interfaces of Java collection classes.
Need for Collection Framework:
Before Collection Framework (or before JDK 1.2) was introduced, the standard
methods for grouping Java objects (or collections) were array or Vector or Hashtable.
All three of these collections had no common interface.
Advantages of Collection Framework:
Consistent API: The API has basic set of interfaces like Collection, Set, List, or Map.
All those classes (such as ArrayList, LinkedList, Vector etc) which implements, these
interfaces have some common set of methods.
Reduces programming effort: The programmer need not to worry about design of
Collection rather than he can focus on its best use in his program.
Increases program speed and quality: Increases performance by providing high-
performance implementations of useful data structures and algorithms.

58
Centum- Foundation Student’s Participation Guide

List Implementation

The List interface is the base interface for collections which allows to store objects in
a resizable container.

ArrayList and LinkedList as implementations

ArrayList is an implementation of this interface and allow that elements are


dynamically added and removed from the list. If more elements are added to
ArrayList than its initial size, its size is increased dynamically. The elements in
an ArrayList can be accessed directly and efficiently by using
the get() and set() methods, since ArrayList is implemented based on an
array. ArrayList is typically used in implementations as implementation class for
the Listinterface.

LinkedList is implemented as a double linked list. Its performance


on add() and remove() is better than the performance of Arraylist.
The get() and set() methods have worse performance than the ArrayList, as
the LinkedList does not provide direct access to its members.

Java LinkedList class

59
Centum- Foundation Student’s Participation Guide

Java LinkedList class uses doubly linked list to store the elements. It provides a linked-
list data structure. It inherits the AbstractList class and implements List and Deque
interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non-synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be
occurred.
o Java LinkedList class can be used as list, stack or queue.

Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion
order. Both are non-synchronized classes.

But there are many differences between ArrayList and LinkedList classes that are
given below.

package com.example.java.collections.list;
import java.util.ArrayList;
import java.util.List;

public class ListExample {


public static void main (String[] args) {
// use type inference for ArrayList
60
Centum- Foundation Student’s Participation Guide

List<Integer> list = Arrays.asList (3, 2, 1, 4, 5, 6, 6);

// alternative you can declare the list via:


// List<Integer> list = new ArrayList<>( );
// and use list.add(element); to add elements
for (Integer integer: list) {
System.out.println(integer);
}
}

Iterator interface
Iterator interface provides the facility of iterating the elements in forward
direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

Java List Interface

List Interface is the sub interface of Collection. It contains methods to insert and delete
elements in index basis. It is a factory of ListIterator interface.

List Interface declaration


public interface List<E> extends Collection<E>

Methods of ListIterator Interface

61
Centum- Foundation Student’s Participation Guide

********************************************************************
Check Your Progress
Exercise 1
What is the difference between ArrayList and Vector class?

Exercise 2
Explain the concept of Set Interface using suitable program.

Exercise 3
Explain the difference among HashSet, TreeSet and LinkedHashSet.

Exercise 4
Write a menu driven program to implement the concept of Stack using appropriate
Collection.
Exercise 5
Write a program to implement the ascending order sort on Student class on the basis
of marks field. Student class has following layout:
62
Centum- Foundation Student’s Participation Guide

Class Student {
int student_id;
String Name;
int age;
int marks;

// use appropriate methods


}

63
Centum- Foundation Student’s Participation Guide

RDBMS

Most of the problems faced at the time of implementation of any system are outcome
of a poor database design. In many cases it happens that system has to be continuously
modified in multiple respects due to changing requirements of users. It is very
important that a proper planning has to be done. A relation in a relational database is
based on a relational schema, which consists of number of attributes. A relational
database is made up of a number of relations and corresponding relational database
schema. The goal of a relational database design is to generate a set of relation schema
that allows us to store information without unnecessary redundancy and also to
retrieve information easily. One approach to design schemas that are in an appropriate
normal form. The normal forms are used to ensure that various types of anomalies and
inconsistencies are not introduced into the database.

RDBMS stands for Relational Database Management System. RDBMS data is


structured in database tables, fields and records. Each RDBMS table consists of
database table rows. Each database table row consists of one or more database table
fields. RDBMS store the data into collection of tables, which might be related by
common fields (database table columns). RDBMS also provide relational operators to
manipulate the data stored into the database tables. Most RDBMS use SQL as database
query language. The most popular RDBMS are MS SQL Server, DB2, Oracle and
MySQL. The relational model is an example of record-based model. Record based
models are so named because the database is structured in fixed format records of
several types. Each table contains records of a particular type. Each record type
defines a fixed number of fields, or attributes. The columns of the table correspond to
the attributes of the record types. The relational data model is the most widely used
data model, and a vast majority of current database systems are based on the relational
model. The relational model was designed by the IBM research scientist and
mathematician, Dr. E.F.Codd. Many modern DBMS do not conform to the Codd’s
definition of a RDBMS, but nonetheless they are still considered to be RDBMS. Two
of Dr.Codd’s main focal points when designing the relational model were to further
reduce data redundancy and to improve data integrity within database systems.
The relational model originated from a paper authored by Dr.codd entitled “A
Relational Model of Data for Large Shared Data Banks”, written in 1970. This paper
included the following concepts that apply to database management systems for
relational databases. The relation is the only data structure used in the relational data
model to represent both entities and relationships between them. Rows of the relation
are referred to as tuples of the relation and columns are its attributes. Each attribute of
64
Centum- Foundation Student’s Participation Guide

the column are drawn from the set of values known as domain. The domain of an
attribute contains the set of values that the attribute may assume. From the historical
perspective, the relational data model is relatively new .The first database systems
were based on either network or hierarchical models .The relational data model has
established itself as the primary data model for commercial data processing
applications. Its success in this domain has led to its applications outside data
processing in systems for computer aided design and other environments.

Data Normalization
Normalization of Database
Database Normalization is a technique of organizing the data in the database. Normalization
is a systematic approach of decomposing tables to eliminate data redundancy(repetition) and
undesirable characteristics like Insertion, Update and Deletion Anamolies. It is a multi-step
process that puts data into tabular form, removing duplicated data from the relation tables.
Normalization is used for mainly two purposes,

• Eliminating reduntant (useless) data.


• Ensuring data dependencies make sense i.e data is logically stored.

Problems Without Normalization


If a table is not properly normalized and have data redundancy then it will not only
eat up extra memory space but will also make it difficult to handle and update the
database, without facing data loss. Insertion, Updation and Deletion Anamolies are
very frequent if database is not normalized. To understand these anomalies let us
take an example of a Student table.

65
Centum- Foundation Student’s Participation Guide

Insertion Anomaly
Suppose for a new admission, until and unless a student opts for a branch, data of the
student cannot be inserted, or else we will have to set the branch information
as NULL.
Also, if we have to insert data of 100 students of same branch, then the branch
information will be repeated for all those 100 students.
These scenarios are nothing but Insertion anomalies.

Updation Anomaly
What if Mr. X leaves the college? or is no longer the HOD of computer science
department? In that case all the student records will have to be updated, and if by
mistake we miss any record, it will lead to data inconsistency. This is Updation
anomaly.

Deletion Anomaly
In our Student table, two different informations are kept together, Student
information and Branch information. Hence, at the end of the academic year, if
student records are deleted, we will also lose the branch information. This is
Deletion anomaly.
Normalization Rule
Normalization rules are divided into the following normal forms:

1. First Normal Form


2. Second Normal Form
3. Third Normal Form
4. BCNF
5. Fourth Normal Form

First Normal Form (1NF)


66
Centum- Foundation Student’s Participation Guide

For a table to be in the First Normal Form, it should follow the following 4 rules:

1. It should only have single(atomic) valued attributes/columns.


2. Values stored in a column should be of the same domain
3. All the columns in a table should have unique names.
4. And the order in which data is stored, does not matter.

Second Normal Form (2NF)


For a table to be in the Second Normal Form,

1. It should be in the First Normal form.


2. And, it should not have Partial Dependency.

Third Normal Form (3NF)


A table is said to be in the Third Normal Form when,

1. It is in the Second Normal form.


2. And, it doesn't have Transitive Dependency.

Boyce and Codd Normal Form (BCNF)


Boyce and Codd Normal Form is a higher version of the Third Normal form. This
form deals with certain type of anomaly that is not handled by 3NF. A 3NF table
which does not have multiple overlapping candidate keys is said to be in BCNF. For
a table to be in BCNF, following conditions must be satisfied:

• R must be in 3rd Normal Form


• and, for each functional dependency ( X → Y ), X should be a super Key.

Fourth Normal Form (4NF)


A table is said to be in the Fourth Normal Form when,

1. It is in the Boyce-Codd Normal Form.


2. And, it doesn't have Multi-Valued Dependency.

67
Centum- Foundation Student’s Participation Guide

********************************************************************
Check Your Progress

Exercise 1
Consider the following Purchase_Details table:

Cust_ID and Store_ID make the composite primary key in the table. Identify the
partial dependency in the table, if any. How can you remove the partial dependency
to attain the next normal form?

Exercise 2
Define the following terms:
Regular entities
Attributes
Relationships
Weak entities
Subtypes and supertypes
Exercise 3

68
Centum- Foundation Student’s Participation Guide

Shopping Spree is a leading departmental store in Shanghai. The store has a number
of regular customers who purchase bulk items. The store also conducts regular
feedback sessions to analyze customer satisfaction levels. Chen, the customer Analyst
of Shopping Spree, has to make the ER diagram to represent the preceding situation,
and then to map the ER diagram to the corresponding tables. Help Chen to do the
same.

Exercise 4
Consider the following Student table:

The preceding table is in the first normal form. How can this table be converted into
the second normal form?
Exercise 5
Fill in the blanks using best option:
Any attribute that uniquely identifies a row in a table is a ________________ for the
primary key.
The key that uniquely identifies each record in the table is a ______________ key.
When the key that uniquely identifies the rows of the table is made up of more than
one attribute, it is called a ____________ key.
Any attribute that is a candidate for the primary key but is not the primary key is called
the _________________ key.
Exercise 6
69
Centum- Foundation Student’s Participation Guide

Tom is working in an organization as a database administrator. Based on the hierarchy,


the organization has multiple departments and each department has multiple
employees. The following ER diagram represents the relationship between the
departments and the employees.

In the preceding diagram, you have to identify entities, their attributes, and type of
relationship between the entities.

70
Centum- Foundation Student’s Participation Guide

SQL
STRUCTURED QUERY LANGUAGE (SQL)

Introduction.

• The Oracle RDBMS is available on many different operating system


platforms including Windows and UNIX.
• Oracle is a relational DBMS - even the data dictionary is simply a collection
of tables of data along with indexes and other objects such as sequences and
triggers.
• SQL has a basic grammar and syntax.
• The functionally of the SQL language is virtually identical across these
operating system platforms.
• Using SQL does not require programming experience, but programming
experience can help you conceptualize what a particular SQL command will
accomplish.
• The keywords for SQL queries that retrieve data
are SELECT, FROM, WHERE, and ORDER BY. Other command options
also exist, but these are the basic ones.

Connecting to the ORACLE Database.

• Directions for connecting to the ORACLE database are given in the web
handout, Getting Started with Oracle that is available on the course web site.

Naming Difficulties.

• When building a schema (meaning the definition of the tables, indexes, and
other objects that comprise a database), it is important to name objects like
tables, columns, indexes with meaningful names. A failure to follow this
naming rule can result in difficulties for users when they are creating queries.
• Oracle allows object names to be up to 30 characters long. Make use of this
capability.
• Here are some rules to follow.
o Don't abbreviate unless it is necessary. Example, it is better to name a
column WorkerName than Wname.
o Be consistent when abbreviating. Don't use EmpNo in one table
and Eno in another table and EmpNumber in still another table.

71
Centum- Foundation Student’s Participation Guide

o The Purpose or Meaning of a column or table must be apparent from


the name. What would be the meaning of a table named Scde (Storage
Code)? A better name would be STORAGECODE.
o If you use Underscores as part of a naming convention, then be
consistent. If you are not consistent, then no one can remember when
to use them and when not to use them.
o Be consistent in using Plurals. Is the name of that table "EMP" or
"EMPS"? Is it "NOTE" or "NOTES"?

SQL BASIC INFORMATION

SQL and UNIX Syntax.

• The SQL syntax used in these notes complies with Oracle’s SQL*PLUS
product.
• UNIX syntax used in these notes complies with most UNIX operating
systems.
• The American National Standards Institute (ANSI) first published ANSI SQL
standards in 1986.
• Oracle Corporation - provides SQL*PLUS (an enhanced version of SQL) as
part of the Oracle RDBMS product. This means that SQL*PLUS has some
non-ANSI standard SQL commands that will not run on other RDBMS
platforms.
• Microsoft Corporation - provides the SQL Server RDBMS software -- a
competitor with Oracle Corporation.

SQL Standards - Their Characteristics and Benefits.

• The ANSI SQL Standard provides:


o Specific syntax and semantics of SQL data definition and data
manipulation languages.
o Basic data structures and operations for designing, assessing,
maintaining, controlling, and protecting an SQL database.
o Portability of applications and database definition. Easy to move
applications from one machine to another.
o Minimal standards for adoption among products claiming to be SQL
compatible.
o Reduced training costs - IS professionals share a common language.
o Productivity - IS professionals can become proficient in its use.
72
Centum- Foundation Student’s Participation Guide

o Application longevity - A language tends to remain standard for a long


time.
o Reduced dependence on a single vendor.

SQL Data Types.

• Data stored in a relational database can be stored using a variety of data


types. The primary ORACLE data types are NUMBER, VARCHAR,
and CHAR for storing numbers and a text data; however, there are additional
data types that are supported to support backward compatibility with the
products given below:

KEY DATA TYPES


CHAR(size) Fixed-length character data, size characters long. Maximum
size=255; default=1 byte. Padded on right with blanks to
full length of size.
DATE Valid dates range from Jan 1, 4712 B.C. to Dec 31, 4712
A.D.
NUMBER For NUMBER column with space for 40 digits, plus space
for a decimal point and sign. Numbers may be expressed in
two ways: first, with numbers 0 to 9, the signs + and -, and
a decimal point (.); second, in scientific notation, e.g.
1.85E3 for 1850. Valid values are 0 and positive and
negative numbers from 1.0E-130 to 9.99…E125.
VARCHAR2(size) Variable length character string, maximum size up to 2000
bytes.
MISCELLANEOUS
DATA TYPES
AND
VARIATIONS
DECIMAL Same as NUMBER.
FLOAT Same as NUMBER.
INTEGER Same as NUMBER.
INTEGER(size) Integer of specified size digits wide; same as NUMBER
(size) of specific size digits wide.
LONG Character data of variable size up to 2Gb in length. Only
one LONG column may be defined per table. LONG
columns may not be used in subqueries, functions,
expressions, where clauses, or indexes. A table containing
LONG data may not be clustered.
73
Centum- Foundation Student’s Participation Guide

LONG RAW Raw binary data; otherwise the same as LONG (used for
images).
LONG VARCHAR Same as LONG
NUMBER(size) For NUMBER column of specified size in digits.
NUMBER(size,d) For NUMBER column of specified size with d digits after
the decimal point, e.g. NUMBER(5,2) could contain
nothing larger than 999.99 without an error being
generated.
NUMBER(*) Same as NUMBER.
SMALLINT Same as NUMBER.
RAW(size) Raw binary data, size bytes long, maximum size=255 bytes.
ROWID A value that uniquely identifies a row in an Oracle database
- it is returned by the pseudo-column ROWID. Table
columns may not be assigned this type.
VARCHAR(size) Same as VARCHAR2. Always use VARCHAR2.

SQL and SQLPLUS Basics and Error Messages.

• We have already seen that SQL can be used to select data.


• SQL is used for data manipulation in terms of adding, updating, or deleting
data.
• The primary verbs for data manipulation are insert, update, or delete data.
• Taken together, these are the four primary verbs you use in SQL.
• We will start learning to write SQL commands by connecting through
a telnet session to connect to the ORACLE database, and then by using the
SQLPLUS command to enter the SQLPLUS environment.
• Start using SQLPLUS by typing the command at the prompt SQLPLUS (or
by using the appropriate graphical user interface if it is provided). The typical
prompt you receive is: SQL >
• Sometimes your connection will fail and you will receive an error message.
o If you get the following errors, it may be that access to
the ORACLE binary files is not available because
the PATH command for your account is incorrectly established - see
your instructor to correct this.
o The problem could also be that the database has been shut down and so
ORACLE is not running.
o ERROR: ORA-1017: invalid username/password; logon
denied. Unable to CONNECT to ORACLE after 3 attempts, exiting
SQL*Plus
74
Centum- Foundation Student’s Participation Guide

• When you are finished with your work, you quit SQLPLUS with
the QUIT or EXIT command.

Case in Names and Data.

• Oracle ignores case (upper versus lower case letters) when you type table and
column names. It converts table and column names to uppercase when you
type a query and checks the query's validity in the data dictionary.

Data, however, may be stored as a combination of upper and lower case. You
can use Oracle functions to convert data between upper and lower case if that
becomes necessary as part of a programming application.

• Case matters only if SQLPLUS is checking a value for equality in the


database. For example, the following conditions are not identical.
o Where Section = 'f'
o Where Section = 'F'
• Here the values "f" and "F" inside quotes are called literals, meaning literal
values.

SELECT QUERIES

SQL Query Syntax.

• This section teaches you to write a number of different types of SQL queries.
• SQL is based on the data transform language first named SEQUEL.
• This is a relational calculus type of language which provides three capabilities
in a very simple syntax.
• The basic syntax as we have already seen is:

SELECT (column list)


FROM (table list)
WHERE (condition clause)

A Sample Query.
75
Centum- Foundation Student’s Participation Guide

• This result comes from the ORACLE database which is in use at SIUE. This
database contains all tables given in the Oracle Press: The Complete
Reference, but you do not need to have this book in order to use this set of
notes.

SQL> Select City, Temperature, Humidity from WEATHER


2 where Temperature > 80 and Humidity < 90
3 order by Temperature;

CITY TEMPERATURE HUMIDITY


----------- ----------- ----------
PARIS 81 62
ATHENS 97 89

Describing a Table.

• Often it is useful to be able to describe the structure of a table because you


may not be familiar with a particular table.
• The Describe command is used to accomplish this. This example gives the
description of the WEATHER and LOCATION tables in
the ORACLE database.

SQL> describe weather;


Name Null? Type
--------------- -------- ----
CITY VARCHAR2(11)
TEMPERATURE NUMBER
HUMIDITY NUMBER
CONDITION VARCHAR2(9)

SQL> describe location;


Name Null? Type
--------------- -------- ----
CITY VARCHAR2(25)
COUNTRY VARCHAR2(25)
CONTINENT VARCHAR2(25)
LATITUDE NUMBER
NORTHSOUTH CHAR(1)
76
Centum- Foundation Student’s Participation Guide

LONGITUDE NUMBER
EASTWEST CHAR(1)

Result of a SELECT Command.

• The SELECT command produces a "virtual table" -- this is a combination


of columns and rows from one or more selected tables given in the
query. This normally produces a subset of the columns and rows that
comprise the tables in the query.
• The virtual table produced by a query is stored on disk in
a Temporary tablespace area or in RAM that is sometimes called a "scratch"
space because it is used over and over. The actual location of the virtual table
is a function of the size of the table.
• When the virtual table is no longer needed, Oracle disposes of it.
• The basic operation of each of the three components of the SELECT
command are explained below.

SELECT List the columns including expressions involving columns


from base tables or views to be projected into the table that
will be the result of the command.
FROM Identifies the tables or views from which columns will be
chosen to appear in the result table. This must also list the
tables or views needed to join tables to process the query.
WHERE Includes conditions that restrict the rows selected as well as the
conditions for joining two or more tables or views.

********************************************************************

Check Your Progress


Exercise 1
What are the different types of SQL statements? Define each of them.
Exercise 2
What is the requirement of JOINS in database? Explain each type of JOIN.
Exercise 3

77
Centum- Foundation Student’s Participation Guide

Create following tables using SQL queries. Identify the keys according to your
knowledge:

Using above schema write down the following SQL queries:


Write An SQL Query To Fetch “FIRST_NAME” From Worker Table Using The
Alias Name As <WORKER_NAME>.
Write An SQL Query To Fetch Unique Values Of DEPARTMENT From Worker
Table.
Write An SQL Query To Print The FIRST_NAME And LAST_NAME From Worker
Table Into A Single Column COMPLETE_NAME. A Space Char Should Separate
Them.
Write An SQL Query To Print Details For Workers With The First Name As “Vipul”
And “Satish” From Worker Table.
Write An SQL Query To Print Details Of The Workers Whose SALARY Lies
Between 100000 And 500000.
Write An SQL Query To Print Details Of The Workers Who Are Also Managers.
78
Centum- Foundation Student’s Participation Guide

Write An SQL Query To Show The Top N (Say 10) Records Of A Table.
Write An SQL Query To Determine The Nth (Say N=5) Highest Salary From A Table.
Write An SQL Query To Fetch The List Of Employees With The Same Salary.
Write An SQL Query to increase the salary by 5% of Admin.

79
Centum- Foundation Student’s Participation Guide

JDBC

Introduction to JDBC
It is application programming Interface (API) for the programming language JAVA.
It defines how a client may access a database. It is part of the JAVA standard edition
platform.
JDBC can be used to access any type of RDBMS software on almost all types of
different operating system.
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database. Java can be used to write
different types of executables, such as −
Java Applications
80
Centum- Foundation Student’s Participation Guide

Java Applets
Java Servlets
Java Server Pages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
JDBC Drivers *It is a software component that enables java applications to interact
with the database. It converts JAVA application calls into database calls and vice
versa. There are 4 types of JDBC drivers: *JDBC-ODBC bridge driver (written in C)
*Native API driver (partially written in java) *Network protocol driver (fully written
in java) *Thin driver (fully written in java)
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application −

81
Centum- Foundation Student’s Participation Guide

Common JDBC Components


The JDBC API provides the following interfaces and classes −
DriverManager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.
Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.
Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.
Statement: You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing
stored procedures.

82
Centum- Foundation Student’s Participation Guide

ResultSet: These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move through
its data.
SQLException: This class handles any errors that occur in a database application.
********************************************************************

Check Your Progress

Exercise 1
Write a program to establish and verify the Database connection using JDBC API in
java.
Exercise 2
Write a Menu driven program as per following format:
-----------------MENU-----------------------
You have following options:
[1] Insert a Record
[2] Search a Record
[3] Delete a Record
[4] Update a Record
[5] Exit
Accept choice from user and do the database CRUD operation in any of the database
table you have already created.
Exercise 3
How to get JDBC Connection object using properties file?
Exercise 4
What are the JDBC statements? Define each of the type using example.
Exercise 5
What are the different types of ResultSet available in JDBC? Explain each one of
them.
83
Centum- Foundation Student’s Participation Guide

Exercise 6
Write down the differences between execute(), executeQuery() and executeUpdate()
in JDBC.

84
Centum- Foundation Student’s Participation Guide

HTML5+CSS+Bootstrap

Introduction to Web
Advent of WAN raised a strong need to share data across the globe rather than within
the organization.
WWW is the best example of WAN
Web is a way to access information using the Internet.
All the computers across the globe are connected with each other using Internet
A web is a collection of web pages which contain informations and contents to share.
Differences in between Static and Dynamic Webpages

Static Web page Dynamic Web page


The pages which include hypertext It generates contents on demand.
along with other contents. Database connectivity is must.
Does not provide any interactivity. User can interact with web using events
No database connectivity is necessary. or actions.
It is one way flow of information

Introduction to HTML
Hypertext markup language was introduced in 1990
Primarily used to create static webpages.
It was recommended as standard by W3C in 1997.

85
Centum- Foundation Student’s Participation Guide

HTML5 is the latest version.


Most of the browsers now support HTML5 elements and APIs
Layout of HTML4 Page
An HTML page is made up of various elements, attributes and contents
It is saved with extension .html
Basic HTML elements are:
HTML
HEAD
TITLE
BODY

Layout of HTML5 page


The basic structure of a HTML5 document remains the same. Each HTML5 page
consists of a head section containing unseen elements and links and a body section
where the visible elements of the document are present. HTML offers different tags
to build and organize the content in the body of the document. The body structure
generates the visible part of the document. One of the elements provided for body is
<table> tag. Tables help in improving user’s experience by helping the user to
86
Centum- Foundation Student’s Participation Guide

visualize the Web site in an organized manner. Eventually, other elements replaced
the function of tables. These elements have lesser code and are faster, thus facilitating
creation, portability, and maintenance of a HTML5 Web site. The <div> element was
another element that was introduced in this field. With the integration of HTML, CSS,
and JavaScript, and the usage of more interactive applications, the <div> tag was
frequently used. Both the <div> and <table> elements, did not provide information
about the sections of the body that the element may be representing. Content such as
scripts, images, links, text, menus, forms, and so on could be used between the opening
and closing <div> tags. HTML5 includes new elements that identify and organize
each part of the document body. In HTML5, the most significant sections of a
document are separated and marked. Hence, the main structure does not depend on
the <div> or <table> tags. A typical HTML page would have a page header, footer,
and middle page content. Within the middle page content, at the top level, it may have
navigation, content, and aside columns. Also, within the content, more sections can
be embedded depending on the page’s specific content.

The Header on the top usually has the logo, name, subtitles, and short descriptions of
the Web site or Web page. After that is the Navigation Bar that includes a menu that
contains links for navigation. Web users can navigate to different pages or documents
using the navigation bar. The most relevant content is generally shown in the middle
of the page. The content presented in the Main Information part of the layout usually
has a top priority. It can have a list of products, description of products, blogs, or any
other important information. The Side Bar shows a list of links that lead to certain
87
Centum- Foundation Student’s Participation Guide

items that may be present internally on the Web site or on an external link. For
example, in a blog, the last column offers a list of links that can lead to the blog entries,
information about the author, and so on. These two sections are extremely flexible.
Web designers can perform variety of actions, such as inserting more rows or splitting
the columns, to edit the Web page as required. The footer at the bottom is used to
represent general information about the Web site. This can include the author or the
company name, links regarding rules, terms and conditions, location maps, and any
other additional data.
Working of HTML5
HTML5 is made up of a family of technologies. HTML consists of markups, improved
CSS with CSS3 that provides added options to style your pages. There is also
JavaScript and a new set of JavaScript APIs that are available in HTML5. The process
generally followed for HTML5 is as follows: The browser loads the document, which
includes HTML markup and CSS style. After the browser loads the page, it also
creates an internal model of the document that contains all the elements of HTML
markup. The browser also loads the JavaScript code, which executes after the page
loads. The APIs give access to audio, video, 2D drawing with the canvas, local
storage, and other technologies that are required to build apps.
New Features of HTML5
Some of the new features introduced in HTML5 are as follows:
The <canvas> element is used for 2D drawing.
New content-specific elements, such as <article>, <nav>, <header>, <footer>,
<section>, and so on helps to structure the document.
HTML5 has local storage support.
The <audio> and <video> elements is available for media playback.
New form controls, such as calendar, date, time, e-mail, URL, search, and so on have
been provided by HTML5.
The Web workers API is added to support background processes without disturbing
the main process.
The common problems faced by Web applications are slow performance when a large
set of data is processed. This is due to the fact that all the processes are executed in a
single thread. Web workers help to solve this problem.

88
Centum- Foundation Student’s Participation Guide

The Web Sockets API provides a continuous connection between a server and a client
by using a specific port. Thus, the Web applications become efficient as the data can
be easily exchanged between client and server without reloading the page constantly.
Easier access to location specific data which is made available by devices having
Global Positioning System (GPS) capabilities. This improved functionality is
achieved with the help of API.
HTML5 allows Web applications to be executed offline by storing the files and other
resources required in the application cache. Web application data is saved locally
using Web SQL databases.
Cascading Style sheet
HTML5 along with CSS and JavaScript forms an integrated instrument. CSS is
basically a language that works along with HTML to provide visual styles to the
elements of the document, such as size, color, backgrounds, borders, and so on. A
style sheet is a collection of rules that specifies the appearance of data in an HTML
document. HTML is a markup language that focuses only on the layout of the content
on a Web page. However, applying layouts to more than one occurrence of an HTML
element in an HTML page is a tedious job. For example, if you want to change the
text in the H2 element to bold, this has to be done manually for all the H2 elements.
Such a manual task might result into human errors such as missing an occurrence of
the H2 element for applying the bold format. This results in format inconsistency
among the H2 elements within an HTML page. Further, the specified formatting might
not have same appearance across various devices such as computers and mobiles.
Style sheets overcome these problems by specifying the formatting instructions in a
separate file as shown in figure:
A CSS is a rule-based language, which specifies the
formatting instructions for the content specified in
an HTML page. Its purpose is to separate HTML
content from its formatting so that Web page
designers would not worry about the formatting and
layout. This is because they can define the layout
and formatting of the content in a separate file saved
with an extension of .css. In the .css file, the
formatting instructions for an element are referred
to as a rule set. Each rule defines how the content
specified within an element should be displayed in
a Web browser. While displaying the HTML page, the browser identifies the .css file
for the page and applies the rules for the specified elements. You can merge the rules

89
Centum- Foundation Student’s Participation Guide

from different .css files or can edit them. This task of combining and matching rules
from different files is referred to as cascading.
Benefits of CSS
Multiple HTML pages can use a CSS document. CSS provides some useful benefits
that make it an ideal choice to specify the appearance of the content in an HTML page.
These benefits are as follows:
Code Reusability: CSS saves time by specifying the formatting options of an element
only once and applying them to multiple HTML pages.
Less HTML Code: CSS helps in reducing the file size of HTML documents by
specifying the formatting instructions in another file.

Introduction to Bootstrap
Bootstrap is a powerful front-end framework for faster and easier web development.
It includes HTML and CSS based design templates for common user interface
components like Typography, Forms, Buttons, Tables, Navigations, Dropdowns,
Alerts, Modals, Tabs, Accordion, Carousel and many other as well as optional
JavaScript extensions.
Bootstrap also gives the ability to create responsive layout with much less efforts.
Advantages of Bootstrap
The biggest advantage of using Bootstrap is that it comes with free set of tools for
creating flexible and responsive web layouts as well as common interface
components.
Additionally, using the Bootstrap data APIs you can create advanced interface
components like Scrollspy and Typeaheads without writing a single line of JavaScript.
Here are some more advantages, why one should opt for Bootstrap:
Save lots of time — You can save lots of time and efforts using the Bootstrap
predefined design templates and classes and concentrate on other development work.
Responsive features — Using Bootstrap you can easily create responsive designs.
Bootstrap responsive features make your web pages to appear more appropriately on
different devices and screen resolutions without any change in markup.
Consistent design — All Bootstrap components share the same design templates and
styles through a central library, so that the designs and layouts of your web pages are
consistent throughout your development.

90
Centum- Foundation Student’s Participation Guide

Easy to use — Bootstrap is very easy to use. Anybody with the basic working
knowledge of HTML and CSS can start development with Bootstrap.
Compatible with browsers — Bootstrap is created with modern browsers in mind
and it is compatible with all modern browsers such as Mozilla Firefox, Google
Chrome, Safari, Internet Explorer, and Opera.
Open Source — the best part is, it is completely free to download and use.
Downloading Bootstrap files
There are two versions available for download, compiled Bootstrap and Bootstrap
source files. Compiled Bootstrap contains compiled and minified version of CSS and
JavaScript files as well as icons in font format for faster and easier web development,
while the source contain original source files for all CSS and JavaScript, along with a
local copy of the docs.
The file structure of Bootstrap

Compiled version of Bootstrap provides compiled CSS and JS files (bootstrap.*), as


well as compiled and minified CSS and JS (bootstrap.min.*).
There are four font files (glyphicons-halflings-regular.*) inside the fonts folder. These
fonts file includes more than 250 icons from the Glyphicon Halflings set.
Bootstrap Grid System
Bootstrap grid system provides the quick and easy way to create responsive website
layouts. As opposed to the previous Bootstrap 2.x grid system which is fixed by
default, the new version, i.e. Bootstrap 3 introduces the responsive mobile first fluid
grid system that appropriately scales up to 12 columns as the device or viewport size
increases.

91
Centum- Foundation Student’s Participation Guide

Bootstrap 3 includes predefined grid classes for quickly making grid layouts for
different types of devices like cell phones, tablets, laptops and desktops, etc. For
example, you can use the .col-xs-* class to create grid columns for extra small devices
like cell phones, similarly the .col-sm-*class for small screen devices like tablets,
the .col-md-* class for medium size devices like desktops and the .col-lg-* for large
desktop screens. The following table summarizes some of the key features of the new
grid system.
Above table demonstrates one important thing, applying any .col-sm-* class to an
element will not only affect its styling on small devices, but also on medium and large
devices having a screen size greater than or equal to 768px (i.e. ≥768px) if .col-md-
* and .col-lg-* class is not present. Similarly the .col-md-* class will not only affect
the styling of elements on medium devices, but also on large devices if a .col-lg-
* class is not present.
Now the question arises how to create rows and columns using this 12 column
responsive grid system. The answer is pretty simple, at first create a container that acts
as a wrapper for your rows and columns using the .container class, after that create
rows inside the container using the .row class, and to create columns inside any row
you can use the class .col-xs-*, .col-sm-*, .col-md-* and .col-lg-*. The columns are
actual content area where we will place our contents. Let's put all these things into real
action.

********************************************************************

92
Centum- Foundation Student’s Participation Guide

Check Your Progress

Exercise 1
An automobile company decides to build a website for its company to enhance the
sales and attract more customers. The home page of the website should show the
details of various car companies in a tabular format. Steve, a website designer, has
been assigned this task. The table should appear, as shown in the following figure:

Exercise 2
After creating the above table, enhance the table using external Cascading Style Sheet.
The Table should appear as shown in the following figure:

Exercise 3
Design an HTML form using HTML5, CSS and Bootstrap concept as:

93
Centum- Foundation Student’s Participation Guide

Note: Form must be responsive in nature.


Exercise 4
Photo Gallery Assignment
Design a photo gallery as per following instructions:

94
Centum- Foundation Student’s Participation Guide

Introduction to Angular

Angular is a framework for building client applications in HTML, CSS, and either
JavaScript or a language like TypeScript that can be compiled (more accurately,
transpiled) to JavaScript.
TypeScript
TypeScript is a superset of JavaScript. That means any valid JavaScript code is valid
TypeScript code. But many prefer TypeScript because it has additional features that
we don’t have in the current version of JavaScript that most browsers understand. So,
when building Angular applications, we need to have our TypeScript code converted
into JavaScript code that browsers can understand. This process is
called transpilation which is the combination of translate and compile. And that’s the
job of the TypeScript compiler.
Why we need Angular Framework?
As our web application grows, structuring the code in a clean and maintainable and
more importantly, testable way, becomes harder and harder. Although it is possible
but undoubtedly very complex. Using a framework like Angular, makes it far easier.
Advantages of Angular over AngularJS
Angular 4 is an extension of Angular 2, which was re-written version of Angular1
and not an update. The best way to compare Angular and AngularJS is by finding out

95
Centum- Foundation Student’s Participation Guide

the new features in Angular. This way we will be able to find out the advantages of
Angular over AngularJS precisely. So, some of the advantages of Angular are:-
Angular AngularJS

Angular is a mobile-oriented framework Whereas AngularJS was not


developed with mobile base in
mind.
Angular is a versatile framework, i.e. we have Whereas an AngularJS code
more choices for languages. We can use ES5, can written by using only ES5,
ES6, Typescript or Dart to write an Angular ES6 and Dart. We don’t have
code many choices of language in
Angular1.
Nowadays, the controllers are replaced by Whereas AngularJS was based
components and Angular is completely on controllers whose scope is
component based. now over.

Angular directly uses the valid HTML DOM element properties and events which
reduces the usage of many available built-in directives.
Architecture of Angular app
The most fundamental building block in an Angular application is a component. You
can think of a component as a view component. It represents a view or part of a view
(what the user sees). A component consists of three pieces:

HTML markup: to render that view


State: the data to display on the view
Behavior: the logic behind that view. For example, what should happen when the user
clicks a button?

96
Centum- Foundation Student’s Participation Guide

A component can contain other components. For example, if we have to build a web
app like Twitter using Angular. In our implementation, we may have a tree of
component likes this:
➢ App
➢ NavBar
➢ SideBar
➢ ContentArea
➢ Tweets
➢ Tweet
➢ Like
At the root of the application, we have a component called AppComponent. This is
the root of every Angular application. Our AppComponent contains 3 child
components: NavBar, SideBar, and ContentArea.
The reason for such separation is because the navigation bar is logically a separate
part of the view. It has its own markup, state, and behavior. We can encapsulate all
that using a component called NavBarComponent. This way, when modifying or
extending the navigation bar of our application, we can focus on a small component
with a lightweight template.

********************************************************************

Check Your Progress


Exercise 1
Create TODO List application using Angular concepts
Exercise 2
Create an Angular app containing predefined validation and custom validation in
HTML Form.
Exercise 3
Explain the concept of routing through Angular app.
Exercise 4
Create an Angular data driven app using modules and components.
Exercise 5
97
Centum- Foundation Student’s Participation Guide

Create an inline editor app using Angular.

98
Centum- Foundation Student’s Participation Guide

J2EE

Introduction
J2EE is called as Java 2 Enterprise Edition.
It is an environment to develop and deploy enterprise applications.
It consists of J2EE components, services, APIs and protocols that provide the
functionality for developing multitiered applications.
J2EE is four-tier architecture. These consist of Client Tier (Presentation tier or
Application tier), Web tier, Enterprise JavaBeans Tier (or Application server tier), and
the Enterprise Information Systems Tier or the Data tier.

99
Centum- Foundation Student’s Participation Guide

Components of J2EE Architecture

CLIENT TIER: Client tier consists of programs that interact with the user. It prompts
the user for input and then convert the user’s response into requests that are forwarded
to software on a component that processes the request and returns results to the client
program.

WEB TIER: Web tier accepts requests from other software that was sent using POST,
GET, and PUT operations, which are part of HTTP transmissions. The two major
components of web tier are Servlets and Java Server Pages. A servlet is a java class
that resides on the web tier and is called by a request from a browser client that
operates on the client tier. A servlet is associated with a URL that is mapped by the
servlet container. It typically generates an HTML output stream that is returned to the
web server. The web server in turn transmits the data to the client. JSP is different
than a servlet depending on the container that is used. JSP uses custom tags to access
the bean.

ENTERPRISE JAVA BEANS TIER OR APPLICATION TIER: Enterprise java


bean is a class that contains business logic and callable from a servlet or Jsp. EJB tier
contains the enterprise java beans server that stores and manages enterprise java
beans.

ENTERPRISE INFORMATION SYSTEMS TIER OR DATA TIER: This tier


provides flexibility to developers of J2EE applications since it include variety of
resources and support connectivity to resources. It defines all the elements that are
needed to communicate between J2EE application and non-J2EE software.
Servlets in Java
Servlet is a java programming language developed by sun microsystem. It extends the
capability of a server and provides dynamic contents. The first version was 1.0
released in 1997 and current version is servlet 3.1

100
Centum- Foundation Student’s Participation Guide

Request-Response Model

Differences between HTTPRequest and HTTPResponse

Role of Servlet
Web server can handle only the static web pages.
In case of dynamic web pages, we need a helper application that can help to generate
dynamic contents.
This helper application is Servlet

101
Centum- Foundation Student’s Participation Guide

Servlet is nothing but a Java program


This Servlet does not has any main method
It has only callback methods
Servlet Architecture

Role of Web Container


➢ It is simply a Servlet Engine
➢ Communication support
➢ Lifecycle management
➢ Multi-threading support
➢ Security (Client cannot directly communicate with a servlet, it must be handled
through web container)
➢ JSP support
Web.xml file
web.xml is a configuration file that is used to run Servlet and JSP pages. It’s an XML
document which describes the deployment of an application. Deployment Descriptor
is called web.xml and is placed in WEB-INF folder.

102
Centum- Foundation Student’s Participation Guide

Components of web.xml file

103
Centum- Foundation Student’s Participation Guide

Main methods of Servlet Life cycle

A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
The init() Method
The init method is called only once. It is called only when the servlet is created, and
not called for any user requests afterwards. So, it is used for one-time initializations,
just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.

104
Centum- Foundation Student’s Participation Guide

The service () Method


The service () method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service () method to handle requests coming from
the client (browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service () method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.

The destroy () Method


destroy () method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.
After destroy () method is called, the servlet object is marked for garbage collection.
105
Centum- Foundation Student’s Participation Guide

Inter Servlet Communication


It represents the communication between Servlets.
Inter-servlet communication using Request Dispatcher
Request Dispatcher: An object of the javax.servlet.RequestDispatcher interface that
allows inter-servlet communication.
Object is used to include to forward the content of another servlet.
The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to
include the content of another resource also. It is one of the way of servlet
collaboration.
There are two methods defined in the RequestDispatcher interface.
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They are:
public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on the server.

public void include(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Includes the content of a resource (servlet,
JSP page, or HTML file) in the response.

106
Centum- Foundation Student’s Participation Guide

Inter Servlet communication using sendRedirect ()


The sendRedirect () method of HttpServletResponse interface can be used to
redirect response to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another
request. So, it can work inside and outside the server.
Difference between forward () and sendRedirect () method
There are many differences between the forward () method of RequestDispatcher and
sendRedirect () method of HttpServletResponse interface. They are given below:

Session Management in Servlet


HTTP is a "stateless" protocol which means each time a client retrieves a Web page,
the client opens a separate connection to the Web server and the server automatically
does not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web
server

107
Centum- Foundation Student’s Participation Guide

Cookies
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way because many time browser does not support a
cookie
Hidden Form Fields
A web server can send a hidden HTML form field along with a unique session ID as
follows –
<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends
request back, then session_id value can be used to keep the track of different web
browsers.
This could be an effective way of keeping track of the session but clicking on a regular
(<A HREF...>) hypertext link does not result in a form submission, so hidden form
fields also cannot support general session tracking.
URL Rewriting
You can append some extra data on the end of each URL that identifies the session,
and the server can associate that session identifier with data it has stored about that
session.
URL rewriting is a better way to maintain sessions and it works even when browsers
don't support cookies. The drawback of URL re-writing is that you would have to
generate every URL dynamically to assign a session ID, even in case of a simple static
HTML page.
The HttpSession Object
Apart from the above mentioned three ways, servlet provides HttpSession Interface
which provides a way to identify a user across more than one page request or visit to
a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client
and an HTTP server. The session persists for a specified time period, across more than
one connection or page request from the user.

108
Centum- Foundation Student’s Participation Guide

You would get HttpSession object by calling the public method getSession () of
HttpServletRequest, as below −
HttpSession session = request.getSession ();
JSP in Java
JSP technology is used to create web application just like Servlet technology. It can
be thought of as an extension to servlet because it provides more functionality than
servlet such as expression language, jstl etc.
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain
than servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tag etc.
Advantage of JSP over Servlet
There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of
servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, which makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the
presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The
servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.
4) Less code than Servlet
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces
the code. Moreover, we can use EL, implicit objects etc.
Life cycle of JSP page
The JSP pages follows these phases:
Translation of JSP Page
Compilation of JSP Page
109
Centum- Foundation Student’s Participation Guide

Classloading (class file is loaded by the classloader)


Instantiation (Object of the Generated Servlet is created).
Initialization (jspInit () method is invoked by the container).
Request processing (jspService () method is invoked by the container).
Destroy (jspDestroy () method is invoked by the container).
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are
three types of scripting elements:
Scriptlet tag: A scriptlet tag is used to execute java source code in JSP.
Syntax is as follows:
<% java source code %>

<html>
<body>
<% out.print ("welcome to jsp"); %>
</body>
</html>

expression tag: The code placed within JSP expression tag is written to the output
stream of the response. So you need not write out.print() to write data. It is mainly
used to print the values of variable or method.
Syntax is as follows:
<%= statement %>

<html>
<body>
<%= "welcome to jsp" %>
</body>
110
Centum- Foundation Student’s Participation Guide

</html>

declaration tag: The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet.
So it doesn't get memory at each request.
Syntax is as follows:
<%! field or method declaration %>
JSP Implicit object
There are 9 jsp implicit objects. These objects are created by the web container that
are available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below:

111
Centum- Foundation Student’s Participation Guide

Check Your Progress


Exercise 1

Write a servlet that snoops all the information about the current session. Make a
“registration” form that collects a first name, last name, and email address. Send the
data to a servlet that displays it. Next, modify the servlet to use a default value in form
(or give an error message) if the user omits any of the three required parameters.
Exercise 2
Write a program using servlet and JDBC for developing an online application for the
shopping of computer science books. (Hint: use concept of session tracking) You have
to create a database for book title, author(s) of book, publisher, year of publication,
price. Make necessary assumptions for book shopping.

Exercise 3

Write a servlet that displays the values of the firstName, lastName, and emailAddress
request parameters. But, remember what users told you in the past, and use the old
values if the current values are missing. So, if a parameter is missing and the client is
a first-time visitor, have the servlet list “Unknown” for the missing values. If a
parameter is missing and the client is a repeat visitor, have the servlet use previously
entered values for the missing values. This should definitely be easier than a version
that uses cookies explicitly.
Exercise 4

Make a JSP page that lets the user supply a request parameter indicating the
background color. If no parameter is supplied, the most recently used background
color (from a previous request by any user) should be used.

Exercise 5
Create a web application to demonstrate the session tracking using hidden form field,
cookies and session object. Which is the best way you prefer for session management?

112

Potrebbero piacerti anche