SlideShare a Scribd company logo
1 of 116
Download to read offline
1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
IMPORTANT QUESTIONS & ANSWERS
JUNE – NOV.2015
CS6501 – INTERNET PROGRAMMING
Year/Sem : IV/VIII
Branch : COMPUTER SCIENCE AND ENGINEERING
Faculty : V.KARTHIK
SYLLABUS
CS6501 INTERNET PROGRAMMING LTPC/3104
OBJECTIVES:
The student should be made to:
 Learn Java Programming.
 Understand different Internet Technologies.
 Be exposed to java specific web services architecture.
UNIT I JAVA PROGRAMMING
An overview of Java – Data Types – Variables and Arrays – Operators – Control
Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes –
Interfaces and Inner classes – Exception handling - Introduction to Threads –
Multithreading – String handling – Streams and I/O – Applets.
UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
Web 2.0: Basics-RIA Rich Internet Applications - Collaborations tools - Understanding
websites and web servers: Understanding Internet – Difference between websites and
web server- Internet technologies Overview – Understanding the difference between
internet and intranet; HTML and CSS: HTML 5.0 , XHTML, CSS 3.
UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING
Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,-
Regular Expressions- Exception Handling- Validation-Built-in objects-Event Handling-
DHTML with JavaScript. Servlets: Java Servlet Architecture- Servlet Life Cycle- Form
GET and POST actions- Session Handling- Understanding Cookies- Installing and
Configuring Apache Tomcat Web Server;-
DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example - JSP:
Understanding Java Server Pages-JSP Standard Tag Library (JSTL)-Creating HTML
forms by embedding JSP code.
2
UNIT IV PHP and XML
An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in
functions-Connecting to Database – Using Cookies-Regular Expressions; XML: Basic
XML- Document Type Definition-XML Schema DOM and Presenting XML, XML
Parsers and Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
AJAX: Ajax Client Server Architecture- XML Http Request Object-Call Back Methods;
Web Services: Introduction- Java web services Basics – Creating, Publishing, Testing
and Describing a Web services (WSDL)-Consuming a web service, Database Driven web
service from an application – SOAP.
TOTAL (L: 45+T: 15): 60 PERIODS
OUTCOMES:
 At the end of the course, the student should be able to:
 Implement Java programs.
 Create a basic website using HTML and Cascading Style Sheets.
 Design and implement dynamic web page with validation using JavaScript objects
and by applying different event handling mechanisms.
 Design rich client presentation using AJAX.
 Design and implement simple web page in PHP, and to present data in XML
format.
 Design and implement server side programs using Servlets and JSP.
TEXT BOOKS:
1. Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to Program‖,
Prentice Hall, 5th Edition, 2011.
2. Herbert Schildt, ―Java-The Complete Reference‖, Eighth Edition, Mc Graw Hill
Professional,2011.
REFERENCES:
1. Stephen Wynkoop and JohnBurke ―Running a Perfect Website‖, QUE,2nd
Edition,1999.
2. Chris Bates, Web Programming – Building Intranet Applications, 3 rd Edition, Wiley
Publications, 2009.
3. Jeffrey C and Jackson, ―Web Technologies A Computer Science Perspective‖, Pearson
Education, 2011.
4. Gopalan N.P. and Akilandeswari J., ―Web Technology‖, Prentice Hall of India, 2011.
5. Paul Dietel and Harvey Deitel, ―Java How to Program‖,8 th Edition Prentice Hall of
India.
6. Mahesh P. Matha, ―Core Java A Comprehensive Study‖, Prentice Hall of India, 2011.
7. Uttam K.Roy, ―Web Technologies‖, Oxford University Press, 2011.
3
SECTION B: QUESTIONS
UNIT –I JAVA PROGRAMMING
PART -A
1. What is a Class and Object?
2. What is final modifier?
3. What is meant by abstraction?
4. What are methods and how are they defined?
5. What is an Object and how do you allocate memory to it?
6. Explain the usage of Java packages.
7. What is method overloading and method overriding?
8.What is static variable and static method?
9. What is array? Give an example.
10.What is a package?
11.Explain working of Java Virtual Machine (JVM)?
12. What is meant by Inheritance and what are its advantages?
13. What are inner class and anonymous class?
14. What is an Interface?
15.What is interface and its use?
16. What are the types of Exceptions in Java
17. Whatis the difference between String and String Buffer?
18.What are different types of access modifiers (Access specifiers)?
19. What is multithreading?
20. What is an applets?
PART -B
1. Explain in detail about operator in java with example? (16)
2. i) Discuss in detail the access specifiers available in Java.(8)
ii)What is Array? How to declare array?Discuss the methods under array class. (8)
3. Explain Packages in detail with example. (16)
4. Explain the concept of inheritance and its types. (16)
5. Explain the different ways to handle exceptions in java. (16)
6.Explain in detail about Multithreading in java. (16)
4
UNIT –II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
PART-A
1. What are the necessities of using HTML forms?
2. Define HTML.
3. What do you understand about DOCTYPE in HTML?
4. What are the Hyperlink, Anchors and Link in the HTML?
5. How you define HTML Style Attribute in HTML?
6. HTML is case sensitive or not?
7. How to use form‘s action attribute and submit button in html?
8. How to use Line Break and Horizontal Line tags in HTML?
9. What are Style Sheets?
10. List down the ways of including style information in a document.
11. What are the style precedence rules when using multiple approaches?
12. Give the syntax to specify a characteristic in linked style sheet.
13. List down font characteristics permitted in style sheets.
14. How to toggle display an HTML element?
15. What is the HTML DOM?
PART –B
1. Explain Basic internet protocols and HTTP message format?(16)
2. To create a web page that displays college information using various styles (16)
3. Explain XHTML Syntax and semantics with example.(16)
4. i)Design a HTML Form for aRailwaay Reservation System? (8)
ii)Explain about different types of XHTML DTD(8)
5.i)Explain about internet and intranet with difference.(8)
ii) Design a HTML document using relative positioning to nudge text to the left.(8)
5
UNIT –III CLIENT SIDE AND SERVER SIDE PROGRAMMING
PART-A
1. How to create an Object in JavaScript?
2. What is the result of below given line of code in Java Script? 5+4+‖7‖
3.What is undefined value means in JavaScript?
4. Which method is used to Clear an array using JavaScript?
5.What will be the Output of the following using JavaScript,
document.Write(Math.Round(6.7));
6.What should appear at the very end of your JavaScript?
7.What is a JSP and what is it used for?
8. What is difference between custom JSP tags and beans?
9. What are the implicit objects?
10. Compare Client side vs. server side scripting.
11. State the Servlet life cycle
12. What is JavaScript?
13. What is the purpose of cookies?
14. What are the steps needs to establish JDBC connectivity?
15. What is the difference between GET and POST method?
16. What is different between web server and application server?
17. What are different methods of session management in servlets?
18. What is difference between GenericServlet and HttpServlet?
PART –B
1. Explain javascript variables and debuggers in detail (16)
2. Discuss JavaScript Array object in detail. (16)
3. Write java script to perform all arithmetic operation (16)
4. Explain DOM event handling in detail.(16)
5. Write java servlet programs to conduct online examination and to display student mark
list available in a database (16)
6
UNIT-IV PHP and XML
PART –A
1. Mention the rules of well-formed XML.
2. What is the DOM?
3. What is the XML DOM?
4. What is the XMLHttpRequest Object?
5. What is XSL-FO?
6. What is XSL-FO Documents? Explain XSL-FO Documents structure
7. What is XSL-FO Processors?
8. Explain XML Attributes with an example
9. XML Elements vs. Attributes.
10. What are the problems with using XML attributes?
11. What is XSLT?
12. What are the roles of XSLT?
13.What is XSLT? Explain its relationships with XSL
14.What is XSLT style sheet?
15.Discuss the role of XPATH
16.Explain the XSLT data model
17.Why the need for XHTML?
18.What is XQuery language?
19.Explain the Relation between RSS and XML
20. Define. DOM
PART –B
1. Given an XSLT document and a source XML document explain the XSLT
transformation process that produces a single result XML document. (16)
2.Write a program to display student information using XSLT in XML document (16)
3. i)Explain the role XML namespaces with an example.(8)
(ii)Explain the feature of XML path.(8)
4. Explain the model view controller architecture pattern in detail. (16)
5. Write Programs using XML – Schema – XSLT/XSL (16)
7
UNIT V – INTRODUCTION TO AJAX and WEB SERVICES
PART –A
1. What is DTD? Explain it with example.
2. What is AJAX?
3.What is a web service?
4.What is SOAP?
5. What is SOAP and how it will be utilized in web-components?
6. Explain about the role of XML in SOAP?
7.What are the elements which should be contained in SOAP message?
8. What is SOAP?
9. Explain web services architecture.
10. What is WSDL?
11. Differentiate between AJAX and Java Script
12. What are the advantages of AJAX ?
13. Define Web Service?
14. Brief few drawbacks of using GET and POST methods to communicate with the web
service?
15. Differentiate between a SOA and a Web service?
PART –B
1. Describe the significance and working of WSDL with an example(16)
2. Describe the major elements of SOAP (16)
3. Explain about AJAX Http Request Object (16)
4. Explain in details about Web Services Conceptual Architecture (16)
5. Write a program to run and implement the web service (16)
8
SECTION C: QUESTIONS AND ANSWER
UNIT –I PART A
1. What is a Classand Object?
Class is a template for a set of objects that share a common structureand a common
behavior.
Object is an instance of a class. It has state, behavior and identity. It isalso called as an
instance of a class.
2. What is final modifier?
The final modifier keyword makes that the programmer cannotchange the value anymore.
The actual meaning depends on whether it isapplied to a class, a variable, or a method.
final Classes- A final class cannot have subclasses.
final Variables- A final variable cannot be changed once it is initialized.
final Methods- A final method cannot be overridden by subclasses.
3. What is meant by abstraction?
Abstraction defines the essential characteristics of an object that distinguish it from all
other kinds of objects. Abstraction provides crisply-defined conceptual boundaries
relative to the perspective of the viewer. It‘s the process of focusing on the essential
characteristics of an object. Abstraction is one of the fundamental elements of the object
model
4. What are methods and how are they defined?
Methods are functions that operate on instances of classesin which they are defined.
Objects can communicate with each other usingmethods and can call methods in other
classes. Method definition has fourparts. They are name of the method, type of object or
primitive type themethod returns, a list of parameters and the body of the method. A
method‘s signature is a combination of the first three parts mentionedabove.
5. What is an Object and how do you allocate memory to it?
Object is an instance of a class and it is a software unit that combines astructured set of
data with a set of operations for inspecting and manipulatingthat data. When an object is
created using new operator, memory is allocated toit.
6. Explain the usage of Java packages.
This is a way to organize files when a project consists of multiplemodules. It also helps
resolve naming conflicts when different packages haveclasses with the same names.
Packages access level also allows you toprotect data from being used by the non-
authorized classes.
7. What is method overloading and method overriding?
Method overloading: When a method in a class having the same methodname with
different arguments is said to be method overloading. Methodoverriding: When a method
in a class having the same method name withsame arguments is said to be method
overriding.
9
8.What is static variable and static method?
Static variable is a class variable which value remains constant for theentire class.
Static method is the one which can be called with the class itself and can holdonly the
static variables.
9. What is array? Give an example.
An array is a group of like-typed variables that are referred to by a common name.
Arrays ofany type can be created and may have one or more dimensions. A specific
element in an arrayis accessed by its index. Arrays offer a convenient means of grouping
related information.
Syntax:
array-var = new type[size];example:month_days = new int[12];
10.What is a package?
A package is a collection of classes and interfaces that provides ahigh-level layer of
access protection and name space management.
11.Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computingmachine which first
converts .java file into .class file by using Compiler (.class isnothing but byte code file.)
and Interpreter reads byte codes
12. What is meant by Inheritance and what are its advantages?
Inheritance is the process of inheriting all the features from a class.The advantages of
inheritance are reusability of code and accessibility ofvariables and methods of the super
class by subclasses.
13. What are inner class and anonymous class?
Inner class: classes defined in other classes, includingthose defined in methods are called
inner classes. An inner class canhave any accessibility including private.
Anonymous class: Anonymousclass is a class defined inside a method without a name
and is instantiated and declared in the same place and cannot have explicit constructors
14. What is an Interface?
Interface is an outside view of a class or object which emphasizes itsabstraction while
hiding its structure and secrets of its behavior.
15.What is interface and its use?
Interface is similar to a class which may contain method‘ssignature only but not bodies
and it is a formal set of method and constantdeclarations that must be defined by the class
that implements it.Interfaces are useful for:
a) Declaring methods that one or moreclasses are expected to implement
b) Capturing similarities betweenunrelated classes without forcing a class relationship.
c) Determining anobject‘s programming interface without revealing the actual body of
the
class
10
16. What are the types of Exceptions in Java
There are two types of exceptions in Java, unchecked exceptions andchecked exceptions.
Checked exceptions:
A checked exception is some subclass of Exception (orException itself), excluding class
Runtime Exception and its subclasses. Eachmethod must either handle all checked
exceptions by supplying a catchclause or list each unhandled checked exception as a
thrown exception.
Unchecked exceptions:
All Exceptions that extend the Runtime Exceptionclass are unchecked exceptions. Class
Error and its subclasses also areunchecked.
17. Whatis the difference between String and String Buffer?
a) String objects are constants and immutable whereas String Buffer objects are not.
b) String class supports constant strings whereas String Buffer class supports grow able
and modifiablestrings.
18.What are different types of access modifiers (Access specifiers)?
Access specifiers are keywords that determine the type of accessto the member of a class.
These keywords are for allowingprivileges to parts of a program such as functions and
variables. Theseare:
Public: Anything declared as public can be accessed from anywhere.
Private: Anything declared as private can‘t be seen outside of its class.
Protected: Anything declared as protected can be accessed by classes inthe same package
and subclasses in the other packages.
Default modifier : Can be accessed only to classes in thesame package.
19. What is multithreading?
Java provides built-in support for multithreadedprogramming. A multithreaded program
contains two or more parts that can runconcurrently. Each part of such a program is
called a thread, and each thread definesa separate path of execution. Thus, multithreading
is a specialized form of multitasking.
20. What is an applets?
Applets are small applications that are accessed on anInternet server, transported over the
Internet, automatically installed, and run as part of a webdocument. After an applet
arrives on the client, it has limited access to resources so that itcan produce a graphical
user interface and run complex computations without introducingthe risk of viruses or
breaching data integrity.
11
SECTION C: QUESTIONS & ANSWERS
UNIT –I JAVA PROGRAMMING
1. Explain in detail about operator in java with example? (16)
Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical. Java also defines some
additional operators that handle certain special situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators:
Operator | Result:
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
– – Decrement
The operands of the arithmetic operators must be of a numeric type. You cannot use
them on boolean types, but you can use them on char types, since the char type in Java
is,essentially, a subset of int.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
12
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types, long, int,
short,char, and byte. These operators act upon the individual bits of their operands.
They aresummarized in the following table:
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome
of
each operation.
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then
the resultant bit is a 1, as shown here:
The Bitwise XOR
13
// Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
output from this program:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown
here:
14
Example:
int a = 4;
int b = 1;
boolean c = a < b;
Boolean Logical Operators
The Boolean logical operators shown here operate only on boolean operands. All of the
binary logical operators combine two boolean values to form a resultant boolean value.
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way
that they operate on the bits of an integer. The logical ! operator inverts the Boolean state:
!true == false and !false == true. The following table shows the effect of each logical
operation:
// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
15
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
O/P:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
The Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator works in
Java much as it does in any other computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression.
For example,
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
The ? Operator
Ternary (three-way) operator that can replace certain types of if-then-else
Statements .The ? has this general form:
expression1? expression2:expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1
istrue, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of
the ?operation is that of the expression evaluated. Both expression2 and expression3 are
requiredto return the same type, which can‘t be void.
Example:
ratio = denom == 0 ? 0 : num / denom;
16
2. i) Discuss in detail the access specifiers available in Java.(8)
ii)What is Array? How to declare array?Discuss the methods under array class. (8)
i) Discuss in detail the access specifiers available in Java.(8)
Java‘s four level of access protection:
 Public
 Private
 Protected
 Default
Some aspects of access control are related mostly to inheritance or package. (A package
is,essentially, a grouping of classes) protected is applied only when inheritance is
invoked. :
Public Access: When a member of a class is modified by public specifier, then that
member can be accessed by any other code. Now you can understand why main () has
always been preceded by the public specifier.it is called by code that is outside the
program that is by java run time system
Private Access: when a member of class is specified as private, then that member can
only be accessed by other members of its class.
protected:
Variables, methods and constructors which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class.The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected.Protected access gives the subclass a chance to use
the helper method or variable, while preventing a nonrelated class from trying to use it.
Default Access: when no specifier is used then by default the member of class is public
within its own package, but cannot be accessed outside of its package.in the classes
development so far ,all members of a class have use the default access mode .which is
essentially public. This access specifier is also known as friendly access.
table showing all the access specifiers and theiraccessibility in the class, package,
subclasses andother packages.
17
Example of public & private
/* Program to demonstrate Access Protection */
class Demo {
int p; // default access
public int q; // public access
private int r; // private access
// methods to access r
void setr(int i)
{ // set r's value
r = i;
}
int getr()
{ // get r's value
return r;
}
}
class AccessProDemo
{
public static void main(String args[])
{
Demo d= new Demo();
// OK : 'p' and 'q' may be accessed directly
d.p=300;
d.q=400;
// NOT OK : 'r' cannot be accessed outside the class, hence will cause an error
// d.r=50;
// You must access 'r' through its methods
d.setr(500); //OK
System.out.println(" p, q, and r = "+d.p+", "+d.q+", and "+d.getr());
}
}
o/p:- P, q, and r =300,400, and 500
18
2.ii) What is Array? How to declare array?Discuss the methods under array class.
An array is a data structure that stores a collection of values of the same type. You access
each individualvalue through an integer index.
Array Name [index]
Integer constant, variable, or expression
For Instance we can define
an array name salary to represent a set of salaries of a group of employees. Aparticular
value is indicated by writing a number called index in brackets after the array name.
salary [10]
it represents the salary of the 10th employee.
Types of arrays
One dimensional arrays
Two dimensional arrays
One Dimensional arrays
A list of items can be given one variable name using only one subscript and such a
variable iscalled single - subscripted of one dimensional array. The subscript can also
start from 0. ie x[0].
If we want to represent a set of five numbers, say (35,40,20,57,19) by an array variable
number,then we have to create the variable number as follows
int number [ ] = new int [5 ];
The value to the array elements can be assigned as follows
Number[0] =35;
Number [1] =40;
Number [2] =20;
Number [3] =57;
Number [4] =19;
This would cause the array number to store the values shown as follows;
Creating an array
Declaring the array
Creating memory locations
Putting values into the memory locations.
Declaring the Array
Array in java can be declared in two forms
Form 1
type arrayname [ ];
Form 2
type [ ] arrayname;
Creation of arrays
arrayname = new type [ size ];
Eg;
number = new int [5] ;
average = new float[10];
it is also
possible to combine declaration and creation.
int number [ ] = new int [5];
Initialization of arrays
19
The final step is to put values into the array created. This process is known as
initialization usingthe array subscripts as shown below.
arrayname[subscript] = value ;
Eg
number[0] = 15;
we can also initialize by following way
typearrayname [ ] = { list of values }
Array Length
All array store the allocated size in an variable named length. We can obtain the length of
array ausing a.length
Eg:
intasize = a.length;
Sample Code for array manipulation
Two Dimensional arrary:
Usage :intmyArray [ ] [ ];
myArray= new int [3] [4];
or
initmyArray [ ] [ ] = new int [3][4]
This creates a table that can store 12 integer values, four across and three down.
Strings:
Series of characters represents a string, and easiest way to represent the string is array
Eg:
Char charArray [ ] = new char [2] ;
charArray[0] = „j‟ ;
charArray[1] = „a‟ ;
String can be declared and created in the following way
string stringname;
stringname = new string (―string‖);
Operations on string
int m = stringname.length() //will return the length of the string
string city = ―New‖ + ―Delhi‖// will return New Delhi ,string concatenating Sample Code
forstring Manipulation
3. Explain Packages in detail with example. (16)
Packages are java‟s way of grouping a variety of classes and/or interfaces together.
Packages are container for the classes.
It is stored in a hierarichical manner.
If we want to use the packages in a class, we want to import it.
The two types of packages are:
1. System package.
2. User defined package.
Uses of Packages:
Packages reduce the complexity of the software because a large number of classes can be
grouped into a limited number of packages.
20
We can create classes with same name in different packages.
Using packages we can hide classes.
We may like to use many of the classes contained in a package.it can be achieved by
Import packagename .classname
Or
Import packagename.*
Creating the
package
To create our own packages
packagefirstpackage;// package declaration
public class FirstClass //class definition
{.....
(body of class)
.......}
The file is saved as FirstClass.java,located at firstpackage directory. when it is
compiled .class file will be
created in same ditectory.
Access a package
The import statement can be used to search a list of packages for a particular class. The
general
form of import statement for searching class is a as follows.
Import package1 [.package2] [.package3].classname;
Using the package
package package1 ;
public class classA
{
public void displayA()
{
System.out.println(―class A‖);
}
}
Adding a class to package
Define the class and make it public
Place the package statement
Package P1
Before the class definition as follows
Package p1;
Public class B
Package name
{
// body of B
}
Example:
Package college
Class student
{
21
intregno;
String name;
Student(intr,stringna);
{
Regno=r
Name=na
}
Public void print()
{
System.out.println(―Regno‖+regno );
System.out.println(―Name‖+name );
}
}
Package Course
Class engineering
{
Intregno;
String branch;
String year;
Engineering(int r, string br, string yr)
{
Regno=br;
Branch=br;
Year=yr;
}
public void print()
{
Systems.out.println(―Regno‖+regno);
Systems.out.println(―
Branch‖+branch);
Systems.out.println(―Year‖+year);
}
}
import college.*;
import course.*;
Class demo
{
Public static void main(string args[])
{
Student sl=new Engineering(1,‖CSE‖,‖III
Year‖);
Sl.print();
El.print();
}
}
22
4. Explain the concept of inheritance and its types. (16)
There exist basically three types of inheritance.
 Multilevel inheritance
 Multiple inheritance
 Hierarchical inheritance
1. In single inheritance, one class extends one class only. In multilevel inheritance, the
ladder of single inheritance increases.
2. In multiple inheritance, one class directly extends more than one class.
3. In hierarchical inheritance one class is extended by more than one class.
1. Single Inheritance
When a single derived class is created from a single base class then the inheritance is
called as single inheritance.
1. Multilevel Inheritance
In multilevel, one-to-one ladder increases. Multiple classes are involved in inheritance,
but one class extends only one. The lowermost subclass can make use of all its super
classes' members. Multilevel inheritance is an indirect way of implementing multiple
inheritance. Following program explains.
class Aves
{
public void nature()
{
System.out.println("Generally, Aves fly");
}
}
class Bird extends Aves
{
public void eat()
{
System.out.println("Eats to live");
}
}
23
public class Parrot extends Bird
{
public void food()
{
System.out.println("Parrot eats seeds and fruits");
}
public static void main(String args[])
{
Parrot p1 = new Parrot();
p1.food(); // calling its own
p1.eat(); // calling super class Bird method
p1.nature(); // calling super class Aves method
}
}
Now, Parrot has two super classes Bird and Aves; but extended one-to-one. Parrot can
make use of the methods of Bird and Aves. Bird can make use of the methods of Aves,
but Parrot as a super class cannot access subclass members. Following figure gives a
schematic representation of the multilevel hierarchy with the classes involved in the
program.
2. Multiple Inheritance
In multiple inheritance, one class extends multiple classes. Java does not support
multiple inheritance but C++ supports. The above program can be modified to illustrate
multiple inheritance. The following program does not work.
calss Aves { }
class Bird { }
24
publicclass Parrot extends Aves, Bird { }
In the above code, Parrot extends both Aves and Bird. This is not supported by Java and
the above code raises compilation error. Following is the schematic representation.
Note: Java supports multiple inheritance partially through interfaces.
3. Hierarchical Inheritance
In hierarchical type of inheritance, one class is extended by many subclasses. It is one-
to-many relationship. A realtime example is available at dynamic binding.
class Aves
{
publicvoid fly()
{
System.out.println("Generally, aves fly");
}
}
class Parrot extends Aves
{
publicvoid eat()
{
System.out.println("Parrot eats fruits and seeds");
}
}
class Vulture extends Aves
{
publicvoid vision()
{
System.out.println("Vulture can see from high altitudes");
}
}
publicclass FlyingCreatures
{
publicstaticvoid main(String args[])
{ // all the following code is composition for FlyingCreatures
Parrot p1 = new Parrot();
p1.eat(); // calling its own member
p1.fly();
25
// calling super class member by inheritance
Vulture v1 = new Vulture();
v1.vision(); // calling its own member
v1.fly(); // calling super class member by inheritance
}}
Output screen of FlyingCreatures.java
In the above code, Aves class is extended by two classes – Parrot and Vulture. Both
classes can make use of the methods of Aves. Even though the Parrot and Vulture are
subclasses of the same class Aves, but still they cannot make use of each other members.
Parrot and Vulture are known as "siblings". Siblings are disjoint and they cannot make
use of other members as between them no inheritance is involved (like two sons of a
father; one son's property cannot be shared by other but both can share the property of
father). Following is the schematic representation of the classes involved.
Dynamic binding and dynamic polymorphism use hierarchical inheritance.
Disadvantages of Inheritance
1. Both classes (super and subclasses) are tightly-coupled.
2. As they are tightly coupled (binded each other strongly with extends keyword),
they cannot work independently of each other.
3. Changing the code in super class method also affects the subclass functionality.
4. If super class method is deleted, the code may not work as subclass may call the
super class method with super keyword. Now subclass method behaves
independently.
26
5. Explain the different ways to handle exceptions in java. (16)
An exception is a problem that arises during the execution of a program. An exception
can occur formany different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run
out ofmemory.
Some of these exceptions are caused by user error, others by programmer error, and
others byphysical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three
categories ofexceptions:
Checked exceptions: A checked exception is an exception that is typically a user error or
aproblem that cannot be foreseen by the programmer. For example, if a file is to be
opened,
but the file cannot be found, an exception occurs. These exceptions cannot simply be
ignoredat the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably
could
have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely
doanything about an error. For example, if a stack overflow occurs, an error will arise.
They are alsoignored at the time of compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is
asubclass of the Throwable class. Other than the exception class there is another subclass
calledError which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally
happen in case ofsevere failures, which are not handled by the java programs. Errors are
generated to indicate errorsgenerated by the runtime environment.
Example : JVM is out of Memory. Normally programs cannotrecover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException
Class.
27
Here is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods:
Following is the list of important medthods available in the Throwable class.
Methods with Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message
isinitialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error
outputstream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index
0represents the top of the call stack, and the last element in the array represents
themethod at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to
anyprevious information in the stack trace.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A
try/catchblock is placed around the code that might generate an exception. Code within a
try/catch block isreferred to as protected code, and the syntax for using try/catch looks
like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
28
}
A catch statement involves declaring the type of exception you are trying to catch. If an
exceptionoccurs in protected code, the catch block (or blocks) that follows the try is
checked. If the type ofexception that occurred is listed in a catch block, the exception is
passed to the catch block muchas an argument is passed into a method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the
3rd elementof the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This would produce the following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for multiple catch
blocks looks likethe following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
themafter a single try. If an exception occurs in the protected code, the exception is
thrown to the firstcatch block in the list. If the data type of the exception thrown matches
ExceptionType1, it getscaught there. If not, the exception passes down to the second
catch statement. This continuesuntil the exception either is caught or falls through all
29
catches, in which case the current methodstops execution and the exception is thrown
down to the previous method on the call stack.
Example:
Here is code segment showing how to use multiple try/catch statements.
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using the
throwskeyword. throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, byusing the throw keyword. Try to understand the different in throws and throw
keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the
exceptions are
declared in a list separated by commas. For example, the following method declares that
it throws aRemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
30
//Remainder of class definition
}
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally
block of codealways executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to
execute, nomatter what happens in the protected code.A finally block appears at the end
of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
This would produce the following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following:
31
A catch clause cannot exist without a try statement.It is not compulsory to have finally
clauses when ever a try/catch block is present.The try block cannot be present without
either catch clause or finally clause.Any code cannot be present in between the try, catch,
finally blocks.
Declaring you own Exception:
You can create your own exceptions in Java. Keep the following points in mind when
writing your ownexception classes:
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}
You just need to extend the Exception class to create your own Exception class. These
are
considered to be checked exceptions. The following InsufficientFundsException class is a
userdefinedexception that extends the Exception class, making it a checked exception. An
exceptionclass is like any other class, containing useful fields and methods.
Example:
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class
contains awithdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
32
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods ofCheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
33
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce the following
result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Common Exceptions:
In Java, it is possible to define two catergories of Exceptions and Errors.
JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown
by the
JVM.Examples:NullPointerException,ArrayIndexOutOfBoundsException,
ClassCastException,
Programmatic exceptions: - These exceptions are thrown explicitly by the application
or
the API programmers Examples: IllegalArgumentException, IllegalStateException
6.Explain in detail about Multithreading in java. (16)
Java provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is
called a thread, and each thread defines a separate path of execution. Thus,
multithreading is a specialized form of multitasking.
Multithreading enables you to write very efficient programs that make maximum use of
the CPU, because idle time can be kept to a minimum. This is especially important for the
interactive, networked environment in which Java operates, because idle time is common.
For example, the transmission rate of data over a network is much slower than the rate at
which the computer can process it. Even local file system resources are read and written
at a much slower pace than they can be processed by the CPU. And, of course, user input
is much slower than the computer
The Thread Class and the Runnable Interface
Java‘s multithreading system is built upon the Thread class, its methods, and its
companion interface, Runnable. Thread encapsulates a thread of execution. Since you
can‘t directly refer to the ethereal state of a running thread, you will deal with it through
its proxy, the Thread instance that spawned it. To create a new thread, your program will
either extend Thread or implement the Runnable interface.
The Thread class defines several methods that help manage threads. The ones that will
be used in this chapter are shown here:
34
The Main Thread
When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of your program, because it is the one that is executed when your
program begins. The main thread is important for two reasons:
• It is the thread from which other ―child‖ threads will be spawned.
• Often, it must be the last thread to finish execution because it performs various
shutdown actions.
Creating a Thread
In the most general sense, you create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished:
• You can implement the Runnable interface.
• You can extend the Thread class, itself.
The following two sections look at each method, in turn.
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface.
Runnable abstracts a unit of executable code. You can construct a thread on any object
that implements Runnable. To implement Runnable, a class need only implement a
single method called run( ), which is declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables,
just like the main thread can. The only difference is that run( ) establishes the entry point
for another, concurrent thread of execution within your program. This thread will end
when run( ) returns.
Here is an example that creates a new thread and starts it running:
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
35
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Inside NewThread‘s constructor, a new Thread object is created by the following
statement:
t = new Thread(this, "Demo Thread");
o/p:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
36
Creating Multiple Threads
So far, you have been using only two threads: the main thread and one child thread.
However, your program can spawn as many threads as it needs. For example, the
following program creates three child threads:
// Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
The output from this program is shown here:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
37
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
38
UNIT –II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
PART-A:
1. What are the necessities of using HTML forms?
Gathering user information
Conducting Surveys
Interactive services
2. Define HTML.
It is a simple page description language, which enables document creation for the web.
3. What do you understand about DOCTYPE in HTML?
A Document Type Declaration, or DOCTYPE, is an instruction that associates a
particular SGML or XML document (for example, a web page) with a Document Type
Definition(DTD) (for example, the formal definition of a particular version of HTML). It
manifests as a short string of markup that conforms to a particular syntax.
4. What are the Hyperlink, Anchors and Link in the HTML?
The <a> tag can be used in two ways:
1.To create a link to another document, by using the href attribute
2.To create a bookmark inside a document, by using the name attribute
<a href="url">Link text</a> - The href attribute specifies the destination of a link.
5. How you define HTML Style Attribute in HTML?
The <style> tag is used to define style information for an HTML document. Inside the
style element you specify how HTML elements should render in a browser.
The required type attribute defines the content of the style element. The only possible
value is "text/css". The style element always goes inside the head section.
<head>
<styletype="text/css">
h1 {color:red}</style> </head>
6. HTML is case sensitive or not?
Html is not a case sensitive language. <P> means the same as <p>.But a combination of
upper and lower case letters must not be used.
7. How to use form’s action attribute and submit button in html?
The required action attribute specifies where to send the form-data when a form is
submitted.
<form action="form_action.asp" method="get"> ,, </form>
<input type="submit" /> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page
specified in the form's action attribute.
<input type="submit" value="Submit" />
8. How to use Line Break and Horizontal Line tags in HTML?
The <br> tag inserts a single line break. It‘s a empty tag, i.e. it has no end tag. The <hr>
tag creates a horizontal line in the html page, and can be used to separate the contents in a
html page. It is also an empty tag with no empty tag.
39
9. What are Style Sheets?
CSS stands for Cascading Style Sheets. Styles define how to display HTML elements.
Styles were added to HTML 4.0 to solve a problem. External Style Sheets can save a lot
of work. External Style Sheets are stored in CSS files.
10. List down the ways of including style information in a document.
There are three main ways to include styles into a document namely, external style
sheets, embedded style sheets and inline styles.
11. What are the style precedence rules when using multiple approaches?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style
sheet by the following rules, where number four has the highest priority:
 Browser default
 External style sheet
 Internal style sheet (in the head section)
 Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it
will override a style defined inside the <head> tag, or in an external style sheet, or in a
browser (a default value).
12. Give the syntax to specify a characteristic in linked style sheet.
{Characteristic:Value;} Multiple Characteristic/Values should
be separated by semicolons.
13. List down font characteristics permitted in style sheets.
Font – family, font – size, font – weight, font- style and font – variant.
14. How to toggle display an HTML element?
An element in HTML can be toggle displayed using the style. Display parameter inside a
separate toggle function.
15. What is the HTML DOM?
The HTML DOM is:
A standard object model for HTML
A standard programming interface for HTML Platform- and language-independent A
W3C standard The HTML DOM defines the objects and properties of all HTML
elements, and the methods (interface) to access them.
40
UNIT-II PART -B
1. Explain Basic internet protocols and HTTP message format?(16)
Internet Protocol:
The Internet protocols are the world‘s most popular open-system (nonproprietary)
protocol suite because they can be used to communicate across any set of interconnected
networks and are equally well suited for LAN and WAN communications. The Internet
protocols consist of a suite of communication protocols, of which the two best known are
the Transmission Control Protocol (TCP) and the Internet Protocol (IP). The Internet
protocol suite not only includes lower-layer protocols (such as TCP and IP), but it also
specifies common applications such as electronic mail, terminal emulation, and file
transfer.
Internet protocols were first developed in the mid-1970s, when the Defense Advanced
Research Projects Agency (DARPA) became interested in establishing a packet-switched
network that would facilitate communication between dissimilar computer systems at
research institutions. With the goal of heterogeneous connectivity in mind, DARPA
funded research by Stanford University and Bolt, Beranek, and Newman (BBN). The
result of this development effort was the Internet protocol suite, completed in the late
1970s. TCP/IP later was included with Berkeley Software Distribution (BSD) UNIX and
has since become the foundation on which the Internet and the World Wide Web
(WWW) are based
41
Internet Protocol (IP)
The Internet Protocol (IP) is a network-layer (Layer 3) protocol that contains addressing
information and some control information that enables packets to be routed. IP is
documented in RFC 791 and is the primary network-layer protocol in the Internet
protocol suite. Along with the Transmission Control Protocol (TCP), IP represents the
heart of the Internet protocols. IP has two primary responsibilities: providing
connectionless, best-effort delivery of datagram‘s through an internetwork; and providing
fragmentation and reassembly of datagrams to support data links with different
maximum-transmission unit (MTU) sizes.
IP Packet Format
An IP packet contains several types of information, as illustrated in Figure 30-2.
The following discussion describes the IP packet fields illustrated in Figure 30-2:
• Version—Indicates the version of IP currently used.
• IP Header Length (IHL)—Indicates the datagram header length in 32-bit words.
• Type-of-Service—Specifies how an upper-layer protocol would like a current datagram
to be handled, and assigns datagrams various levels of importance.
• Total Length—Specifies the length, in bytes, of the entire IP packet, including the data
and header.
• Identification—Contains an integer that identifies the current datagram. This field is
used to help piece together datagram fragments.
• Flags—Consists of a 3-bit field of which the two low-order (least-significant) bits
control fragmentation. The low-order bit specifies whether the packet can be fragmented.
The middle bit specifies whether the packet is the last fragment in a series of fragmented
packets. The third or high-order bit is not used.
• Fragment Offset—Indicates the position of the fragment‘s data relative to the beginning
of the data in the original datagram, which allows the destination IP process to properly
reconstruct the original datagram.
42
• Time-to-Live—Maintains a counter that gradually decrements down to zero, at which
point the datagram is discarded. This keeps packets from looping endlessly.
• Protocol—Indicates which upper-layer protocol receives incoming packets after IP
processing is complete.
• Header Checksum—Helps ensure IP header integrity.
• Source Address—Specifies the sending node.
• Destination Address—Specifies the receiving node.
•Options—Allows IP to support various options, such as security.
•Data—Contains upper-layer information
HTTP message format:
HyperText Transfer Protocol (HTTP)
HTTP (Hypertext Transfer Protocol) is perhaps the most popular application protocol
used in the Internet (or The WEB).
HTTP is an asymmetric request-response client-server protocol as illustrated. An HTTP
client sends a request message to an HTTP server. The server, in turn, returns a response
message. In other words, HTTP is a pull protocol, the client pulls information from the
server (instead of server pushes information down to the client).
 HTTP is a stateless protocol. In other words, the current request does not know
what has been done in the previous requests.
 HTTP permits negotiating of data type and representation, so as to allow systems
to be built independently of the data being transferred.
 Quoting from the RFC2616: "The Hypertext Transfer Protocol (HTTP) is an
application-level protocol for distributed, collaborative, hypermedia information
systems. It is a generic, stateless, protocol which can be used for many tasks
beyond its use for hypertext, such as name servers and distributed object
management systems, through extension of its request methods, error codes and
headers."
43
HTTP Request and Response Messages
HTTP client and server communicate by sending text messages. The client sends a
request message to the server. The server, in turn, returns a response message.
An HTTP message consists of a message header and an optional message body, separated
by a blank line, as illustrated below:
HTTP Request Message
The format of an HTTP request message is as follow:
Request Line
The first line of the header is called the request line, followed by optional request
headers.
The request line has the following syntax:
request-method-name request-URI HTTP-version
44
 request-method-name: HTTP protocol defines a set of request methods, e.g.,
GET, POST, HEAD, and OPTIONS. The client can use one of these methods to
send a request to the server.
 request-URI: specifies the resource requested.
 HTTP-version: Two versions are currently in use: HTTP/1.0 and HTTP/1.1.
Examples of request line are:
GET /test.html HTTP/1.1
HEAD /query.html HTTP/1.0
POST /index.html HTTP/1.1
Request Headers
The request headers are in the form of name:value pairs. Multiple values, separated by
commas, can be specified.
request-header-name: request-header-value1, request-header-value2, ...
Examples of request headers are:
Host: www.xyz.com
Connection: Keep-Alive
Accept: image/gif, image/jpeg, */*
Accept-Language: us-en, fr, cn
Example
The following shows a sample HTTP request message:
HTTP Response Message
The format of the HTTP response message is as follows:
45
Status Line
The first line is called the status line, followed by optional response header(s).
The status line has the following syntax:
HTTP-version status-code reason-phrase
 HTTP-version: The HTTP version used in this session. Either HTTP/1.0 and
HTTP/1.1.
 status-code: a 3-digit number generated by the server to reflect the outcome of the
request.
 reason-phrase: gives a short explanation to the status code.
 Common status code and reason phrase are "200 OK", "404 Not Found", "403
Forbidden", "500 Internal Server Error".
Examples of status line are:
HTTP/1.1 200 OK
HTTP/1.0 404 Not Found
HTTP/1.1 403 Forbidden
Response Headers
The response headers are in the form name:value pairs:
response-header-name: response-header-value1, response-header-value2, ...
Examples of response headers are:
Content-Type: text/html
Content-Length: 35
Connection: Keep-Alive
Keep-Alive: timeout=15, max=100
The response message body contains the resource data requested.
Example
The following shows a sample response message:
HTTP Request Methods
HTTP protocol defines a set of request methods. A client can use one of these request
methods to send a request message to an HTTP server. The methods are:
 GET: A client can use the GET request to get a web resource from the server.
 HEAD: A client can use the HEAD request to get the header that a GET request
would have obtained. Since the header contains the last-modified date of the data,
this can be used to check against the local cache copy.
 POST: Used to post data up to the web server.
46
 PUT: Ask the server to store the data.
 DELETE: Ask the server to delete the data.
 TRACE: Ask the server to return a diagnostic trace of the actions it takes.
 OPTIONS: Ask the server to return the list of request methods it supports.
 CONNECT: Used to tell a proxy to make a connection to another host and simply
reply the content, without attempting to parse or cache it. This is often used to
make SSL connection through the proxy.
 Other extension methods.
"GET" Request Method
GET is the most common HTTP request method. A client can use the GET request
method to request (or "get") for a piece of resource from an HTTP server. A GET request
message takes the following syntax:
GET request-URI HTTP-version
(optional request headers)
(blank line)
(optional request body)
 The keyword GET is case sensitive and must be in uppercase.
 request-URI: specifies the path of resource requested, which must begin from the
root "/" of the document base directory.
 HTTP-version: Either HTTP/1.0 or HTTP/1.1. This client negotiates the protocol
to be used for the current session. For example, the client may request to use
HTTP/1.1. If the server does not support HTTP/1.1, it may inform the client in the
response to use HTTP/1.0.
 The client uses the optional request headers (such as Accept, Accept-Language,
and etc) to negotiate with the server and ask the server to deliver the preferred
contents (e.g., in the language that the client preferred).
 GET request message has an optional request body which contains the query
string (to be explained later).
Response Status Code
The first line of the response message (i.e., the status line) contains the response status
code, which is generated by the server to indicate the outcome of the request.
The status code is a 3-digit number:
 1xx (Informational): Request received, server is continuing the process.
 2xx (Success): The request was successfully received, understood, accepted and
serviced.
 3xx (Redirection): Further action must be taken in order to complete the request.
 4xx (Client Error): The request contains bad syntax or cannot be understood.
 5xx (Server Error): The server failed to fulfill an apparently valid request.
Some commonly encountered status codes are:
 100 Continue: The server received the request and in the process of giving the
response.
 200 OK: The request is fulfilled.
 301 Move Permanently: The resource requested for has been permanently moved
to a new location. The URL of the new location is given in the response header
47
called Location. The client should issue a new request to the new location.
Application should update all references to this new location.
 302 Found & Redirect (or Move Temporarily): Same as 301, but the new location
is temporarily in nature. The client should issue a new request, but applications
need not update the references.
 304 Not Modified: In response to the If-Modified-Since conditional GET request,
the server notifies that the resource requested has not been modified.
 400 Bad Request: Server could not interpret or understand the request, probably
syntax error in the request message.
 401 Authentication Required: The requested resource is protected, and require
client‘s credential (username/password). The client should re-submit the request
with his credential (username/password).
 403 Forbidden: Server refuses to supply the resource, regardless of identity of
client.
 404 Not Found: The requested resource cannot be found in the server.
 405 Method Not Allowed: The request method used, e.g., POST, PUT, DELETE,
is a valid method. However, the server does not allow that method for the
resource requested.
 408 Request Timeout:
 414 Request URI too Large:
 500 Internal Server Error: Server is confused, often caused by an error in the
server-side program responding to the request.
 501 Method Not Implemented: The request method used is invalid (could be
caused by a typing error, e.g., "GET" misspell as "Get").
 502 Bad Gateway: Proxy or Gateway indicates that it receives a bad response
from the upstream server.
 503 Service Unavailable: Server cannot response due to overloading or
maintenance. The client can try again later.
 504 Gateway Timeout: Proxy or Gateway indicates that it receives a timeout from
an upstream server.
48
2. To create a web page that displays college information using various styles
HTML CODE:
<html>
<head><h1><center>ALL STYLE SHEETS</center></h1>
<title>USE of INTERNAL and EXTERNAL STYLESHEETS
</title>
<link rel="stylesheet" href="xyz.css" type="text/css">
<style type="text/css">
.vid{font-family:verdana;font-style:italic;color:red;text-align:center}
.ani{font-family:tahoma;font-style:italic;font-size:20;text-align:center;}
font{font-family:georgia;color:blue;font-size:20}
ul{list-style-type:circle}
</style>
</head>
<body>
<ol style="list-style-type:lower-alpha">
<b>PERI GROUP OF COLLEGES</b><br><br><br>
<li>Raj Engineering College
<li>PERI University and Research Institute
<li> College of Engineering, Bangalore
<li>Tamilnadu College of Arts and Science
</ol>
<p style="font-size:20pt;color:purple">A.C.S GROUP OF COLLEGES</p>
<p class="ani">CSS Group of colleges is owned by XXX.<br>It is approved by
International Council It is affliated to JKK University.<br></p>
<h2 class="vid">DES College of Engg</h2>
<br>
<font>It is an ISO certified Institution</font><br>
<br>
<font>
<h2>List of Courses offered</h2>
<ul>
<li>Computer Science and Engineering</li>
<li>Ece</li>
<li>mech</li>
<li>eee</li>
</ul>
</font>
<h3>Results of cse students</h3>
<table width="100%" cellspacing="2" cellpadding="2" border="5">
49
<tr>
<th>S.NAME</th>
<th>MARKS</th>
<th>RESULT</th>
</tr>
<tr>
<td align="center">Dinesh</td>
<td align="center">100</td>
<td align="center">pass</td>
</tr>
<tr>
<td align="center">Bala</td>
<td align="center">99</td>
<td align="center">pass</td>
</tr>
<tr>
<td align="center">Gopi</td>
<td align="center">98</td>
<td align="center">pass</td>
</tr>
</table>
</body>
</html>
XYZ.CSS:
h3{font-family:arial;font-size:20;color:cyan}
table{border-color:green}
td{font-size:20pt;color:magenta}
50
3. Explain XHTML Syntax and semantics with example.(16)
XHTML – EXtensible HyperText Markup Language
 is HTML defined as an XML application
 is a stricter and cleaner HTML
 is compatible to HTML 4.01 and supported by all browsers
 is a W3C recommendation
Why XHTML ?
the following, ―bad‖ html document will work fine in most browser even if it does not
follow HTML rules:
<html>
<head>
<body>
<p>a paragraph…<br>
<a href=―#‖>test
</html>
 but browsers running on hand-held devices (e.g. mobile phones) have small
computing power and can not interpret ―bad‖ markup language
 HTML is designed to structure (and display) data and XML is designed to
describe and structure data
 XHTML specifies that everything must be marked up correctly
 XHTML – base syntactic rules
 XHTML elements must be properly nested
<b><i> Italic and bold text </b></i>
<b><i> Italic and bold text </i></b>
 XHTML elements must always be closed
<p> A paragraph…
<br>
<img src=―foo.jpg‖>
<p> A paragraph…</p>
<br />
<img src=―foo.jpg‖ />
 XHTML elements must be in lowercase
 XHTML elements must have one <html> root element (which contains a <head>
and a <body>)
XHTML – other syntactic rules
 attribute names must be in lower case
 attribute values must be quoted
<table width=300px>
<table width=―300px‖>
 the ―id‖ attribute replaces the ―name‖ attribute
 XHTML DTD defines mandatory elements
 attribute minimization is forbidden
<input checked>
51
<input disabled>
<input checked=―checked‖ />
<input disabled=―disabled‖ />
General format of an XHTML document
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>…</title>
</head>
<body>
…
</body>
</html>
<!Doctype>,<html>,<head>,<title>,<body> are mandatory
DTD – Document Type Definition
 a DTD specifies the syntax of a document written in a SGML language (HTML,
XHTML, XML) it specifies:
o the hierarchical structure of the document,
o element names and types
o element content type
o and attributes names and values
o XML 1.0 has 3 DTDs: Strict, Transitional and Frameset
DTD example (internal to XHTML file)
<!DOCTYPE course [
<!ELEMENT course (lecture+)>
<!ELEMENT lecture (title,bibliography,notes,examples)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT bibliography (#PCDATA)>
<!ELEMENT notes (#PCDATA)>
<!ELEMENT examples (#PCDATA)>
<!ATTLIST course professor CDATA #REQUIRED>
<!ATTLIST course title CDATA #REQUIRED>
<!ATTLIST course yearofstudy CDATA #REQUIRED>
<!ATTLIST course date CDATA #IMPLIED>
]>
XHTML validation
 a valid XHTML document is an XHTML document which obeys the rules of the
DTD specified by the <!Doctype> tag.
 the official W3C XHTML validator:
 http://validator.w3.org/check/referer
 XHTML DTD is split in 28 modules
52
3. i)Design a HTML Form for aRailwaay Reservation System? (8)
ii)Explain about different types of XHTML DTD(8)
Design a HTML Form for aRailwaay Reservation System?
<FOTRM METHOD=º Postº ACTION=http://server name/directory
name/Script name><HR>
PASSENGER NAME:
<INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR>
ADDRESS:
<INPUT TYPE=º Textº Name=º addº MAXLENGTH=º 24º <BR>
CITY:
<INPUT TYPE=º Textº Name=º cityº MAXLENGTH=º 24º <BR>
STATE:
<INPUT TYPE=º Textº Name=º stateº MAXLENGTH=º 24º
ZIP: <INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR>
</HR>
<INPUT TYPE=º submitº value=º reserveº ></FORM>
ii)Explain about different types of XHTML DTD(8)
Document Type Definitions (DTD)
A DTD specifies the syntax of a web page in SGML
DTDs are used by SGML applications, such as HTML, to specify rules for documents of
a particular type, including a set of elements and entity declarations
An XHTML DTD describes in precise, computer-readable language, the allowed syntax
of XHTML markup
There are three XHTML DTDs:
STRICT
TRANSITIONAL
FRAMESET
XHTML 1.0 Strict
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Use the strict DOCTYPE when you want really clean markup, free of presentational
clutter. Use it together with CSS.
XHTML 1.0 Transitional
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Use the transitional DOCTYPE when you want to still use HTML's presentational
features.
XHTML 1.0 Frameset
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
53
4. Explain Style sheets syntax and types of css with example.
Cascading Style Sheets (CSS) are a method of web design that formats web page content
according to a presentation style specified by the web page author. There are several
advantages to using CS to format the presentation elements of a web page. CSS
essentially separates document content from the manner in which it is presented, thus
allowing for more fluid transitions between various browser platforms. CSS also provides
for more precise control for spacing, alignment, and positioning of content without
relying on the need for layout tables or frames. Font style, color, and font size can all be
manipulated using CSS as well.
The basic CSS Syntax
Selector: is the hook used to choose what part(s) of your HTML to apply the CSS
to. It indicates the element to which the rule is applied. Following the selector is the...
•Declaration Block:Everything within the curly brackets, ―{‖ and ―}‖, is called the
declaration block
•Declaration: Inside a declaration block you can have as many declarations as you want
and each declaration is a combination of a CSS Property and a value.
•Property:is one of the CSS Properties used to tell what part of the selector will be
changed (or styled). It specifies a characteristic, such as color, font-family, position, and
is followed by a colon (:)
•Value:assigns a value to the property.
Types of selectors
CSS has several types of selectors. Explaining all of them in detail would take too long.
We will just introduce you with two most commonly used selectors. For a really in depth
study, you should look into the W3C specification for selectors.
Class and ID selectors
With the class selector you can define different styles for the same type of HTML
element.In our example, the class selector would look like this:
P.blue {color: blue;}
54
ID selector
The W3C defines CSS ID as "a unique identifier to an element". IDs are commonly used
for Layout and Uniqueness. Standards specify that any given ID name can only be
referenced once within a page or document. From our experience, IDs are most
commonly used correctly in CSS layouts. This makes sense because there are usually
only one menu per page, one banner, and usually only one content pane.
Grouping
You can group selectors. Separate each selector with a comma
H1, H2, H3, H4, H5, H6 {color: blue ;}
Positioning
The CSS positioning properties allow you to position an element.
There are five different layout properties available in CSS: position: static, position:
relative, position: absolute, and float.
Three ways to insert CSS
 Inline CSS
 Internal Style Sheets
 External Style Sheets
Inline CSS
The first way is called Inline Cascading Style Sheets. You can add CSS directly into the
elements in your markup with the ―style‖ attribute.
<div style=‖color:red;‖><p style=‖font-size:12px;‖>
―Style‖ is a ―Core HTML Attribute‖ so you can apply it to any visual HTML/XHTML
elements. This may seem to be the easiest way of using CSS, but it is not recommended
as it completely ignores the best parts of Cascading Style Sheets.
Internal Style Sheets
The second way adds CSS to a single document or web page by adding the following
code into the <head> of your document using the <style> element.
<style type="text/css">
hr {color: sienna}
p {margin-left:20px}
body {background-image:url("images/back40.gif")}
</style>
As you can see, <style> is an HTML element that is opened and closed. Within the
<style> element is the CSS that will be applied to that page. There is no limit to the
amount of CSS you can put inside the <style> element. You would enter this code in the
<head> area of your web page (anywhere after <head> and before </head> in your
HTML document) and that would apply this CSS to the elements of that web page.
External Style Sheets
The third and most advantageous way to embed CSS into a document uses External
Cascading Style Sheets (or External Style Sheets). An external CSS file is simply a text
file with a ―.css‖ extension. This file can then be included into many different pages.
55
This allows you to make one document that has the styling for your entire website. Then
you include that file into every page of your website. This is the recommended way of
using CSS in your website as it lets you make global visual changes (to an entire website)
by only tweaking one file. For Example, let‘s say you have a website where all the
paragraphs are black, and you want to change them to grey. Since you have an external
Style Sheet, you just open up that one CSS file and change the style for paragraphs to:
color:grey; Now all the paragraphs on your website are grey!
Here is the code you need to link the css fileto your webpages‖:
<link rel=“stylsheet” type="text/css" href=“style.css”>
Media Types
There are about 10 different media types in CSS, but most common types are Screen and
Print. CSS today allows you to link to more than one style sheet in your web page.
5.i)Explain about internet and intranet with difference.(8)
ii) Design a HTML document using relative positioning to nudge text to the left.
Internet
It is a worldwide system which has the following characteristics:
Internet is a world-wide / global system of interconnected computer networks.
Internet uses the standard Internet Protocol (TCP/IP) Every computer in internet is
identified by a unique IP address. IP Address is a unique set of numbers (such as
110.22.33.114) which identifies a computer‘s location.
A special computer DNS (Domain Name Server) is used to give name to the IP Address
so that user can locate a computer by a name.For example, a DNS server will resolve a
name http://www.periit.com to a particular IP address to uniquely identify the computer
on which this website is hosted. Internet is accessible to every user all over the world.
56
Intranet
Intranet is system in which multiple PCs are connected to each other. PCs in intranet are
not available to the world outside the intranet. Usually each company or organization has
their own Intranet network and members/employees of that company can access the
computers in their intranet. Each computer in Intranet is also identified by an IP Address
which is unique among the computers in that Intranet.
Similarities in Internet and Intranet
Intranet uses the internet protocols such as TCP/IP and FTP.
Intranet sites are accessible via web browser in similar way as websites in internet. But
only members of Intranet network can access intranet hosted sites.
In Intranet, own instant messengers can be used as similar to yahoo messenger/ gtalk over
the internet.
Differences in Internet and Intranet
Internet is general to PCs all over the world whereas Intranet is specific to few PCs.
Internet has wider access and provides a better access to websites to large population
whereas Intranet is restricted.
Internet is not as safe as Intranet as Intranet can be safely privatized as per the need.
ii) Design a HTML document using relative positioning to nudge text to the left
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
57
RelativePos.html
</title>
<style type="text/css">
.right { position:relative; right:0.25em }
</style>
</head>
<body>
<p>
<span style="background-color:red">&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class="right">Red</span>
<span style="background-color:yellow">&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class="right">Yellow</span>
<span style="background-color:lime">&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class="right">Green</span>
</p>
</body>
</html>
58
UNIT –III CLIENT SIDE AND SERVER SIDE PROGRAMMING
PART-A
1. How to create an Object in JavaScript?
An object is just a special kind of data, with a collection of properties and methods. You
can add properties to an object by simply giving it a value.
The sytax: objName.propName
2. What is the result of below given line of code in Java Script?
5+4+”7”
The answer is 97. Here 5 and 4 are integers, bt since 7 is enclosed within quotes, its
considered as a string, and hence is not added.
3.What is undefined value means in JavaScript?
Undefined value means the variable used in the code doesnt exist or is not assigned any
value or the property doesnt exist.
4. Which method is used to Clear an array using JavaScript?
Clear() method is used to clear all the defined array. we use the clear() method which
removes all elements from an Array instance. After removing the array by clear()
method, the resulting array's length will become zero.
5.What will be the Output of the following using JavaScript
document.Write(Math.Round(6.7));
The output will be 7. The math.round function is used to round off the value to the
nearest higher integer value.
6.What should appear at the very end of your JavaScript?
The <script LANGUAGE="JavaScript">tag
7.What is a JSP and what is it used for?
Java Server Pages (JSP) is a platform independent presentation layer technology that
comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces
embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the
background to generate a Servlet from the JSP page.
8. What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are
interpreted, and then group your tags into collections called tag libraries that can be used
in any number of JSP files. To use custom JSP tags, you need to define three separate
components:
The tag handler class that defines the tag's behavior the tag library descriptor file that
maps the XML element names to the tag implementations the JSP file that uses the tag
library
59
9. What are the implicit objects?
Implicit objects are objects that are created by the web container and contain information
related to a particular request, page, or application. They are: –request ,response,
pageContext, session application , out , config ,page ,exception
10. Compare Client side vs. server side scripting.
Website scripts run in one of two places – the client side, also called the front-end, or the
server side, also called the back-end. The client of a website refers to the web browser
that is viewing it. The server of a website is the server that hosts it.
Client side: JavaScript.
Server side: PHP ,Ruby on Rails, ASP.NET
11. State the 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.
12. What is JavaScript?
JavaScript is a programming language used to make web pages interactive. It runs on
your visitor's computer and doesn't require constant downloads from your website.
JavaScript is often used to create polls and quizzes
13. What is the purpose of cookies?
Cookies make the interaction between users and websites faster and easier. Without
cookies, it would be very difficult for a website to allow a visitor to fill up a shopping
cart or to remember the user's preferences or registration details for a future visit.
14. What are the steps needs to establish JDBC connectivity?
The programming involved to establish a JDBC connection is fairly simple. Here are
these simple four steps −
 Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.
 Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
 Database URL Formulation: This is to create a properly formatted address that
points to the database to which you wish to connect.
 Create Connection Object: Finally, code a call to the DriverManager object's
getConnection( ) method to establish actual database connection.
15. What is the difference between GET and POST method?
 GET is a safe method (idempotent) where POST is non-idempotent method.
60
 We can send limited data with GET method and it‘s sent in the header request
URL whereas we can send large amount of data with POST because it‘s part of
the body.
 GET method is not secure because data is exposed in the URL and we can easily
bookmark it and send similar request again, POST is secure because data is sent
in request body and we can‘t bookmark it.
 GET is the default HTTP method whereas we need to specify method as POST to
send request with POST method.
 Hyperlinks in a page uses GET method.
16. What is different between web server and application server?
A web server responsibility is to handler HTTP requests from client browsers and
responds with HTML response. A web server understands HTTP language and runs on
HTTPprotocol.
Apache Web Server is kind of a web server and then we have specific containers that can
execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support,
JMS Messaging support, Transaction Management etc. So we can say that Application
server is a web server with additional functionalities to help developers with enterprise
applications.
17. What are different methods of session management in servlets?
Session is a conversional state between client and server and it can consists of multiple
request and response between client and server. Since HTTP and Web Server both are
stateless, the only way to maintain a session is when some unique information about the
session (session id) is passed between server and client in every request and response.
Some of the common ways of session management in servlets are:
1. User Authentication
2. HTML Hidden Field
3. Cookies
4. URL Rewriting
5. Session Management API
18. What is difference between GenericServlet and HttpServlet?
GenericServlet is protocol independent implementation of Servlet interface whereas
HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet
for creating web application and that‘s why we extend HttpServlet class. HttpServlet
class extends GenericServlet and also provide some other methods specific to HTTP
protocol.
61
UNIT –III PART –B
1. Explain javascript variables and debuggers in detail . (16)
JavaScript Variables
JavaScript variables are used to hold values or expressions. A variable can have a short
name, like x, or a more descriptive name, like carname. Rules for JavaScript variable
names:
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character
Because JavaScript is case-sensitive, variable names are case-sensitive.
Declaring (Creating) JavaScript Variables
Creating variables in JavaScript is most often referred to as "declaring" variables. You
can declare JavaScript variables with the var keyword:
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5, and
carname will hold the valueVolvo.
Assigning Values to Undeclared JavaScript Variables
If you assign values to variables that have not yet been declared, the variables will
automatically be declared. These statements:
x=5;
carname="Volvo";
have the same effect as:
var x=5;
62
var carname="Volvo";
Redeclaring JavaScript Variables
If you redeclare a JavaScript variable, it will not lose its original value.
var x=5; var x;
After the execution of the statements above, the variable x will still have the value of 5.
The value of x is not reset (or cleared) when you redeclare it.
The Lifetime of JavaScript Variables
If you declare a variable within a function, the variable can only be accessed within that
function. When you exit the function, the variable is destroyed. These variables are called
local variables. You can have local variables with the same name in different functions,
because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it.
The lifetime of these variables starts when they are declared, and ends when the page is
closed
2. Discuss JavaScript Array object in detail. (16)
JavaScript Arrays
•Arrays are used to store lists or collections of items
•Arrays in JavaScript are indexed by numbers from 0
•Array elements can be any type, even arrays or objects
•An array‘s elements do not have to have the same type
Creating Arrays
Arrays can be created with the new keyword
var(myArray(=(new(Array();
var(myArray(=(new(Array(―one‖,―two‖,(3);
or with array literal syntax
var(myArray(=([];
var(myArray(=([―one‖,(―two‖,(3];
Updating Array Elements
Insert by index
myArray[5](=(―new(item‖;
Stack/queue-like interface
myArray.push(―new(item‖);
var(lastItem(=(myArray.pop();
var(firstItem(=(myArray.shift();
63
Iterating Over Arrays
var$myArray$=$[];
var$i;
myArray.push(―one‖);
myArray.push(―two‖);
myArray.push(―three‖);
for$(i=0;$i<myArray.length();$i+=1)${
console.log(myArray[i]);
}
Other Array Methods
var arrayLength = myArray.length();
myArray.length = 4;
myArray.reverse();
myArray.sort();
myArray.indexOf(―this item‖);
myArray.lastIndexOf(―this item‖);
JavaScript Objects
•Most things in JavaScript is an object - even functions
•Objects have properties and methods
•This distinction is vague, as functions are ‗first class‘
•Prototypes rather than class-based inheritance
•The this keyword refers to the current object
Creating Objects
var(obj1(=(new(Object();
var(emptyObject(=({};
var(myObject(=({
((((val1:(3,
((((val2:(―x‖,
((((func:(function()({
((((((((console.log(this.val1(+(―(―(+
((((((((((((((((((((this.val2);
((((}
}
Aside: Anonymous Functions
•The value assigned to this.func may look a little odd
•It is an an anonymous function, a function with no name
•This is much the same as any other function, but it
doesn‘t have a name
•Anonymous functions can have parameters, and are
commonly used when a function will be used just once
•This simplifies code and reduces namespace clutter
64
Using Objects
•You can dynamically add and update properties
•myObj.newVal(=(―New(property‖;
•myObj.val1(=(5;
•You can call methods (properties which are functions)
•myObj.func;
Object Constructors
function(MyConstructor()({
((((this.val1(=(3;
((((this.val2(=(―x‖;
((((this.func(=(function()({
((((((((console.log(this.val1(+(―(―(+
((((((((((((((((((((this.val2);
((((}
}
var(myObject(=(new(MyConstructor();
The this Keyword
•Note that the constructor assigns properties to this
•What exactly this is depends on the context
•In a constructor, this is the new object
•In an object‘s method, this is the object itself
•In a callback, this is the object that was triggered
•In a browser, this is the window object by default
Array-Like Objects
•Some JavaScript objects look like arrays (but aren‘t)
•document.getElementsByTagName(―p‖);
•They can be indexed with [] and have .length
•They don‘t have sort, push, etc.
•If you add elements then .length doesn‘t change
•What‘s going on here? •Objects can be indexed using [] as associative maps
•Property names are given inside the brackets
•And length is just another property
var$obj$=${length:$2};
obj[0]$=$―one‖;$obj[1]$=$―two‖;
obj.length$=$2;
var$obj2$=${0:―one‖,$1:―two‖,$length:2};
65
3. Write java script to perform all arithmetic operation (16)
<html>
<head>
<title> Arithmatic Operation </title>
<script type="text/javascript">
var n1,n2,r;
function add()
{
n1=document.myform.n1.value;
n2=document.myform.n2.value;
n1=parseFloat(n1);
n2=parseFloat(n2);
r=n1+n2;
document.myform.result.value=r;
}
function sub()
{
n1=document.myform.n1.value;
n2=document.myform.n2.value;
n1=parseFloat(n1);
n2=parseFloat(n2);
r=n1-n2;
document.myform.result.value=r;
}
function mul()
{
n1=document.myform.n1.value;
n2=document.myform.n2.value;
n1=parseFloat(n1);
n2=parseFloat(n2);
r=n1*n2;
document.myform.result.value=r;
}
function divide()
{
n1=document.myform.n1.value;
n2=document.myform.n2.value;
n1=parseFloat(n1);
n2=parseFloat(n2);
r=n1/n2;
document.myform.result.value=r;
}
</script> </head>
<body>
<form name="myform">
66
<h1 align="center"> Arithmatic Operations</h1>
<hr color="red">
<center><u>Enter a number in each text box </u><br><br>
Number 1:<input type="text" name="n1" value=""> <br><br>
Number 2:<input type="text" name="n2" value=""> <br><br>
<input type="button" value="Add" onClick="add()">
<input type="button" value="Subtract" onClick="sub()">
<input type="button" value="Multiply" onClick="mul()" >
<input type="button" value="Divide" onClick="divide()"><br><br>
<font color="red">Result is:
<input type="text" name="result" value=""></center></font>
</form>
</body>
</html>
Output:
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming
CS6501 - Internet programming

More Related Content

What's hot

What's hot (20)

CORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBACORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBA
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Subnetting (FLSM & VLSM) with examples
Subnetting (FLSM & VLSM) with examplesSubnetting (FLSM & VLSM) with examples
Subnetting (FLSM & VLSM) with examples
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Dot net assembly
Dot net assemblyDot net assembly
Dot net assembly
 
Soap web service
Soap web serviceSoap web service
Soap web service
 
JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 
Servicios web
Servicios webServicios web
Servicios web
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
5. phases of nlp
5. phases of nlp5. phases of nlp
5. phases of nlp
 
Servlet
Servlet Servlet
Servlet
 
Distributed Transaction
Distributed TransactionDistributed Transaction
Distributed Transaction
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
 
Top 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and AnswerTop 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and Answer
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological Parsing
 
2.1 & 2.2 grammar introduction – types of grammar
2.1 & 2.2 grammar introduction – types of grammar2.1 & 2.2 grammar introduction – types of grammar
2.1 & 2.2 grammar introduction – types of grammar
 
Web Service Presentation
Web Service PresentationWeb Service Presentation
Web Service Presentation
 
Web servers
Web serversWeb servers
Web servers
 
Web 3 | Bootstrap
Web 3 | BootstrapWeb 3 | Bootstrap
Web 3 | Bootstrap
 

Viewers also liked

Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1Mohammed Hussein
 
Cs6660 compiler design november december 2016 Answer key
Cs6660 compiler design november december 2016 Answer keyCs6660 compiler design november december 2016 Answer key
Cs6660 compiler design november december 2016 Answer keyappasami
 
Cs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer KeyCs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer Keyappasami
 
30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-ppt30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-pptraj732723
 

Viewers also liked (7)

Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1
 
Cs6660 compiler design november december 2016 Answer key
Cs6660 compiler design november december 2016 Answer keyCs6660 compiler design november december 2016 Answer key
Cs6660 compiler design november december 2016 Answer key
 
Cs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer KeyCs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer Key
 
30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-ppt30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-ppt
 
CS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMSCS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMS
 
CS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMSCS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMS
 
CS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMSCS6601 DISTRIBUTED SYSTEMS
CS6601 DISTRIBUTED SYSTEMS
 

Similar to CS6501 - Internet programming

Mean stack training-course-content
Mean stack training-course-contentMean stack training-course-content
Mean stack training-course-contentTraining Institute
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course JavaEE Trainers
 
Tcs Technical Question
Tcs Technical QuestionTcs Technical Question
Tcs Technical QuestionVinay Kumar
 
Exposing EJBs As Web Services
Exposing EJBs As Web ServicesExposing EJBs As Web Services
Exposing EJBs As Web ServicesSubin Sugunan
 
Automating the Use of Web APIs through Lightweight Semantics
Automating the Use of Web APIs through Lightweight SemanticsAutomating the Use of Web APIs through Lightweight Semantics
Automating the Use of Web APIs through Lightweight Semanticsmmaleshkova
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
Bt0083 server side programming-theory
Bt0083   server side programming-theoryBt0083   server side programming-theory
Bt0083 server side programming-theorysmumbahelp
 
Dot net interview questions
Dot net interview questionsDot net interview questions
Dot net interview questionsNetra Wable
 
.NET Difference Between Interview Questions - Compiled
.NET Difference Between Interview Questions - Compiled.NET Difference Between Interview Questions - Compiled
.NET Difference Between Interview Questions - CompiledUmar Ali
 
Core java and advance java syallabus - Cacit.co.in
Core java and advance java syallabus - Cacit.co.inCore java and advance java syallabus - Cacit.co.in
Core java and advance java syallabus - Cacit.co.incacitnoida
 
Mounika .net dev
Mounika .net devMounika .net dev
Mounika .net devSAI MOUNIKA
 
Service Oriented Architecture Updated Luqman
Service Oriented Architecture Updated  LuqmanService Oriented Architecture Updated  Luqman
Service Oriented Architecture Updated Luqmanguesteb791b
 
Dot net-course-curriculumn
Dot net-course-curriculumnDot net-course-curriculumn
Dot net-course-curriculumnAmit Sharma
 

Similar to CS6501 - Internet programming (20)

Dot net2+ questions
Dot net2+ questionsDot net2+ questions
Dot net2+ questions
 
Best interview questions
Best interview questionsBest interview questions
Best interview questions
 
Question bank
Question bankQuestion bank
Question bank
 
Mean stack training-course-content
Mean stack training-course-contentMean stack training-course-content
Mean stack training-course-content
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
Wt unit 6 ppts web services
Wt unit 6 ppts web servicesWt unit 6 ppts web services
Wt unit 6 ppts web services
 
Tcs Technical Question
Tcs Technical QuestionTcs Technical Question
Tcs Technical Question
 
Exposing EJBs As Web Services
Exposing EJBs As Web ServicesExposing EJBs As Web Services
Exposing EJBs As Web Services
 
Automating the Use of Web APIs through Lightweight Semantics
Automating the Use of Web APIs through Lightweight SemanticsAutomating the Use of Web APIs through Lightweight Semantics
Automating the Use of Web APIs through Lightweight Semantics
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Java programing brochure
Java programing  brochureJava programing  brochure
Java programing brochure
 
Bt0083 server side programming-theory
Bt0083   server side programming-theoryBt0083   server side programming-theory
Bt0083 server side programming-theory
 
Dot net training bangalore
Dot net training bangaloreDot net training bangalore
Dot net training bangalore
 
Dot net interview questions
Dot net interview questionsDot net interview questions
Dot net interview questions
 
.NET Difference Between Interview Questions - Compiled
.NET Difference Between Interview Questions - Compiled.NET Difference Between Interview Questions - Compiled
.NET Difference Between Interview Questions - Compiled
 
Core java and advance java syallabus - Cacit.co.in
Core java and advance java syallabus - Cacit.co.inCore java and advance java syallabus - Cacit.co.in
Core java and advance java syallabus - Cacit.co.in
 
Mounika .net dev
Mounika .net devMounika .net dev
Mounika .net dev
 
Pollock
PollockPollock
Pollock
 
Service Oriented Architecture Updated Luqman
Service Oriented Architecture Updated  LuqmanService Oriented Architecture Updated  Luqman
Service Oriented Architecture Updated Luqman
 
Dot net-course-curriculumn
Dot net-course-curriculumnDot net-course-curriculumn
Dot net-course-curriculumn
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 

CS6501 - Internet programming

  • 1. 1 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING IMPORTANT QUESTIONS & ANSWERS JUNE – NOV.2015 CS6501 – INTERNET PROGRAMMING Year/Sem : IV/VIII Branch : COMPUTER SCIENCE AND ENGINEERING Faculty : V.KARTHIK SYLLABUS CS6501 INTERNET PROGRAMMING LTPC/3104 OBJECTIVES: The student should be made to:  Learn Java Programming.  Understand different Internet Technologies.  Be exposed to java specific web services architecture. UNIT I JAVA PROGRAMMING An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets. UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 Web 2.0: Basics-RIA Rich Internet Applications - Collaborations tools - Understanding websites and web servers: Understanding Internet – Difference between websites and web server- Internet technologies Overview – Understanding the difference between internet and intranet; HTML and CSS: HTML 5.0 , XHTML, CSS 3. UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,- Regular Expressions- Exception Handling- Validation-Built-in objects-Event Handling- DHTML with JavaScript. Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions- Session Handling- Understanding Cookies- Installing and Configuring Apache Tomcat Web Server;- DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example - JSP: Understanding Java Server Pages-JSP Standard Tag Library (JSTL)-Creating HTML forms by embedding JSP code.
  • 2. 2 UNIT IV PHP and XML An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions-Connecting to Database – Using Cookies-Regular Expressions; XML: Basic XML- Document Type Definition-XML Schema DOM and Presenting XML, XML Parsers and Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM). UNIT V INTRODUCTION TO AJAX and WEB SERVICES AJAX: Ajax Client Server Architecture- XML Http Request Object-Call Back Methods; Web Services: Introduction- Java web services Basics – Creating, Publishing, Testing and Describing a Web services (WSDL)-Consuming a web service, Database Driven web service from an application – SOAP. TOTAL (L: 45+T: 15): 60 PERIODS OUTCOMES:  At the end of the course, the student should be able to:  Implement Java programs.  Create a basic website using HTML and Cascading Style Sheets.  Design and implement dynamic web page with validation using JavaScript objects and by applying different event handling mechanisms.  Design rich client presentation using AJAX.  Design and implement simple web page in PHP, and to present data in XML format.  Design and implement server side programs using Servlets and JSP. TEXT BOOKS: 1. Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to Program‖, Prentice Hall, 5th Edition, 2011. 2. Herbert Schildt, ―Java-The Complete Reference‖, Eighth Edition, Mc Graw Hill Professional,2011. REFERENCES: 1. Stephen Wynkoop and JohnBurke ―Running a Perfect Website‖, QUE,2nd Edition,1999. 2. Chris Bates, Web Programming – Building Intranet Applications, 3 rd Edition, Wiley Publications, 2009. 3. Jeffrey C and Jackson, ―Web Technologies A Computer Science Perspective‖, Pearson Education, 2011. 4. Gopalan N.P. and Akilandeswari J., ―Web Technology‖, Prentice Hall of India, 2011. 5. Paul Dietel and Harvey Deitel, ―Java How to Program‖,8 th Edition Prentice Hall of India. 6. Mahesh P. Matha, ―Core Java A Comprehensive Study‖, Prentice Hall of India, 2011. 7. Uttam K.Roy, ―Web Technologies‖, Oxford University Press, 2011.
  • 3. 3 SECTION B: QUESTIONS UNIT –I JAVA PROGRAMMING PART -A 1. What is a Class and Object? 2. What is final modifier? 3. What is meant by abstraction? 4. What are methods and how are they defined? 5. What is an Object and how do you allocate memory to it? 6. Explain the usage of Java packages. 7. What is method overloading and method overriding? 8.What is static variable and static method? 9. What is array? Give an example. 10.What is a package? 11.Explain working of Java Virtual Machine (JVM)? 12. What is meant by Inheritance and what are its advantages? 13. What are inner class and anonymous class? 14. What is an Interface? 15.What is interface and its use? 16. What are the types of Exceptions in Java 17. Whatis the difference between String and String Buffer? 18.What are different types of access modifiers (Access specifiers)? 19. What is multithreading? 20. What is an applets? PART -B 1. Explain in detail about operator in java with example? (16) 2. i) Discuss in detail the access specifiers available in Java.(8) ii)What is Array? How to declare array?Discuss the methods under array class. (8) 3. Explain Packages in detail with example. (16) 4. Explain the concept of inheritance and its types. (16) 5. Explain the different ways to handle exceptions in java. (16) 6.Explain in detail about Multithreading in java. (16)
  • 4. 4 UNIT –II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 PART-A 1. What are the necessities of using HTML forms? 2. Define HTML. 3. What do you understand about DOCTYPE in HTML? 4. What are the Hyperlink, Anchors and Link in the HTML? 5. How you define HTML Style Attribute in HTML? 6. HTML is case sensitive or not? 7. How to use form‘s action attribute and submit button in html? 8. How to use Line Break and Horizontal Line tags in HTML? 9. What are Style Sheets? 10. List down the ways of including style information in a document. 11. What are the style precedence rules when using multiple approaches? 12. Give the syntax to specify a characteristic in linked style sheet. 13. List down font characteristics permitted in style sheets. 14. How to toggle display an HTML element? 15. What is the HTML DOM? PART –B 1. Explain Basic internet protocols and HTTP message format?(16) 2. To create a web page that displays college information using various styles (16) 3. Explain XHTML Syntax and semantics with example.(16) 4. i)Design a HTML Form for aRailwaay Reservation System? (8) ii)Explain about different types of XHTML DTD(8) 5.i)Explain about internet and intranet with difference.(8) ii) Design a HTML document using relative positioning to nudge text to the left.(8)
  • 5. 5 UNIT –III CLIENT SIDE AND SERVER SIDE PROGRAMMING PART-A 1. How to create an Object in JavaScript? 2. What is the result of below given line of code in Java Script? 5+4+‖7‖ 3.What is undefined value means in JavaScript? 4. Which method is used to Clear an array using JavaScript? 5.What will be the Output of the following using JavaScript, document.Write(Math.Round(6.7)); 6.What should appear at the very end of your JavaScript? 7.What is a JSP and what is it used for? 8. What is difference between custom JSP tags and beans? 9. What are the implicit objects? 10. Compare Client side vs. server side scripting. 11. State the Servlet life cycle 12. What is JavaScript? 13. What is the purpose of cookies? 14. What are the steps needs to establish JDBC connectivity? 15. What is the difference between GET and POST method? 16. What is different between web server and application server? 17. What are different methods of session management in servlets? 18. What is difference between GenericServlet and HttpServlet? PART –B 1. Explain javascript variables and debuggers in detail (16) 2. Discuss JavaScript Array object in detail. (16) 3. Write java script to perform all arithmetic operation (16) 4. Explain DOM event handling in detail.(16) 5. Write java servlet programs to conduct online examination and to display student mark list available in a database (16)
  • 6. 6 UNIT-IV PHP and XML PART –A 1. Mention the rules of well-formed XML. 2. What is the DOM? 3. What is the XML DOM? 4. What is the XMLHttpRequest Object? 5. What is XSL-FO? 6. What is XSL-FO Documents? Explain XSL-FO Documents structure 7. What is XSL-FO Processors? 8. Explain XML Attributes with an example 9. XML Elements vs. Attributes. 10. What are the problems with using XML attributes? 11. What is XSLT? 12. What are the roles of XSLT? 13.What is XSLT? Explain its relationships with XSL 14.What is XSLT style sheet? 15.Discuss the role of XPATH 16.Explain the XSLT data model 17.Why the need for XHTML? 18.What is XQuery language? 19.Explain the Relation between RSS and XML 20. Define. DOM PART –B 1. Given an XSLT document and a source XML document explain the XSLT transformation process that produces a single result XML document. (16) 2.Write a program to display student information using XSLT in XML document (16) 3. i)Explain the role XML namespaces with an example.(8) (ii)Explain the feature of XML path.(8) 4. Explain the model view controller architecture pattern in detail. (16) 5. Write Programs using XML – Schema – XSLT/XSL (16)
  • 7. 7 UNIT V – INTRODUCTION TO AJAX and WEB SERVICES PART –A 1. What is DTD? Explain it with example. 2. What is AJAX? 3.What is a web service? 4.What is SOAP? 5. What is SOAP and how it will be utilized in web-components? 6. Explain about the role of XML in SOAP? 7.What are the elements which should be contained in SOAP message? 8. What is SOAP? 9. Explain web services architecture. 10. What is WSDL? 11. Differentiate between AJAX and Java Script 12. What are the advantages of AJAX ? 13. Define Web Service? 14. Brief few drawbacks of using GET and POST methods to communicate with the web service? 15. Differentiate between a SOA and a Web service? PART –B 1. Describe the significance and working of WSDL with an example(16) 2. Describe the major elements of SOAP (16) 3. Explain about AJAX Http Request Object (16) 4. Explain in details about Web Services Conceptual Architecture (16) 5. Write a program to run and implement the web service (16)
  • 8. 8 SECTION C: QUESTIONS AND ANSWER UNIT –I PART A 1. What is a Classand Object? Class is a template for a set of objects that share a common structureand a common behavior. Object is an instance of a class. It has state, behavior and identity. It isalso called as an instance of a class. 2. What is final modifier? The final modifier keyword makes that the programmer cannotchange the value anymore. The actual meaning depends on whether it isapplied to a class, a variable, or a method. final Classes- A final class cannot have subclasses. final Variables- A final variable cannot be changed once it is initialized. final Methods- A final method cannot be overridden by subclasses. 3. What is meant by abstraction? Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. It‘s the process of focusing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model 4. What are methods and how are they defined? Methods are functions that operate on instances of classesin which they are defined. Objects can communicate with each other usingmethods and can call methods in other classes. Method definition has fourparts. They are name of the method, type of object or primitive type themethod returns, a list of parameters and the body of the method. A method‘s signature is a combination of the first three parts mentionedabove. 5. What is an Object and how do you allocate memory to it? Object is an instance of a class and it is a software unit that combines astructured set of data with a set of operations for inspecting and manipulatingthat data. When an object is created using new operator, memory is allocated toit. 6. Explain the usage of Java packages. This is a way to organize files when a project consists of multiplemodules. It also helps resolve naming conflicts when different packages haveclasses with the same names. Packages access level also allows you toprotect data from being used by the non- authorized classes. 7. What is method overloading and method overriding? Method overloading: When a method in a class having the same methodname with different arguments is said to be method overloading. Methodoverriding: When a method in a class having the same method name withsame arguments is said to be method overriding.
  • 9. 9 8.What is static variable and static method? Static variable is a class variable which value remains constant for theentire class. Static method is the one which can be called with the class itself and can holdonly the static variables. 9. What is array? Give an example. An array is a group of like-typed variables that are referred to by a common name. Arrays ofany type can be created and may have one or more dimensions. A specific element in an arrayis accessed by its index. Arrays offer a convenient means of grouping related information. Syntax: array-var = new type[size];example:month_days = new int[12]; 10.What is a package? A package is a collection of classes and interfaces that provides ahigh-level layer of access protection and name space management. 11.Explain working of Java Virtual Machine (JVM)? JVM is an abstract computing machine like any other real computingmachine which first converts .java file into .class file by using Compiler (.class isnothing but byte code file.) and Interpreter reads byte codes 12. What is meant by Inheritance and what are its advantages? Inheritance is the process of inheriting all the features from a class.The advantages of inheritance are reusability of code and accessibility ofvariables and methods of the super class by subclasses. 13. What are inner class and anonymous class? Inner class: classes defined in other classes, includingthose defined in methods are called inner classes. An inner class canhave any accessibility including private. Anonymous class: Anonymousclass is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors 14. What is an Interface? Interface is an outside view of a class or object which emphasizes itsabstraction while hiding its structure and secrets of its behavior. 15.What is interface and its use? Interface is similar to a class which may contain method‘ssignature only but not bodies and it is a formal set of method and constantdeclarations that must be defined by the class that implements it.Interfaces are useful for: a) Declaring methods that one or moreclasses are expected to implement b) Capturing similarities betweenunrelated classes without forcing a class relationship. c) Determining anobject‘s programming interface without revealing the actual body of the class
  • 10. 10 16. What are the types of Exceptions in Java There are two types of exceptions in Java, unchecked exceptions andchecked exceptions. Checked exceptions: A checked exception is some subclass of Exception (orException itself), excluding class Runtime Exception and its subclasses. Eachmethod must either handle all checked exceptions by supplying a catchclause or list each unhandled checked exception as a thrown exception. Unchecked exceptions: All Exceptions that extend the Runtime Exceptionclass are unchecked exceptions. Class Error and its subclasses also areunchecked. 17. Whatis the difference between String and String Buffer? a) String objects are constants and immutable whereas String Buffer objects are not. b) String class supports constant strings whereas String Buffer class supports grow able and modifiablestrings. 18.What are different types of access modifiers (Access specifiers)? Access specifiers are keywords that determine the type of accessto the member of a class. These keywords are for allowingprivileges to parts of a program such as functions and variables. Theseare: Public: Anything declared as public can be accessed from anywhere. Private: Anything declared as private can‘t be seen outside of its class. Protected: Anything declared as protected can be accessed by classes inthe same package and subclasses in the other packages. Default modifier : Can be accessed only to classes in thesame package. 19. What is multithreading? Java provides built-in support for multithreadedprogramming. A multithreaded program contains two or more parts that can runconcurrently. Each part of such a program is called a thread, and each thread definesa separate path of execution. Thus, multithreading is a specialized form of multitasking. 20. What is an applets? Applets are small applications that are accessed on anInternet server, transported over the Internet, automatically installed, and run as part of a webdocument. After an applet arrives on the client, it has limited access to resources so that itcan produce a graphical user interface and run complex computations without introducingthe risk of viruses or breaching data integrity.
  • 11. 11 SECTION C: QUESTIONS & ANSWERS UNIT –I JAVA PROGRAMMING 1. Explain in detail about operator in java with example? (16) Java provides a rich operator environment. Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain special situations. Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Operator | Result: + Addition – Subtraction (also unary minus) * Multiplication / Division % Modulus ++ Increment += Addition assignment –= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment – – Decrement The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is,essentially, a subset of int. class BasicMath { public static void main(String args[]) { // arithmetic using integers System.out.println("Integer Arithmetic"); int a = 1 + 1; int b = a * 3; int c = b / 4; int d = c - a; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e);
  • 12. 12 The Bitwise Operators Java defines several bitwise operators that can be applied to the integer types, long, int, short,char, and byte. These operators act upon the individual bits of their operands. They aresummarized in the following table: The Bitwise Logical Operators The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each operation. The Bitwise OR The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the resultant bit is a 1, as shown here: The Bitwise XOR
  • 13. 13 // Demonstrate the bitwise logical operators. class BitLogic { public static void main(String args[]) { String binary[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" }; int a = 3; // 0 + 2 + 1 or 0011 in binary int b = 6; // 4 + 2 + 0 or 0110 in binary int c = a | b; int d = a & b; int e = a ^ b; int f = (~a & b) | (a & ~b); int g = ~a & 0x0f; System.out.println(" a = " + binary[a]); System.out.println(" b = " + binary[b]); System.out.println(" a|b = " + binary[c]); System.out.println(" a&b = " + binary[d]); System.out.println(" a^b = " + binary[e]); System.out.println("~a&b|a&~b = " + binary[f]); System.out.println(" ~a = " + binary[g]); } } output from this program: a = 0011 b = 0110 a|b = 0111 a&b = 0010 a^b = 0101 ~a&b|a&~b = 0101 ~a = 1100 Relational Operators The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are shown here:
  • 14. 14 Example: int a = 4; int b = 1; boolean c = a < b; Boolean Logical Operators The Boolean logical operators shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value. The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and !false == true. The following table shows the effect of each logical operation: // Demonstrate the boolean logical operators. class BoolLogic { public static void main(String args[]) { boolean a = true; boolean b = false; boolean c = a | b; boolean d = a & b; boolean e = a ^ b; boolean f = (!a & b) | (a & !b); boolean g = !a; System.out.println(" a = " + a);
  • 15. 15 System.out.println(" b = " + b); System.out.println(" a|b = " + c); System.out.println(" a&b = " + d); System.out.println(" a^b = " + e); System.out.println("!a&b|a&!b = " + f); System.out.println(" !a = " + g); } } O/P: a = true b = false a|b = true a&b = false a^b = true a&b|a&!b = true !a = false The Assignment Operator The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does in any other computer language. It has this general form: var = expression; Here, the type of var must be compatible with the type of expression. For example, int x, y, z; x = y = z = 100; // set x, y, and z to 100 The ? Operator Ternary (three-way) operator that can replace certain types of if-then-else Statements .The ? has this general form: expression1? expression2:expression3 Here, expression1 can be any expression that evaluates to a boolean value. If expression1 istrue, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?operation is that of the expression evaluated. Both expression2 and expression3 are requiredto return the same type, which can‘t be void. Example: ratio = denom == 0 ? 0 : num / denom;
  • 16. 16 2. i) Discuss in detail the access specifiers available in Java.(8) ii)What is Array? How to declare array?Discuss the methods under array class. (8) i) Discuss in detail the access specifiers available in Java.(8) Java‘s four level of access protection:  Public  Private  Protected  Default Some aspects of access control are related mostly to inheritance or package. (A package is,essentially, a grouping of classes) protected is applied only when inheritance is invoked. : Public Access: When a member of a class is modified by public specifier, then that member can be accessed by any other code. Now you can understand why main () has always been preceded by the public specifier.it is called by code that is outside the program that is by java run time system Private Access: when a member of class is specified as private, then that member can only be accessed by other members of its class. protected: Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it. Default Access: when no specifier is used then by default the member of class is public within its own package, but cannot be accessed outside of its package.in the classes development so far ,all members of a class have use the default access mode .which is essentially public. This access specifier is also known as friendly access. table showing all the access specifiers and theiraccessibility in the class, package, subclasses andother packages.
  • 17. 17 Example of public & private /* Program to demonstrate Access Protection */ class Demo { int p; // default access public int q; // public access private int r; // private access // methods to access r void setr(int i) { // set r's value r = i; } int getr() { // get r's value return r; } } class AccessProDemo { public static void main(String args[]) { Demo d= new Demo(); // OK : 'p' and 'q' may be accessed directly d.p=300; d.q=400; // NOT OK : 'r' cannot be accessed outside the class, hence will cause an error // d.r=50; // You must access 'r' through its methods d.setr(500); //OK System.out.println(" p, q, and r = "+d.p+", "+d.q+", and "+d.getr()); } } o/p:- P, q, and r =300,400, and 500
  • 18. 18 2.ii) What is Array? How to declare array?Discuss the methods under array class. An array is a data structure that stores a collection of values of the same type. You access each individualvalue through an integer index. Array Name [index] Integer constant, variable, or expression For Instance we can define an array name salary to represent a set of salaries of a group of employees. Aparticular value is indicated by writing a number called index in brackets after the array name. salary [10] it represents the salary of the 10th employee. Types of arrays One dimensional arrays Two dimensional arrays One Dimensional arrays A list of items can be given one variable name using only one subscript and such a variable iscalled single - subscripted of one dimensional array. The subscript can also start from 0. ie x[0]. If we want to represent a set of five numbers, say (35,40,20,57,19) by an array variable number,then we have to create the variable number as follows int number [ ] = new int [5 ]; The value to the array elements can be assigned as follows Number[0] =35; Number [1] =40; Number [2] =20; Number [3] =57; Number [4] =19; This would cause the array number to store the values shown as follows; Creating an array Declaring the array Creating memory locations Putting values into the memory locations. Declaring the Array Array in java can be declared in two forms Form 1 type arrayname [ ]; Form 2 type [ ] arrayname; Creation of arrays arrayname = new type [ size ]; Eg; number = new int [5] ; average = new float[10]; it is also possible to combine declaration and creation. int number [ ] = new int [5]; Initialization of arrays
  • 19. 19 The final step is to put values into the array created. This process is known as initialization usingthe array subscripts as shown below. arrayname[subscript] = value ; Eg number[0] = 15; we can also initialize by following way typearrayname [ ] = { list of values } Array Length All array store the allocated size in an variable named length. We can obtain the length of array ausing a.length Eg: intasize = a.length; Sample Code for array manipulation Two Dimensional arrary: Usage :intmyArray [ ] [ ]; myArray= new int [3] [4]; or initmyArray [ ] [ ] = new int [3][4] This creates a table that can store 12 integer values, four across and three down. Strings: Series of characters represents a string, and easiest way to represent the string is array Eg: Char charArray [ ] = new char [2] ; charArray[0] = „j‟ ; charArray[1] = „a‟ ; String can be declared and created in the following way string stringname; stringname = new string (―string‖); Operations on string int m = stringname.length() //will return the length of the string string city = ―New‖ + ―Delhi‖// will return New Delhi ,string concatenating Sample Code forstring Manipulation 3. Explain Packages in detail with example. (16) Packages are java‟s way of grouping a variety of classes and/or interfaces together. Packages are container for the classes. It is stored in a hierarichical manner. If we want to use the packages in a class, we want to import it. The two types of packages are: 1. System package. 2. User defined package. Uses of Packages: Packages reduce the complexity of the software because a large number of classes can be grouped into a limited number of packages.
  • 20. 20 We can create classes with same name in different packages. Using packages we can hide classes. We may like to use many of the classes contained in a package.it can be achieved by Import packagename .classname Or Import packagename.* Creating the package To create our own packages packagefirstpackage;// package declaration public class FirstClass //class definition {..... (body of class) .......} The file is saved as FirstClass.java,located at firstpackage directory. when it is compiled .class file will be created in same ditectory. Access a package The import statement can be used to search a list of packages for a particular class. The general form of import statement for searching class is a as follows. Import package1 [.package2] [.package3].classname; Using the package package package1 ; public class classA { public void displayA() { System.out.println(―class A‖); } } Adding a class to package Define the class and make it public Place the package statement Package P1 Before the class definition as follows Package p1; Public class B Package name { // body of B } Example: Package college Class student {
  • 21. 21 intregno; String name; Student(intr,stringna); { Regno=r Name=na } Public void print() { System.out.println(―Regno‖+regno ); System.out.println(―Name‖+name ); } } Package Course Class engineering { Intregno; String branch; String year; Engineering(int r, string br, string yr) { Regno=br; Branch=br; Year=yr; } public void print() { Systems.out.println(―Regno‖+regno); Systems.out.println(― Branch‖+branch); Systems.out.println(―Year‖+year); } } import college.*; import course.*; Class demo { Public static void main(string args[]) { Student sl=new Engineering(1,‖CSE‖,‖III Year‖); Sl.print(); El.print(); } }
  • 22. 22 4. Explain the concept of inheritance and its types. (16) There exist basically three types of inheritance.  Multilevel inheritance  Multiple inheritance  Hierarchical inheritance 1. In single inheritance, one class extends one class only. In multilevel inheritance, the ladder of single inheritance increases. 2. In multiple inheritance, one class directly extends more than one class. 3. In hierarchical inheritance one class is extended by more than one class. 1. Single Inheritance When a single derived class is created from a single base class then the inheritance is called as single inheritance. 1. Multilevel Inheritance In multilevel, one-to-one ladder increases. Multiple classes are involved in inheritance, but one class extends only one. The lowermost subclass can make use of all its super classes' members. Multilevel inheritance is an indirect way of implementing multiple inheritance. Following program explains. class Aves { public void nature() { System.out.println("Generally, Aves fly"); } } class Bird extends Aves { public void eat() { System.out.println("Eats to live"); } }
  • 23. 23 public class Parrot extends Bird { public void food() { System.out.println("Parrot eats seeds and fruits"); } public static void main(String args[]) { Parrot p1 = new Parrot(); p1.food(); // calling its own p1.eat(); // calling super class Bird method p1.nature(); // calling super class Aves method } } Now, Parrot has two super classes Bird and Aves; but extended one-to-one. Parrot can make use of the methods of Bird and Aves. Bird can make use of the methods of Aves, but Parrot as a super class cannot access subclass members. Following figure gives a schematic representation of the multilevel hierarchy with the classes involved in the program. 2. Multiple Inheritance In multiple inheritance, one class extends multiple classes. Java does not support multiple inheritance but C++ supports. The above program can be modified to illustrate multiple inheritance. The following program does not work. calss Aves { } class Bird { }
  • 24. 24 publicclass Parrot extends Aves, Bird { } In the above code, Parrot extends both Aves and Bird. This is not supported by Java and the above code raises compilation error. Following is the schematic representation. Note: Java supports multiple inheritance partially through interfaces. 3. Hierarchical Inheritance In hierarchical type of inheritance, one class is extended by many subclasses. It is one- to-many relationship. A realtime example is available at dynamic binding. class Aves { publicvoid fly() { System.out.println("Generally, aves fly"); } } class Parrot extends Aves { publicvoid eat() { System.out.println("Parrot eats fruits and seeds"); } } class Vulture extends Aves { publicvoid vision() { System.out.println("Vulture can see from high altitudes"); } } publicclass FlyingCreatures { publicstaticvoid main(String args[]) { // all the following code is composition for FlyingCreatures Parrot p1 = new Parrot(); p1.eat(); // calling its own member p1.fly();
  • 25. 25 // calling super class member by inheritance Vulture v1 = new Vulture(); v1.vision(); // calling its own member v1.fly(); // calling super class member by inheritance }} Output screen of FlyingCreatures.java In the above code, Aves class is extended by two classes – Parrot and Vulture. Both classes can make use of the methods of Aves. Even though the Parrot and Vulture are subclasses of the same class Aves, but still they cannot make use of each other members. Parrot and Vulture are known as "siblings". Siblings are disjoint and they cannot make use of other members as between them no inheritance is involved (like two sons of a father; one son's property cannot be shared by other but both can share the property of father). Following is the schematic representation of the classes involved. Dynamic binding and dynamic polymorphism use hierarchical inheritance. Disadvantages of Inheritance 1. Both classes (super and subclasses) are tightly-coupled. 2. As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other. 3. Changing the code in super class method also affects the subclass functionality. 4. If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently.
  • 26. 26 5. Explain the different ways to handle exceptions in java. (16) An exception is a problem that arises during the execution of a program. An exception can occur formany different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out ofmemory. Some of these exceptions are caused by user error, others by programmer error, and others byphysical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories ofexceptions: Checked exceptions: A checked exception is an exception that is typically a user error or aproblem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignoredat the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely doanything about an error. For example, if a stack overflow occurs, an error will arise. They are alsoignored at the time of compilation. Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is asubclass of the Throwable class. Other than the exception class there is another subclass calledError which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case ofsevere failures, which are not handled by the java programs. Errors are generated to indicate errorsgenerated by the runtime environment. Example : JVM is out of Memory. Normally programs cannotrecover from errors. The Exception class has two main subclasses: IOException class and RuntimeException Class.
  • 27. 27 Here is a list of most common checked and unchecked Java's Built-in Exceptions. Exceptions Methods: Following is the list of important medthods available in the Throwable class. Methods with Description 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message isinitialized in the Throwable constructor. 2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 3 public String toString() Returns the name of the class concatenated with the result of getMessage() 4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error outputstream. 5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0represents the top of the call stack, and the last element in the array represents themethod at the bottom of the call stack. 6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to anyprevious information in the stack trace. Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catchblock is placed around the code that might generate an exception. Code within a try/catch block isreferred to as protected code, and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block
  • 28. 28 } A catch statement involves declaring the type of exception you are trying to catch. If an exceptionoccurs in protected code, the catch block (or blocks) that follows the try is checked. If the type ofexception that occurred is listed in a catch block, the exception is passed to the catch block muchas an argument is passed into a method parameter. Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd elementof the array which throws an exception. // File Name : ExcepTest.java import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } This would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks likethe following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of themafter a single try. If an exception occurs in the protected code, the exception is thrown to the firstcatch block in the list. If the data type of the exception thrown matches ExceptionType1, it getscaught there. If not, the exception passes down to the second catch statement. This continuesuntil the exception either is caught or falls through all
  • 29. 29 catches, in which case the current methodstops execution and the exception is thrown down to the previous method on the call stack. Example: Here is code segment showing how to use multiple try/catch statements. try { file = new FileInputStream(fileName); x = (byte) file.read(); }catch(IOException i) { i.printStackTrace(); return -1; }catch(FileNotFoundException f) //Not valid! { f.printStackTrace(); return -1; } The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throwskeyword. throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, byusing the throw keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException: import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition } A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws aRemoteException and an InsufficientFundsException: import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation }
  • 30. 30 //Remainder of class definition } The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of codealways executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, nomatter what happens in the protected code.A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. } Example: public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } } This would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Note the following:
  • 31. 31 A catch clause cannot exist without a try statement.It is not compulsory to have finally clauses when ever a try/catch block is present.The try block cannot be present without either catch clause or finally clause.Any code cannot be present in between the try, catch, finally blocks. Declaring you own Exception: You can create your own exceptions in Java. Keep the following points in mind when writing your ownexception classes: All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a userdefinedexception that extends the Exception class, making it a checked exception. An exceptionclass is like any other class, containing useful fields and methods. Example: // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } To demonstrate using our user-defined exception, the following CheckingAccount class contains awithdraw() method that throws an InsufficientFundsException. // File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; }
  • 32. 32 public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods ofCheckingAccount. // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("nWithdrawing $100..."); c.withdraw(100.00); System.out.println("nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount());
  • 33. 33 e.printStackTrace(); } } } Compile all the above three files and run BankDemo, this would produce the following result: Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13) Common Exceptions: In Java, it is possible to define two catergories of Exceptions and Errors. JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM.Examples:NullPointerException,ArrayIndexOutOfBoundsException, ClassCastException, Programmatic exceptions: - These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException 6.Explain in detail about Multithreading in java. (16) Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates, because idle time is common. For example, the transmission rate of data over a network is much slower than the rate at which the computer can process it. Even local file system resources are read and written at a much slower pace than they can be processed by the CPU. And, of course, user input is much slower than the computer The Thread Class and the Runnable Interface Java‘s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. Since you can‘t directly refer to the ethereal state of a running thread, you will deal with it through its proxy, the Thread instance that spawned it. To create a new thread, your program will either extend Thread or implement the Runnable interface. The Thread class defines several methods that help manage threads. The ones that will be used in this chapter are shown here:
  • 34. 34 The Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons: • It is the thread from which other ―child‖ threads will be spawned. • Often, it must be the last thread to finish execution because it performs various shutdown actions. Creating a Thread In the most general sense, you create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished: • You can implement the Runnable interface. • You can extend the Thread class, itself. The following two sections look at each method, in turn. Implementing Runnable The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) Inside run( ), you will define the code that constitutes the new thread. It is important to understand that run( ) can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run( ) returns. Here is an example that creates a new thread and starts it running: // Create a second thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() {
  • 35. 35 try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Inside NewThread‘s constructor, a new Thread object is created by the following statement: t = new Thread(this, "Demo Thread"); o/p: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.
  • 36. 36 Creating Multiple Threads So far, you have been using only two threads: the main thread and one child thread. However, your program can spawn as many threads as it needs. For example, the following program creates three child threads: // Create multiple threads. class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } } class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); try { // wait for other threads to end Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } } The output from this program is shown here: New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] One: 5
  • 37. 37 Two: 5 Three: 5 One: 4 Two: 4 Three: 4 One: 3 Three: 3 Two: 3 One: 2 Three: 2 Two: 2 One: 1 Three: 1 Two: 1 One exiting. Two exiting. Three exiting. Main thread exiting.
  • 38. 38 UNIT –II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 PART-A: 1. What are the necessities of using HTML forms? Gathering user information Conducting Surveys Interactive services 2. Define HTML. It is a simple page description language, which enables document creation for the web. 3. What do you understand about DOCTYPE in HTML? A Document Type Declaration, or DOCTYPE, is an instruction that associates a particular SGML or XML document (for example, a web page) with a Document Type Definition(DTD) (for example, the formal definition of a particular version of HTML). It manifests as a short string of markup that conforms to a particular syntax. 4. What are the Hyperlink, Anchors and Link in the HTML? The <a> tag can be used in two ways: 1.To create a link to another document, by using the href attribute 2.To create a bookmark inside a document, by using the name attribute <a href="url">Link text</a> - The href attribute specifies the destination of a link. 5. How you define HTML Style Attribute in HTML? The <style> tag is used to define style information for an HTML document. Inside the style element you specify how HTML elements should render in a browser. The required type attribute defines the content of the style element. The only possible value is "text/css". The style element always goes inside the head section. <head> <styletype="text/css"> h1 {color:red}</style> </head> 6. HTML is case sensitive or not? Html is not a case sensitive language. <P> means the same as <p>.But a combination of upper and lower case letters must not be used. 7. How to use form’s action attribute and submit button in html? The required action attribute specifies where to send the form-data when a form is submitted. <form action="form_action.asp" method="get"> ,, </form> <input type="submit" /> defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. <input type="submit" value="Submit" /> 8. How to use Line Break and Horizontal Line tags in HTML? The <br> tag inserts a single line break. It‘s a empty tag, i.e. it has no end tag. The <hr> tag creates a horizontal line in the html page, and can be used to separate the contents in a html page. It is also an empty tag with no empty tag.
  • 39. 39 9. What are Style Sheets? CSS stands for Cascading Style Sheets. Styles define how to display HTML elements. Styles were added to HTML 4.0 to solve a problem. External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files. 10. List down the ways of including style information in a document. There are three main ways to include styles into a document namely, external style sheets, embedded style sheets and inline styles. 11. What are the style precedence rules when using multiple approaches? Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:  Browser default  External style sheet  Internal style sheet (in the head section)  Inline style (inside an HTML element) So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a default value). 12. Give the syntax to specify a characteristic in linked style sheet. {Characteristic:Value;} Multiple Characteristic/Values should be separated by semicolons. 13. List down font characteristics permitted in style sheets. Font – family, font – size, font – weight, font- style and font – variant. 14. How to toggle display an HTML element? An element in HTML can be toggle displayed using the style. Display parameter inside a separate toggle function. 15. What is the HTML DOM? The HTML DOM is: A standard object model for HTML A standard programming interface for HTML Platform- and language-independent A W3C standard The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to access them.
  • 40. 40 UNIT-II PART -B 1. Explain Basic internet protocols and HTTP message format?(16) Internet Protocol: The Internet protocols are the world‘s most popular open-system (nonproprietary) protocol suite because they can be used to communicate across any set of interconnected networks and are equally well suited for LAN and WAN communications. The Internet protocols consist of a suite of communication protocols, of which the two best known are the Transmission Control Protocol (TCP) and the Internet Protocol (IP). The Internet protocol suite not only includes lower-layer protocols (such as TCP and IP), but it also specifies common applications such as electronic mail, terminal emulation, and file transfer. Internet protocols were first developed in the mid-1970s, when the Defense Advanced Research Projects Agency (DARPA) became interested in establishing a packet-switched network that would facilitate communication between dissimilar computer systems at research institutions. With the goal of heterogeneous connectivity in mind, DARPA funded research by Stanford University and Bolt, Beranek, and Newman (BBN). The result of this development effort was the Internet protocol suite, completed in the late 1970s. TCP/IP later was included with Berkeley Software Distribution (BSD) UNIX and has since become the foundation on which the Internet and the World Wide Web (WWW) are based
  • 41. 41 Internet Protocol (IP) The Internet Protocol (IP) is a network-layer (Layer 3) protocol that contains addressing information and some control information that enables packets to be routed. IP is documented in RFC 791 and is the primary network-layer protocol in the Internet protocol suite. Along with the Transmission Control Protocol (TCP), IP represents the heart of the Internet protocols. IP has two primary responsibilities: providing connectionless, best-effort delivery of datagram‘s through an internetwork; and providing fragmentation and reassembly of datagrams to support data links with different maximum-transmission unit (MTU) sizes. IP Packet Format An IP packet contains several types of information, as illustrated in Figure 30-2. The following discussion describes the IP packet fields illustrated in Figure 30-2: • Version—Indicates the version of IP currently used. • IP Header Length (IHL)—Indicates the datagram header length in 32-bit words. • Type-of-Service—Specifies how an upper-layer protocol would like a current datagram to be handled, and assigns datagrams various levels of importance. • Total Length—Specifies the length, in bytes, of the entire IP packet, including the data and header. • Identification—Contains an integer that identifies the current datagram. This field is used to help piece together datagram fragments. • Flags—Consists of a 3-bit field of which the two low-order (least-significant) bits control fragmentation. The low-order bit specifies whether the packet can be fragmented. The middle bit specifies whether the packet is the last fragment in a series of fragmented packets. The third or high-order bit is not used. • Fragment Offset—Indicates the position of the fragment‘s data relative to the beginning of the data in the original datagram, which allows the destination IP process to properly reconstruct the original datagram.
  • 42. 42 • Time-to-Live—Maintains a counter that gradually decrements down to zero, at which point the datagram is discarded. This keeps packets from looping endlessly. • Protocol—Indicates which upper-layer protocol receives incoming packets after IP processing is complete. • Header Checksum—Helps ensure IP header integrity. • Source Address—Specifies the sending node. • Destination Address—Specifies the receiving node. •Options—Allows IP to support various options, such as security. •Data—Contains upper-layer information HTTP message format: HyperText Transfer Protocol (HTTP) HTTP (Hypertext Transfer Protocol) is perhaps the most popular application protocol used in the Internet (or The WEB). HTTP is an asymmetric request-response client-server protocol as illustrated. An HTTP client sends a request message to an HTTP server. The server, in turn, returns a response message. In other words, HTTP is a pull protocol, the client pulls information from the server (instead of server pushes information down to the client).  HTTP is a stateless protocol. In other words, the current request does not know what has been done in the previous requests.  HTTP permits negotiating of data type and representation, so as to allow systems to be built independently of the data being transferred.  Quoting from the RFC2616: "The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. It is a generic, stateless, protocol which can be used for many tasks beyond its use for hypertext, such as name servers and distributed object management systems, through extension of its request methods, error codes and headers."
  • 43. 43 HTTP Request and Response Messages HTTP client and server communicate by sending text messages. The client sends a request message to the server. The server, in turn, returns a response message. An HTTP message consists of a message header and an optional message body, separated by a blank line, as illustrated below: HTTP Request Message The format of an HTTP request message is as follow: Request Line The first line of the header is called the request line, followed by optional request headers. The request line has the following syntax: request-method-name request-URI HTTP-version
  • 44. 44  request-method-name: HTTP protocol defines a set of request methods, e.g., GET, POST, HEAD, and OPTIONS. The client can use one of these methods to send a request to the server.  request-URI: specifies the resource requested.  HTTP-version: Two versions are currently in use: HTTP/1.0 and HTTP/1.1. Examples of request line are: GET /test.html HTTP/1.1 HEAD /query.html HTTP/1.0 POST /index.html HTTP/1.1 Request Headers The request headers are in the form of name:value pairs. Multiple values, separated by commas, can be specified. request-header-name: request-header-value1, request-header-value2, ... Examples of request headers are: Host: www.xyz.com Connection: Keep-Alive Accept: image/gif, image/jpeg, */* Accept-Language: us-en, fr, cn Example The following shows a sample HTTP request message: HTTP Response Message The format of the HTTP response message is as follows:
  • 45. 45 Status Line The first line is called the status line, followed by optional response header(s). The status line has the following syntax: HTTP-version status-code reason-phrase  HTTP-version: The HTTP version used in this session. Either HTTP/1.0 and HTTP/1.1.  status-code: a 3-digit number generated by the server to reflect the outcome of the request.  reason-phrase: gives a short explanation to the status code.  Common status code and reason phrase are "200 OK", "404 Not Found", "403 Forbidden", "500 Internal Server Error". Examples of status line are: HTTP/1.1 200 OK HTTP/1.0 404 Not Found HTTP/1.1 403 Forbidden Response Headers The response headers are in the form name:value pairs: response-header-name: response-header-value1, response-header-value2, ... Examples of response headers are: Content-Type: text/html Content-Length: 35 Connection: Keep-Alive Keep-Alive: timeout=15, max=100 The response message body contains the resource data requested. Example The following shows a sample response message: HTTP Request Methods HTTP protocol defines a set of request methods. A client can use one of these request methods to send a request message to an HTTP server. The methods are:  GET: A client can use the GET request to get a web resource from the server.  HEAD: A client can use the HEAD request to get the header that a GET request would have obtained. Since the header contains the last-modified date of the data, this can be used to check against the local cache copy.  POST: Used to post data up to the web server.
  • 46. 46  PUT: Ask the server to store the data.  DELETE: Ask the server to delete the data.  TRACE: Ask the server to return a diagnostic trace of the actions it takes.  OPTIONS: Ask the server to return the list of request methods it supports.  CONNECT: Used to tell a proxy to make a connection to another host and simply reply the content, without attempting to parse or cache it. This is often used to make SSL connection through the proxy.  Other extension methods. "GET" Request Method GET is the most common HTTP request method. A client can use the GET request method to request (or "get") for a piece of resource from an HTTP server. A GET request message takes the following syntax: GET request-URI HTTP-version (optional request headers) (blank line) (optional request body)  The keyword GET is case sensitive and must be in uppercase.  request-URI: specifies the path of resource requested, which must begin from the root "/" of the document base directory.  HTTP-version: Either HTTP/1.0 or HTTP/1.1. This client negotiates the protocol to be used for the current session. For example, the client may request to use HTTP/1.1. If the server does not support HTTP/1.1, it may inform the client in the response to use HTTP/1.0.  The client uses the optional request headers (such as Accept, Accept-Language, and etc) to negotiate with the server and ask the server to deliver the preferred contents (e.g., in the language that the client preferred).  GET request message has an optional request body which contains the query string (to be explained later). Response Status Code The first line of the response message (i.e., the status line) contains the response status code, which is generated by the server to indicate the outcome of the request. The status code is a 3-digit number:  1xx (Informational): Request received, server is continuing the process.  2xx (Success): The request was successfully received, understood, accepted and serviced.  3xx (Redirection): Further action must be taken in order to complete the request.  4xx (Client Error): The request contains bad syntax or cannot be understood.  5xx (Server Error): The server failed to fulfill an apparently valid request. Some commonly encountered status codes are:  100 Continue: The server received the request and in the process of giving the response.  200 OK: The request is fulfilled.  301 Move Permanently: The resource requested for has been permanently moved to a new location. The URL of the new location is given in the response header
  • 47. 47 called Location. The client should issue a new request to the new location. Application should update all references to this new location.  302 Found & Redirect (or Move Temporarily): Same as 301, but the new location is temporarily in nature. The client should issue a new request, but applications need not update the references.  304 Not Modified: In response to the If-Modified-Since conditional GET request, the server notifies that the resource requested has not been modified.  400 Bad Request: Server could not interpret or understand the request, probably syntax error in the request message.  401 Authentication Required: The requested resource is protected, and require client‘s credential (username/password). The client should re-submit the request with his credential (username/password).  403 Forbidden: Server refuses to supply the resource, regardless of identity of client.  404 Not Found: The requested resource cannot be found in the server.  405 Method Not Allowed: The request method used, e.g., POST, PUT, DELETE, is a valid method. However, the server does not allow that method for the resource requested.  408 Request Timeout:  414 Request URI too Large:  500 Internal Server Error: Server is confused, often caused by an error in the server-side program responding to the request.  501 Method Not Implemented: The request method used is invalid (could be caused by a typing error, e.g., "GET" misspell as "Get").  502 Bad Gateway: Proxy or Gateway indicates that it receives a bad response from the upstream server.  503 Service Unavailable: Server cannot response due to overloading or maintenance. The client can try again later.  504 Gateway Timeout: Proxy or Gateway indicates that it receives a timeout from an upstream server.
  • 48. 48 2. To create a web page that displays college information using various styles HTML CODE: <html> <head><h1><center>ALL STYLE SHEETS</center></h1> <title>USE of INTERNAL and EXTERNAL STYLESHEETS </title> <link rel="stylesheet" href="xyz.css" type="text/css"> <style type="text/css"> .vid{font-family:verdana;font-style:italic;color:red;text-align:center} .ani{font-family:tahoma;font-style:italic;font-size:20;text-align:center;} font{font-family:georgia;color:blue;font-size:20} ul{list-style-type:circle} </style> </head> <body> <ol style="list-style-type:lower-alpha"> <b>PERI GROUP OF COLLEGES</b><br><br><br> <li>Raj Engineering College <li>PERI University and Research Institute <li> College of Engineering, Bangalore <li>Tamilnadu College of Arts and Science </ol> <p style="font-size:20pt;color:purple">A.C.S GROUP OF COLLEGES</p> <p class="ani">CSS Group of colleges is owned by XXX.<br>It is approved by International Council It is affliated to JKK University.<br></p> <h2 class="vid">DES College of Engg</h2> <br> <font>It is an ISO certified Institution</font><br> <br> <font> <h2>List of Courses offered</h2> <ul> <li>Computer Science and Engineering</li> <li>Ece</li> <li>mech</li> <li>eee</li> </ul> </font> <h3>Results of cse students</h3> <table width="100%" cellspacing="2" cellpadding="2" border="5">
  • 49. 49 <tr> <th>S.NAME</th> <th>MARKS</th> <th>RESULT</th> </tr> <tr> <td align="center">Dinesh</td> <td align="center">100</td> <td align="center">pass</td> </tr> <tr> <td align="center">Bala</td> <td align="center">99</td> <td align="center">pass</td> </tr> <tr> <td align="center">Gopi</td> <td align="center">98</td> <td align="center">pass</td> </tr> </table> </body> </html> XYZ.CSS: h3{font-family:arial;font-size:20;color:cyan} table{border-color:green} td{font-size:20pt;color:magenta}
  • 50. 50 3. Explain XHTML Syntax and semantics with example.(16) XHTML – EXtensible HyperText Markup Language  is HTML defined as an XML application  is a stricter and cleaner HTML  is compatible to HTML 4.01 and supported by all browsers  is a W3C recommendation Why XHTML ? the following, ―bad‖ html document will work fine in most browser even if it does not follow HTML rules: <html> <head> <body> <p>a paragraph…<br> <a href=―#‖>test </html>  but browsers running on hand-held devices (e.g. mobile phones) have small computing power and can not interpret ―bad‖ markup language  HTML is designed to structure (and display) data and XML is designed to describe and structure data  XHTML specifies that everything must be marked up correctly  XHTML – base syntactic rules  XHTML elements must be properly nested <b><i> Italic and bold text </b></i> <b><i> Italic and bold text </i></b>  XHTML elements must always be closed <p> A paragraph… <br> <img src=―foo.jpg‖> <p> A paragraph…</p> <br /> <img src=―foo.jpg‖ />  XHTML elements must be in lowercase  XHTML elements must have one <html> root element (which contains a <head> and a <body>) XHTML – other syntactic rules  attribute names must be in lower case  attribute values must be quoted <table width=300px> <table width=―300px‖>  the ―id‖ attribute replaces the ―name‖ attribute  XHTML DTD defines mandatory elements  attribute minimization is forbidden <input checked>
  • 51. 51 <input disabled> <input checked=―checked‖ /> <input disabled=―disabled‖ /> General format of an XHTML document <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>…</title> </head> <body> … </body> </html> <!Doctype>,<html>,<head>,<title>,<body> are mandatory DTD – Document Type Definition  a DTD specifies the syntax of a document written in a SGML language (HTML, XHTML, XML) it specifies: o the hierarchical structure of the document, o element names and types o element content type o and attributes names and values o XML 1.0 has 3 DTDs: Strict, Transitional and Frameset DTD example (internal to XHTML file) <!DOCTYPE course [ <!ELEMENT course (lecture+)> <!ELEMENT lecture (title,bibliography,notes,examples)> <!ELEMENT title (#PCDATA)> <!ELEMENT bibliography (#PCDATA)> <!ELEMENT notes (#PCDATA)> <!ELEMENT examples (#PCDATA)> <!ATTLIST course professor CDATA #REQUIRED> <!ATTLIST course title CDATA #REQUIRED> <!ATTLIST course yearofstudy CDATA #REQUIRED> <!ATTLIST course date CDATA #IMPLIED> ]> XHTML validation  a valid XHTML document is an XHTML document which obeys the rules of the DTD specified by the <!Doctype> tag.  the official W3C XHTML validator:  http://validator.w3.org/check/referer  XHTML DTD is split in 28 modules
  • 52. 52 3. i)Design a HTML Form for aRailwaay Reservation System? (8) ii)Explain about different types of XHTML DTD(8) Design a HTML Form for aRailwaay Reservation System? <FOTRM METHOD=º Postº ACTION=http://server name/directory name/Script name><HR> PASSENGER NAME: <INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR> ADDRESS: <INPUT TYPE=º Textº Name=º addº MAXLENGTH=º 24º <BR> CITY: <INPUT TYPE=º Textº Name=º cityº MAXLENGTH=º 24º <BR> STATE: <INPUT TYPE=º Textº Name=º stateº MAXLENGTH=º 24º ZIP: <INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR> </HR> <INPUT TYPE=º submitº value=º reserveº ></FORM> ii)Explain about different types of XHTML DTD(8) Document Type Definitions (DTD) A DTD specifies the syntax of a web page in SGML DTDs are used by SGML applications, such as HTML, to specify rules for documents of a particular type, including a set of elements and entity declarations An XHTML DTD describes in precise, computer-readable language, the allowed syntax of XHTML markup There are three XHTML DTDs: STRICT TRANSITIONAL FRAMESET XHTML 1.0 Strict <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Use the strict DOCTYPE when you want really clean markup, free of presentational clutter. Use it together with CSS. XHTML 1.0 Transitional <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Use the transitional DOCTYPE when you want to still use HTML's presentational features. XHTML 1.0 Frameset <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
  • 53. 53 4. Explain Style sheets syntax and types of css with example. Cascading Style Sheets (CSS) are a method of web design that formats web page content according to a presentation style specified by the web page author. There are several advantages to using CS to format the presentation elements of a web page. CSS essentially separates document content from the manner in which it is presented, thus allowing for more fluid transitions between various browser platforms. CSS also provides for more precise control for spacing, alignment, and positioning of content without relying on the need for layout tables or frames. Font style, color, and font size can all be manipulated using CSS as well. The basic CSS Syntax Selector: is the hook used to choose what part(s) of your HTML to apply the CSS to. It indicates the element to which the rule is applied. Following the selector is the... •Declaration Block:Everything within the curly brackets, ―{‖ and ―}‖, is called the declaration block •Declaration: Inside a declaration block you can have as many declarations as you want and each declaration is a combination of a CSS Property and a value. •Property:is one of the CSS Properties used to tell what part of the selector will be changed (or styled). It specifies a characteristic, such as color, font-family, position, and is followed by a colon (:) •Value:assigns a value to the property. Types of selectors CSS has several types of selectors. Explaining all of them in detail would take too long. We will just introduce you with two most commonly used selectors. For a really in depth study, you should look into the W3C specification for selectors. Class and ID selectors With the class selector you can define different styles for the same type of HTML element.In our example, the class selector would look like this: P.blue {color: blue;}
  • 54. 54 ID selector The W3C defines CSS ID as "a unique identifier to an element". IDs are commonly used for Layout and Uniqueness. Standards specify that any given ID name can only be referenced once within a page or document. From our experience, IDs are most commonly used correctly in CSS layouts. This makes sense because there are usually only one menu per page, one banner, and usually only one content pane. Grouping You can group selectors. Separate each selector with a comma H1, H2, H3, H4, H5, H6 {color: blue ;} Positioning The CSS positioning properties allow you to position an element. There are five different layout properties available in CSS: position: static, position: relative, position: absolute, and float. Three ways to insert CSS  Inline CSS  Internal Style Sheets  External Style Sheets Inline CSS The first way is called Inline Cascading Style Sheets. You can add CSS directly into the elements in your markup with the ―style‖ attribute. <div style=‖color:red;‖><p style=‖font-size:12px;‖> ―Style‖ is a ―Core HTML Attribute‖ so you can apply it to any visual HTML/XHTML elements. This may seem to be the easiest way of using CSS, but it is not recommended as it completely ignores the best parts of Cascading Style Sheets. Internal Style Sheets The second way adds CSS to a single document or web page by adding the following code into the <head> of your document using the <style> element. <style type="text/css"> hr {color: sienna} p {margin-left:20px} body {background-image:url("images/back40.gif")} </style> As you can see, <style> is an HTML element that is opened and closed. Within the <style> element is the CSS that will be applied to that page. There is no limit to the amount of CSS you can put inside the <style> element. You would enter this code in the <head> area of your web page (anywhere after <head> and before </head> in your HTML document) and that would apply this CSS to the elements of that web page. External Style Sheets The third and most advantageous way to embed CSS into a document uses External Cascading Style Sheets (or External Style Sheets). An external CSS file is simply a text file with a ―.css‖ extension. This file can then be included into many different pages.
  • 55. 55 This allows you to make one document that has the styling for your entire website. Then you include that file into every page of your website. This is the recommended way of using CSS in your website as it lets you make global visual changes (to an entire website) by only tweaking one file. For Example, let‘s say you have a website where all the paragraphs are black, and you want to change them to grey. Since you have an external Style Sheet, you just open up that one CSS file and change the style for paragraphs to: color:grey; Now all the paragraphs on your website are grey! Here is the code you need to link the css fileto your webpages‖: <link rel=“stylsheet” type="text/css" href=“style.css”> Media Types There are about 10 different media types in CSS, but most common types are Screen and Print. CSS today allows you to link to more than one style sheet in your web page. 5.i)Explain about internet and intranet with difference.(8) ii) Design a HTML document using relative positioning to nudge text to the left. Internet It is a worldwide system which has the following characteristics: Internet is a world-wide / global system of interconnected computer networks. Internet uses the standard Internet Protocol (TCP/IP) Every computer in internet is identified by a unique IP address. IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a computer‘s location. A special computer DNS (Domain Name Server) is used to give name to the IP Address so that user can locate a computer by a name.For example, a DNS server will resolve a name http://www.periit.com to a particular IP address to uniquely identify the computer on which this website is hosted. Internet is accessible to every user all over the world.
  • 56. 56 Intranet Intranet is system in which multiple PCs are connected to each other. PCs in intranet are not available to the world outside the intranet. Usually each company or organization has their own Intranet network and members/employees of that company can access the computers in their intranet. Each computer in Intranet is also identified by an IP Address which is unique among the computers in that Intranet. Similarities in Internet and Intranet Intranet uses the internet protocols such as TCP/IP and FTP. Intranet sites are accessible via web browser in similar way as websites in internet. But only members of Intranet network can access intranet hosted sites. In Intranet, own instant messengers can be used as similar to yahoo messenger/ gtalk over the internet. Differences in Internet and Intranet Internet is general to PCs all over the world whereas Intranet is specific to few PCs. Internet has wider access and provides a better access to websites to large population whereas Intranet is restricted. Internet is not as safe as Intranet as Intranet can be safely privatized as per the need. ii) Design a HTML document using relative positioning to nudge text to the left <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>
  • 57. 57 RelativePos.html </title> <style type="text/css"> .right { position:relative; right:0.25em } </style> </head> <body> <p> <span style="background-color:red">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Red</span> <span style="background-color:yellow">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Yellow</span> <span style="background-color:lime">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Green</span> </p> </body> </html>
  • 58. 58 UNIT –III CLIENT SIDE AND SERVER SIDE PROGRAMMING PART-A 1. How to create an Object in JavaScript? An object is just a special kind of data, with a collection of properties and methods. You can add properties to an object by simply giving it a value. The sytax: objName.propName 2. What is the result of below given line of code in Java Script? 5+4+”7” The answer is 97. Here 5 and 4 are integers, bt since 7 is enclosed within quotes, its considered as a string, and hence is not added. 3.What is undefined value means in JavaScript? Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist. 4. Which method is used to Clear an array using JavaScript? Clear() method is used to clear all the defined array. we use the clear() method which removes all elements from an Array instance. After removing the array by clear() method, the resulting array's length will become zero. 5.What will be the Output of the following using JavaScript document.Write(Math.Round(6.7)); The output will be 7. The math.round function is used to round off the value to the nearest higher integer value. 6.What should appear at the very end of your JavaScript? The <script LANGUAGE="JavaScript">tag 7.What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page. 8. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: The tag handler class that defines the tag's behavior the tag library descriptor file that maps the XML element names to the tag implementations the JSP file that uses the tag library
  • 59. 59 9. What are the implicit objects? Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: –request ,response, pageContext, session application , out , config ,page ,exception 10. Compare Client side vs. server side scripting. Website scripts run in one of two places – the client side, also called the front-end, or the server side, also called the back-end. The client of a website refers to the web browser that is viewing it. The server of a website is the server that hosts it. Client side: JavaScript. Server side: PHP ,Ruby on Rails, ASP.NET 11. State the 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. 12. What is JavaScript? JavaScript is a programming language used to make web pages interactive. It runs on your visitor's computer and doesn't require constant downloads from your website. JavaScript is often used to create polls and quizzes 13. What is the purpose of cookies? Cookies make the interaction between users and websites faster and easier. Without cookies, it would be very difficult for a website to allow a visitor to fill up a shopping cart or to remember the user's preferences or registration details for a future visit. 14. What are the steps needs to establish JDBC connectivity? The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps −  Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code.  Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.  Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect.  Create Connection Object: Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection. 15. What is the difference between GET and POST method?  GET is a safe method (idempotent) where POST is non-idempotent method.
  • 60. 60  We can send limited data with GET method and it‘s sent in the header request URL whereas we can send large amount of data with POST because it‘s part of the body.  GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can‘t bookmark it.  GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.  Hyperlinks in a page uses GET method. 16. What is different between web server and application server? A web server responsibility is to handler HTTP requests from client browsers and responds with HTML response. A web server understands HTTP language and runs on HTTPprotocol. Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat. Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications. 17. What are different methods of session management in servlets? Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. Some of the common ways of session management in servlets are: 1. User Authentication 2. HTML Hidden Field 3. Cookies 4. URL Rewriting 5. Session Management API 18. What is difference between GenericServlet and HttpServlet? GenericServlet is protocol independent implementation of Servlet interface whereas HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet for creating web application and that‘s why we extend HttpServlet class. HttpServlet class extends GenericServlet and also provide some other methods specific to HTTP protocol.
  • 61. 61 UNIT –III PART –B 1. Explain javascript variables and debuggers in detail . (16) JavaScript Variables JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like carname. Rules for JavaScript variable names: Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character Because JavaScript is case-sensitive, variable names are case-sensitive. Declaring (Creating) JavaScript Variables Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var keyword: var x; var carname; After the declaration shown above, the variables are empty (they have no values yet). However, you can also assign values to the variables when you declare them: var x=5; var carname="Volvo"; After the execution of the statements above, the variable x will hold the value 5, and carname will hold the valueVolvo. Assigning Values to Undeclared JavaScript Variables If you assign values to variables that have not yet been declared, the variables will automatically be declared. These statements: x=5; carname="Volvo"; have the same effect as: var x=5;
  • 62. 62 var carname="Volvo"; Redeclaring JavaScript Variables If you redeclare a JavaScript variable, it will not lose its original value. var x=5; var x; After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it. The Lifetime of JavaScript Variables If you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed 2. Discuss JavaScript Array object in detail. (16) JavaScript Arrays •Arrays are used to store lists or collections of items •Arrays in JavaScript are indexed by numbers from 0 •Array elements can be any type, even arrays or objects •An array‘s elements do not have to have the same type Creating Arrays Arrays can be created with the new keyword var(myArray(=(new(Array(); var(myArray(=(new(Array(―one‖,―two‖,(3); or with array literal syntax var(myArray(=([]; var(myArray(=([―one‖,(―two‖,(3]; Updating Array Elements Insert by index myArray[5](=(―new(item‖; Stack/queue-like interface myArray.push(―new(item‖); var(lastItem(=(myArray.pop(); var(firstItem(=(myArray.shift();
  • 63. 63 Iterating Over Arrays var$myArray$=$[]; var$i; myArray.push(―one‖); myArray.push(―two‖); myArray.push(―three‖); for$(i=0;$i<myArray.length();$i+=1)${ console.log(myArray[i]); } Other Array Methods var arrayLength = myArray.length(); myArray.length = 4; myArray.reverse(); myArray.sort(); myArray.indexOf(―this item‖); myArray.lastIndexOf(―this item‖); JavaScript Objects •Most things in JavaScript is an object - even functions •Objects have properties and methods •This distinction is vague, as functions are ‗first class‘ •Prototypes rather than class-based inheritance •The this keyword refers to the current object Creating Objects var(obj1(=(new(Object(); var(emptyObject(=({}; var(myObject(=({ ((((val1:(3, ((((val2:(―x‖, ((((func:(function()({ ((((((((console.log(this.val1(+(―(―(+ ((((((((((((((((((((this.val2); ((((} } Aside: Anonymous Functions •The value assigned to this.func may look a little odd •It is an an anonymous function, a function with no name •This is much the same as any other function, but it doesn‘t have a name •Anonymous functions can have parameters, and are commonly used when a function will be used just once •This simplifies code and reduces namespace clutter
  • 64. 64 Using Objects •You can dynamically add and update properties •myObj.newVal(=(―New(property‖; •myObj.val1(=(5; •You can call methods (properties which are functions) •myObj.func; Object Constructors function(MyConstructor()({ ((((this.val1(=(3; ((((this.val2(=(―x‖; ((((this.func(=(function()({ ((((((((console.log(this.val1(+(―(―(+ ((((((((((((((((((((this.val2); ((((} } var(myObject(=(new(MyConstructor(); The this Keyword •Note that the constructor assigns properties to this •What exactly this is depends on the context •In a constructor, this is the new object •In an object‘s method, this is the object itself •In a callback, this is the object that was triggered •In a browser, this is the window object by default Array-Like Objects •Some JavaScript objects look like arrays (but aren‘t) •document.getElementsByTagName(―p‖); •They can be indexed with [] and have .length •They don‘t have sort, push, etc. •If you add elements then .length doesn‘t change •What‘s going on here? •Objects can be indexed using [] as associative maps •Property names are given inside the brackets •And length is just another property var$obj$=${length:$2}; obj[0]$=$―one‖;$obj[1]$=$―two‖; obj.length$=$2; var$obj2$=${0:―one‖,$1:―two‖,$length:2};
  • 65. 65 3. Write java script to perform all arithmetic operation (16) <html> <head> <title> Arithmatic Operation </title> <script type="text/javascript"> var n1,n2,r; function add() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1+n2; document.myform.result.value=r; } function sub() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1-n2; document.myform.result.value=r; } function mul() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1*n2; document.myform.result.value=r; } function divide() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1/n2; document.myform.result.value=r; } </script> </head> <body> <form name="myform">
  • 66. 66 <h1 align="center"> Arithmatic Operations</h1> <hr color="red"> <center><u>Enter a number in each text box </u><br><br> Number 1:<input type="text" name="n1" value=""> <br><br> Number 2:<input type="text" name="n2" value=""> <br><br> <input type="button" value="Add" onClick="add()"> <input type="button" value="Subtract" onClick="sub()"> <input type="button" value="Multiply" onClick="mul()" > <input type="button" value="Divide" onClick="divide()"><br><br> <font color="red">Result is: <input type="text" name="result" value=""></center></font> </form> </body> </html> Output: