Ip Cbse Book
Ip Cbse Book
Ip Cbse Book
AND LEARNING
MATERIAL
INFORMATICS PRACTICES
COMPILED BY:
ANSHUDHAR
MUKESH
MCA PGT COMP. SCI. & IP
9810727824, 9810728824
mukesha2000@gmail.com
STUDY MATERIAL
CLASS XII (Informatics Practices)
INDEX
Sr. No. Contents Page No.
1 Syllabus
2 Unit-1: Introduction to Computer System 1-7
3 Unit-2: Introduction to Programming 8-58
4 Unit-3:Relational Database Management System 59-81
5 Unit-4: IT Applications 82-86
6 Sample Question Paper 87-98
7. Previous Year CBSE Question Paper (2014) 99-106
Informatics Practices (065)
• Open Source Software (OSS), common FOSS/FLOSS examples (e.g., GNU/Linux, Firefox,
OpenOffice, Java, Netbeans, MySQL), common open standards (WWW, HTML, XML,
ODF, TCP,
IP).
• Indian Language Computing: character encoding, UNICODE, different types of fonts (open
type vs true type, static vs dynamic), Entering Indian Language Text — phonetic and key
map based.
Unit 2:Programming
Review of Class XI;
Programming Fundamentals
(Refer to Appendix A for Swing Control Methods & Properties, and Appendix B for sample
guidelines of GUI Programming)
• Basic concept of Access specifier for class members (data members and methods).
• Basic concept of Inheritance.
• Commonly used libraries:
- String class and methods: toString(), concat(), length(), toLowerCase(), toUpperCase(),
trim(), substring()
- Math class methods: pow(), round()
• Accessing MySQL database using ODBC/JDBC to connect with database.
• Web application development: URL, Web Server, Communicating with the web server,
concept of Client and Server Side.
• HTML based web pages covering basic tags — HTML, TI TLE, BODY, H1..H6, Paragraph
(P), Line Break (BR), Section Separator (HR), FONT, TABLE, LIST (UL, OL), FORM.
• Creating and accessing static pages using HTML and introduction to XML.
Unit 4: IT Applications
• Front-end Interface: Introduction; content and features; identifying and using appropriate
component (Text Box, Radio Button, CheckBox, List, etc., as learnt in Unit 2 (Programming))
for data entry, validation and display.
• Back-end Database: Introduction and its purpose, exploring the requirement of tables and its
essential attributes.
• Front-End and Database Connectivity: Introduction, requirement and benefits.
• Demonstration and development of appropriate Front-end interface and Back-end Database for
e- Governance, e-Business and e-Learning applications.
• Impact of ICT on society: Social and Economic benefits.
In each of the above domains, identify at least two real-life problems, list the expected outputs and
the input(s) required for the output, and describe the problem solving approach and develop
relevant front-end interface and back-end database.
UNIT – 1
Important Definitions
Network: A Computer Network is a number of computers (Usually called terminals
interconnected by one or more transmission paths.
Need of Networking:
1. Resource Sharing
2. File and data sharing.
3. Data security and centralized security
4. High Reliability :
5. Communication Media
Application of Networks
1. Sharing of data, services and resources
2. Access to remote database
3. Communication facilities
1
NETWORK TOPOLOGIES : The pattern of interconnection of nodes in a network is
called Topology.
1) Bus Topology or Linear Topology : In this topology a single length of the
transmission medium is used onto which the various nodes are attached. The transmission
from any station travels the length of the bus, in both directions and can be received by all
other stations. The bus has a terminator at either end which absorbs the signal, removing it
from the bus.
Characteristics:
1. Short cable length and Simple wiring layout
2. A single cable called trunk is used through which all data propagates and to which all nodes are
connected
3. Easy to extend
4. There is no central point of failure on a bus because there is no hub.
5. Entire network shuts down if there is break in the main cable.
6. Terminators are required at both ends of the backbone cable.
7. Addition of nodes negatively affects the performance of the whole network.
2) Ring Topology: In a ring topology each node is connected to two and only two neighboring
nodes. Data is accepted from one of the neighboring nodes and is transmitted onwards to another.
Thus data travels only in one direction.
1. Every computer serves as a repeater to boost signals
2. Short cable length.
3. Suitable for optical fiber
4. Difficult to add computers
5. More expensive
6. If one computer fails, whole network fails
7. Data clashes can also occur if two machines send messages at the same time.
3) Star Topology: A star topology is designed with each node connected directly to the server
via hub or switch. This topology is used in most existing information network. Data on a star
network passes through the hub or concentrator before continuing to its destination.
1. Easy to install and wire
2. No disruptions to the network when connecting or removing devices.
3. Easy to add new station as each station has direct cable connection to hub or switch.
4. Depending on the intelligence of hub, two or more computers may send message at the same
time
5. One malfunctioning node does not affect the rest of the network.
6. Required more cable length than a linear topology.
7. All signals transmission through the hub; if down, entire network down
4) Tree Topology
A tree topology (hierarchical topology) can be viewed as a collection of star networks arranged in a
hierarchy. This tree has individual peripheral nodes (e.g. leaves), which are required to transmit to
and receive from one node to other node and are not required to act as repeaters or regenerators.
Unlike the star network, the functionality of the central node may be distributed.
2
As in the conventional star network, individual nodes may be isolated from the network in case of
failure, if a link connecting a leaf fails, that leaf is isolated. If a connection to a non-leaf node fails,
an entire section of the network becomes isolated from the rest.
NETWORK DEVICES
1. MODEM( MOdulator DEModulator) : Modem is a device that converts digital data
originating from a terminal or computer to analog signals used by voice communication network
such as the telephone system.
At one end, modems convert the digital pulse to audible tones and convert audio tones back to
digital pulses at the other
2. RJ –45 Connector:
The RJ-45 is a single line jack for digital transmission over ordinary phone wire. It is a 8 wire
connector which is commonly used to connect computers on the LAN(especially Ethernets). RJ –
short for Registered Jack – 45
3. Hub: Hub is a device used to connect several computers together. It is a multi-port card. Hubs
forward any data packets including e-mail, word processing documents or print request – they
receive over one port from one workstation to all of their remaining ports
4. Switches : Switches are smart hubs that send data directly to the destination rather than
everywhere within network. When the switch receives a packet, the switch examines the destination
and source hardware address and compare them to a table of a network segments and addresses. If
the segments are the same the packet is dropped and if the different then the packet is forwarded to
the proper segments.
5. Repeaters :A repeater is a device that amplifies a signal being transmitted on the network.
Since a signal loses strength as it passes along a cable, it if often necessary to boost the signal with
this device.. The repeater electrically amplifies the signal it receives and rebroadcasts it.
6. Router: A device that works like a bridge but can handle different protocols, is known as
router. It is used to separate different segments in a network to improve performance and reliability.
Types of Networks
1. LAN(Local Area Network):-Small computer networks that are confined to a
localized area(e.g. in an office, a building, or a factory)
2. MAN(Metropolitan Area Network): These are spread over a city. E.g. Cable TV
Networks.
3. WAN(Wide Area Network):-These are spread across countries and facilitate fast and
efficient exchange of information at lesser costs and high speeds. E.g. Internet
4. PAN(Personal Area Network): Refers to a small network of communication capable IT
enabled devices within a range of upto 10 meters. It can be wired(using USB) or
wireless(using Bluetooth)
3
Communication Media:-
Wired Transmission Media:-
Twisted Pair:
A cable composed of two small-insulated conductors twisted together without a common covering.
Also known as copper pair. The wires are twisted around each other to minimize interference from
other twisted pairs in the cable. Twisted pairs have less bandwidth than coaxial cable or optical
fiber.
Coaxial Cables:
A cable consisting of two concentric conductors (an inner conductor and an outer conductor)
insulated from each other by a dielectric, commonly used for the transmission of high-speed
electronic data and/or video signals. Coaxial cable is used as a transmission line for radio frequency
signals, in applications such as connecting radio transmitters and receivers with their antennas,
computer network (Internet) connections, and distributing cable television signals.
Optical Fiber:
A flexible optically transparent fiber, usually made of glass or plastic, through which light can be
transmitted by successive internal reflections.
An optical fiber is made up of the core, (carries the light pulses), the cladding (reflects the light
pulses back into the core) and the buffer coating (protects the core and cladding from moisture,
damage, etc.). Together, all of this creates a fiber optic, which can carry up to 10 million messages
at any time using light pulses.
Ethernet Cables:
Ethernet is used to connect computers in a company or home network as well as to connect a single
computer to a cable modem for Internet access.
Wireless Technologies:
Bluetooth:
Bluetooth is an open wireless technology standard for exchanging data over short distances (using
short length radio waves) from fixed and mobile devices, creating personal area networks (PANs)
with high levels of security.
4
Network Security:
Network security consists of the provisions made in an underlying computer network infrastructure,
policies adopted by the network administrator to protect the network and the network-accessible
resources from unauthorized access.
Threats
Snooping: Refers to unauthorized access of someone else’s data, email, computer activity or data
communication.
Eavesdropping: Act of secretly listening someone else’s private communication/data or
information.
Denial of Services Attack: Attacks that prevent the legitimate users of the system , from accessing
the resources , information or capabilities of system.
Measures of security:
Firewall: System designed to prevent unauthorized access to or from a private network. Proper
security policy for your organization. Giving file permissions
5
FSF (Free Software Foundation)
Non-profit organization created for the purpose of supporting free software movement.
GNU (GNUs Not Unix)
To create a system compatible to UNIX but not identical with it.
Now it offers a wide range of software, including applications apart from operating system.
Proprietary software (neither open nor freely available)
Its use is regulated and further distribution and modification is either forbidden or requires special
permission by the supplier. Source code is not available.
Freeware
Free of cost
Copying and further distribution but not modification.
Source code is not available
E.g. Microsoft Internet Explorer
Shareware
Right to redistribute copies
After a certain period of time license fee should be paid.
Source code is not available.
Modifications are not possible.
Main aim is to increase user's will to pay for the software. Limits functionality after a trial
period of 1-3 months.
Some Open Source Softwares
LINUX
Linux: - free and open source operating system software.
It can be downloaded from www.linux.org
Linux is a part of popular web server program LAMP (Linux, apache, MySql, PHP).
Mozilla
Freeware
No source code available
Free internet browsing software
It can be downloaded from www.mozilla.org
Apache Server
The most common web server (or HTTP server) software on the Internet.
Apache is designed as a set of modules, enabling administrators to choose which features
they wish to use and making it easy to add features to meet specific needs including
handling protocols other than the web-standard HTTP.
Apache HTTP server is an open source web server.
It is component of LAMP.
Proprietary Standards and Open Standards.
Proprietary standards are those for which users have to buy license to use them. For e.g. MS
Office format .doc, .ppt, .xls etc
Open Standards are internationally accepted technical standards that guarantee that data can be
exchanged across platforms and for any applications. Open is feely open to all.
Advantages of Open Standards:
Making the data accessible to all.
It ensures data is application and platform independence.
6
Diversity and Interoperability in the Industry i.e. it enables business and people to go for
any technology of their choice as per their needs and budget.
E.g.: ASCII Characters, HTML file, Joint Photographic Expert Group, Portable Network
Graphic etc.
Ogg Vorbis:
It is a new audio compression which is open format developed by Xiph.org. It is roughly
comparable to mp3, mpeg-4 formats and is completely free, open and unpatented.
Unicode standard has incorporated Indian Scripts under the group named Asian scripts. Indian
scripts included as Devnagari, Bengali, Gurumukhi, Gujarati, Oriya, Tamil, Telgu, kannada, and
Malayalam.
Fonts:
A Font refers to a set of displayable text characters called glyphs, having specific style and size.
There are two categories of font: True Type Font and Open Type Font.
True Type Font: It is developed by Apple and licensed to Microsoft. It is 8 bit font which
is compatible with Microsoft Windows and MAC OS.
Open Type Font: It is the extension of the True Type Font Format which is 16 bits font and
support 65536 characters (Unicode characters).
Indian Language Text Entry:
Many Tools / software have been developed to facilitate the typing of Indian Language text. There
are two types text entries:
Phonetic Text Entry: Words typed as per their pronunciation in English script and later on
converted to Corresponding (Hindi/Gujarati) language work is known as phonetic text entry.
Key map based text entry: When you type text from a keyboard having key mapping of
Indian language characters, is known as key map based text entry..
7
UNIT – 2
PROGRAMMING
Programming Fundamentals
Token
The smallest individual unit in a program is known as Token. Java has the following types of
tokens:-Keyword ,Identifier, Literals, Punctuators and operators.
Keywords:
The following list shows the reserved words in Java. These reserved words may not be used
as constant or variable or any other identifier names.
while
volatile
Literals:
A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation. Literals can be assigned to any primitive type variable.
For example:
8
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these
number systems for literals. For example:
String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a = "\u0001";
Identifiers
All Java components require names. Names used for classes, variables and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value
Examples of illegal identifiers: 123abc, -salary
9
Java Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Data Types
There are eight primitive data types supported by Java. Primitive data types are predefined
by the language and named by a keyword. Let us now look into detail about the eight
primitive data types.
Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that be changed. For
example, Employee, Puppy etc.
Class objects, and various type of array variables come under reference data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
10
Scope of a variable:-The part of program where a variable is usable is called scope of a variable.
Block: A group of statement enclosed in pair of parenthesis is called block or a compound
statement
Programming Construct
1. Sequence
2. Selection:-Simple if, If-Else, else if ladder, Switch
3. Iteration:- while ,do-while, for loop
An entry control loop first test the terminating condition and then executes the loop body. If
the condition is found true the loop body is execute otherwise the loop terminates. In case if
the condition is false in first in the first time only then loop will not get executes even once.
An exit control loop first executes the loop body and then test the terminating condition .if
the condition is found true the loop body executed again otherwise the loop terminates. .In
case if the condition is false in first time only then the loop will still get execute at least
once.
JPanel is Swing’s version of the AWT class Panel and uses the same default layout, Flow
Layout. JPanel is descended directly from JComponent.
JFrame is Swing’s version of Frame and is descended directly from that class. The
components added to the frame are referred to as its contents; these are managed by the
content Pane. To add a component to a JFrame, we must use its content Pane instead.
JInternalFrame is confined to a visible area of a container it is placed in. It can be confined
, maximized and layered.
JWindow is Swing’s version of Window and is descended directly from that class. Like
Window, it uses Border Layout by default.
JDialog is Swing’s version of Dialog and is descended directly from that class. Like Dialog,
it uses BorderLayout by default. Like JFrame and JWindow,
JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and
glass panes. All dialogs are modal, which means the current
thread is blocked until user interaction with it has been completed. JDialog class is intended
as the basis for creating custom dialogs; however, some
of the most common dialogs are provided through static methods in the class JOptionPane.
JLabel, descended from JComponent, is used to create text labels.
11
The abstract class Abstract Button extends class JComponent and provides a foundation for
a family of button classes, including JButton.
JTextField allows editing of a single line of text. New features include the ability to justify
the text left, right, or center, and to set the text’s font.
JPasswordField (a direct subclass of JTextField) you can suppress the display of input.
Each character entered can be replaced by an echo character.
This allows confidential input for passwords, for example. By default, the echo character is
the asterisk, *.
JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction
with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to
always or never have either the vertical or horizontal scrollbar;
JButton is a component the user clicks to trigger a specific action.
JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of
radio buttons can be associated as a group in which only
one button at a time can be selected.
JCheckBox is not a member of a checkbox group. A checkbox can be selected and
deselected, and it also displays its current state.
JComboBox is like a drop down box. You can click a drop-down arrow and select an
option from a list. For example, when the component has focus,
pressing a key that corresponds to the first character in some entry’s name selects that entry.
A vertical scrollbar is used for longer lists.
JList provides a scrollable set of items from which one or more may be selected. JList can
be populated from an Array or Vector. JList does not
support scrolling directly, instead, the list must be associated with a scroll pane. The view
port used by the scroll pane can also have a user-defined
border. JList actions are handled using ListSelectionListener.
Focus:- The control under execution is said to have the focus.The control having the focus
obtains input from the user.
getText():- getText() method is used to obtain the text from a jTextField during the run
time.
setText():- setText(0 method is used to set or change the text of a jTextField during run
time.
GUI DIALOGS: -
A Dialog: It is a small separate window that appears to either provide or request to/from the
user.
Java Swing provides four dialog types:
a) JDialog(General purpose dialogs)
b) JOptionPane (Pre-defined styles)
c) JFileChooser (dialog for choosing files) and
d) JColorChooser(dialog for choosing colour)
12
JOptionPane dialog Type:
There are four built-in dialog styles:
i. Message dialog_ JOption.ShowMessageDialog() displays the message dialog
ii. Input dialog_ JOption.ShowInputDialog() displays the input dialog
iii. Confirm dialog_ JOption.ShowConfirmDialog() displays the confirm dialog
iv. Option dialog_ JOption.ShowOptionDialog() displays the option dialog
Solved Questions
Q3. Why do we write a comment in a program? What are two ways of writing comment in a java
program?
Ans. Comments are added to a program for making it more readable and understandable.
Single line comment : //
Multi –line Comment:- /*-
----------------------*/
Q4. What is a syntax error in context of a program?
Ans. Error in the way of writing a statement in a program, yields a syntax error.
Q5. Name and explain the usage of nay two data types used in java to store numbers with decimals.
Ans. Two data types available in java for storing numbers with decimals are
1. float:-for single precision floating point values for example float num=20.0F
2. double: for double precision floating point value. This is the default data type for decimal
numbers for example double num=15.0
Q6. Name and explain the usage of any one relational and one logical operator in java.
Ans. One relational operator in java is = = .This operator results in true if both its operands are
equal otherwise false. One logical operator in java is&&.This operator is used to combine two
logical values. The result of the && will be true if and only if both its operands (both condition) are
true otherwise false.
13
operands are equal, condition evaluates to true otherwise to false .
Q10. What is the difference between Entry controlled loop and exit controlled loop?
Ans. Entry controlled loop:- In this , condition is tested before entering into the loop, if the test-
condition evaluates to true, the loop body executed. The loops belonging to this category are for
loop and while loop.
Exit Controlled loop:- this loop first executes the loop body and then evaluates the continuation
condition. The loop belonging to this category is do-while loop. This types of loops are useful when
you have to execute the loop body atleast once irrespective of the test-condition’s evaluation such
as for displaying menu option
Q.3. What will be the value of j and k after execution of the following code:
int j=10,k=12;
if(k>=j)
{
k=j;
j=k;
} Ans. j=10,k=10
14
Q,5, How many times ,the following loop gets executed?
i=0;
do{
//statements
}while(i>20); Ans. one time
Q.6. What will be the contents of TextField after exec uting the following statement:
int num=4;
num=num+1;
if(num>5)
jTextField1.setText(Integer.toString(num));
else
jTextField1.setText(Integer.toString(num*4)); Ans. 20
Q.7.find the output
int number1=7,number2=8;
int second=73;
if(number1>0||number2>5)
if(number1>7)
jTextField1.setText(“code worked”);
else
jTextField1.setText(“code might work”);
else
jTextField1.setText(“code will not work ”); Ans . code
might work
Q.8. How many times will the following loop get executed?
x=5; y=36;
while(x<=y)
{
x+=6;
}
Q.9. What will be the content of the jTextArea1 after executing the following code?
int num=1;
do
{
jTextArea1.setText(Integer.to String(++num)+”\n”);
num=num+1;
}while(num<=10); Ans. 10
Q.10. Give the output for the following code fragment:
v=20;
do{
jOptionPane.showMessageDialog(numm,v+””);
}while(v<50);
jOptionPane.showMessageDialog(numm,v+””); Ans. infinite
loop
Q.11. Give the value after executing following java code.Also find how many times the following
loop will execute?
15
int a=10;
int b=12;
int x=5;
int y=6;
while(a<=b)
{
if(a%2==)
x=x+y;
else
x=x-y;
a=a+1;
} Ans. x=11
Q.12.What will be the output produced by following code fragment?
float x=9;
float y=5;
int z=(int)(x/y);
switch(z)
{
case 1:x=x+2;
case 2: x=x+3;
default: x=x+1;
}
System,.out.println(“value of x:”+x); Ans. 15
16
Q.16. What values will be assigned to the variable ua,ub,uc and fail after execution of the
following program segment:
int i=0,ua=0,ub=0,uc=0,fail=0;
while(i<=5){
switch(i++)
{
case 1:++ua;
case 2:++ub;uc++;break;
case 3;
case 4:++uc;ua++;ub++;break;
default:++fail;
} Ans. ua=1, ub=1, uc=0
Q.17. Predict an output of the following code fragment:
int i=1,j=0,n=0;
while)i<4)
{
for(j=1;j<=I;j++)
{
n+=1;
i=i+1;
}
System.out.println(n);
} Ans. 6
Q..18. Give the output of the following code:
int m=100;
while(m>0)
{
if(m<10)
break;
m=m-10;
}
System.out.println(“m is “+m); Ans. 0
17
case ‘E’:
case ‘i’:
case ‘E’:
case ‘u’:
case ‘U’:++vowels;
break;
default:++others;
Ans: Two case constant doesn’t have the same value
Q.3. int j=5;
i==j+5;
if(i=j)
jTextField1.setText(“I and j are equal”);
else
jTextField1.settext(“ I and j are unequal”);
Ans. int i,j=5;
i=j+5;
if(i==j)
jTextField.setText(“I and j are equal”);
else
jTextField1.settext(“ I and j are unequal”);
Q.4. Rewrite the code after making correction. Underline the correction.
Int sum;value;inct;
Int i
For(i==0;i<=10;i++)
Sum=sum+I;
Inct++;
Ans.
int sum,value,inct;
int i;
for(i=0;i<=10;i++)
sum=sum+i;
inct++;
Q.5. The following code has some error(s).Rewrite the correct code underlining all the corrections
made.
Int y=3;
Switch(y)
{
case 1: System.out.println(“yes its one”);
case >2: System.out.println(“yes it is more than tw
o”); break;
case else: System.out.println(“invalid number”);
Ans. int y=3;
switch(y)
{
case 1 : System.out.println(“yes its one”);
break;
case 2: System.out.println(“yes its more than two”) ;
18
break;
default: System.out.println(“invalid number”);
}
Q.6. Rewrite the following java code after underlining the correction made:
int x==0;
int n=Integer.parseInt(jLabel1.getText());
Ans. int x=0;
int n=Integer.parseInt(jLabel1.getText());
19
for(I=0;I<10; I+=2)
{
Sum+=I;
}
Q.2. rewrite the following code using while loop:
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=I;++j)
System.out.print(j);
}
System.out.println();
}
Ans.
int i=1.j;
while(i<=4)
{
J=1;
while(j<=i)
{
System.out.print(j);
++j;
}
i++;
System.out.prinln();
}
Q.3. Write a equivalent while loop for the following code:
int sz=25;
for(int i=0,sum=0;i<sz;i++)
sum+=I;
System.out.println(sum);
Ans. int sz=25;
int i=0,sum=0;
while(i<sz)
{
sum+=i;
i++;
}
System.out.println(sum);
Q.4.Rewrite the following if-else segment using switch –case statement
char ch=’A’;
if(ch==’A’)
System,out.println(“Account”);
if((ch==’C’)||(ch==’G’))
System.out.println(“Admin”);
if(ch==’F’)
System.out.println(“advisor”);
20
Ans. char ch=’A’;
switch(ch)
{
case ‘A’:System.out.println(“account”);
break;
case ‘C’:
case ‘G’: System.out.println(“admin”);
break;
case ‘F’: System.out.println(“advisor”);
}
Q..5. Rewrite the following code using while loop
int i, j;
for(i=1,j=2;i<=6;i++,j+=2)
System.out.println(i++);
System.out.println(“finished!!!”);
Ans.
int i=1,j=2;
while (i<=6)
{
System.out.println(i++);
i++;
j+=2;
}
System.out.println(“finished!!!”);
Q.6. Rewrite the following code using for loop.
int i=0;
while(++i<20)
{
if(i==8)
break;
System.out.println(i++);
}
Ans. int i;
for(i=1;i<20;++i)
{ if(i==8) break;
System.out.println(i++);
}
Q.7.Rewrite the code using switch statement:
if(k==1)
day=”Monday”;
else if(k==2)
day=”Tuesday”;
else if (k==3)
day=”Wednesday”;
else day=”-“;
}
21
Ans. switch(k)
{
case 1:day=”Monday”;
break;
case 2”day=”Tuesday”;
break;
case 3 :day=”Wednesday”;
break;
default: day= “ “ ;
}
Questions
1. How do you write an infinite loop using the for statement?
2. How do you write an infinite loop using the while statement?
22
6. . What will be the output of the program?
int i = 1, j = 10;
do
{
if(i > j)
{
break;
}
j--;
} while (++i < 5);
System.out.println("i = " + i + " and j = " + j);
23
case 2: System.out.print("two ");
case 3: System.out.print("three ");
}
}
System.out.println("done");
11. What will be the output of the program?
int i = 1, j = 0;
switch(i)
{
case 2: j += 6;
case 4: j += 1;
default: j += 2;
case 0: j += 4;
}
System.out.println("j = " + j);
12. What will be the output of the program?
int i = 1, j = 0;
switch(i)
. {
case 2: j += 6;
case 4: j += 1;
default: j += 2;
case 0: j += 4;
}
System.out.println("j = " + j); }
24
}
15. What will be the output of the:
(i) byte b;
double d=417.35;
b=(byte)d;
System.out.println(b);
Solved Question
Some Important Questions with Answers
1. Which window is used to design the form
Ans. Design Window
2. Which window contains the Swing Controls components?
Ans. Palette window
3. What is the most suitable component to accept multiline text.
Ans. TextArea
4. Name the different list types controls offered by Java Swing.
Ans. (i) jListBox (ii)jComboBox
5. Name any two commonly used method of ListBox.
Ans. (i)getSelectedIndex() (ii)getSelectedValue()
6. By default a combo box does not offer editing feature. How would you make a combo box
editable.
Ans. By setting its editable property to true.
7. What is the name of event listener interface for action events?
Ans.ActionPerformed
8. What is the difference between a Container and Component control?
Ans. A container is a control that can hold other controls within it. E.g. Panel(there can be
multiple controls inside Panel, Frame(where you can put so many controls on it.)
Component: Controls inside the container are known as container
9. Differentiate between
(a) TextField and TextArea components
25
(b) TextField and PasswordField
(c) Combo box and list box
(a) Ans. The TextField allows the user to enter a single line of text only. But Text Area
component allows to accepts multiline input from the user or display multiple lines of
information.
(b) Textfield displays the obtained text in unencrypted form whereas password field
displays the obtained text in encrypted form. This component allows confidential input
like passwords
(c) List box :- In the list box,the users can only select from the list of choices, but in
combobox a user can select from the list of choices as well as enter his/her
choice(combobox=listbox+textfield)
26
24. What is an event? What is event handler, source, object?
Ans. An event is occurrence of some activities either initiated by user or by the system. In order
to react, you need to implement some event handling system in your application. Event source:-It
is the GUI component that generates the event eg. Button
Event Handler or Event Listener:- It is implemented as in the form of code .It receives and handles
events through listener interface.
Event object or message:- It is created when event occurs. It contains all the information about
the event which includes source of event and type of even etc.
25. Which property would you set the setting the password character as $?
Ans. echoChar
26. Which method returns the password entered in a password field?
Ans. getPassword( )
27. Which method would you determine the index of selected item in a list?
Ans. getSelectedIndex(int Index)
28. Which method would you use to insert an item at specified index, in the list?
Ans. setSelectedIndex(4)
29. How you can determine whether 5th item in a list is selected or not?
Ans. isSelectedIndex(4)
30. Which method you would use to insert “hello” at 10 th position in the TextArea control.
Ans. insert(“hello”,9) //index st arts from zero
31. Which property would you like to set to make a combo box editable?
Ans. Editable
32. What do you understand by focus.
Ans. A Focus is the ability to receive user input/response through Mouse/Keyboard .When object
or control has focus, it can receive input from user.
a) An object or control can receive focus only if its enabled and visible property are set
to true.
b) Most of the controls provide FOCUS_GAINED( ) and FOCUS_LOST( ) method
33. What is meant by scope of a variable ?
Ans. In java ,a variable can be declared anywhere in the program but before using them.
1.The area of program within which a variable is accessible , known as its scope.
2.A variable can be accessed within the block where it is declared
{
int x=10;
if(a>b)
{
int y=5;
//scope of x and y
}
else
{
int z=3;
//scope of z
} }
27
DESIGN PROBLEMS
Q1.
Solution:
(1)
txtDiscount.setEditable(false);
txtNetAmt.setEditable(false);
(2)
//Code for calculate button
double bm=Double.parseDouble(txtbillamt.getText(););
double disc=0.0, netAmt=0.0;
String s= cmbMode.getSelectedItem();
if(s.equals(“Cash”))
{
disc= 0.08*bm;
}
else if(s.equals(“Cheque”))
{
disc=0.07*bm;
28
}
else if(s.equals(“Cash”))
{
disc=0;
}
netAmt=bm-disc; txtDiscount.setText(“ “+disc); txtN etAmt.setText(“ “+netAmt);
(3)
//code for stop button
System.exit(0);
2. Create a Java Desktop Application to find the incentive (%) of Sales for a Sales Person on the
basis of following feedbacks:
Feedback Incentive (%)
Maximum Sales 10
Excellent Customer Feedback 8
Maximum Count Customer 5
Note: that the sales entry should not be space. Calculate the total incentive as :
Sales amount* Incentive.
The feedback will be implemented in JCheckBox controls. Using a JButton’s (Compute Incentive)
click event handler, display the total incentives in a JTextField control. Assume the nomenclature
of the swing components of your own.
Note that the JFrame from IDE window will be shown as given:
29
Ans:- private void btnIncActionPerformed (java.awt.ActionEvent evt)
{
int sales = 0;
if (! txtSales.getText( ).trim( ).equals( “”))
{
sales-Integer.parseInt(txtSales.getText( ).trim ( ));
}
double incentive = 0.0;
if (jCheckBox1.isSelected ( ))
{
incentive = incentive + 0.1;
}
if (jCheckBox2.isSelected ( ))
{
incentive = incentive + 0.8;
}
if (jCheckBox3.isSelected ( ))
{
incentive = incentive + 0.05;
}
txtInc.setText ( “ “ + Math.round(sales * incentive ));
}
3. Assume the following interface built using Netbeans used for bill calculation of a ice-cream
parlor. The parlor offers three verities of ice-cream – vanilla, strawberry, chocolate. Vanilla
icecream costs Rs. 30, Strawberry Rs. 35 and Chocolate Rs. 50. A customer can chose one or more
ice-creams, with quantities more than one for each of the variety chosen. To calculate the bill parlor
manager selects the appropriate check boxes according to the verities of ice-cream chosen by the
customer and enter their respective quantities.
Write Java code for the following:
a. On the click event of the button ‘Calculate’, the a pplication finds and displays the total bill of
the customer. It first displays the rate of various ice-creams in the respective text fields. If a user
doesn’t select a check box, the respective ice -cream rate must become zero. The bill is
calculated by multiplying the various quantities with their respective rate and later adding them
all.
b. On the Click event of the clear button all the text fields and the check boxes get cleared.
c. On the click event of the close button the application gets closed.
30
Ans: (a)
private void jBtncalculateActionPerformed(java.awt.event.ActionEvent evt)
{
if(jchkStrawberry.isSelected()==true)
jTxtPriceStrawberry.setText("35");
else
{
jTxtPriceStrawberry.setText("0");
jTxtQtyStrawberry.setText("0");
}
if(jChkChocolate.isSelected()==true)
jTxtPriceChocolate.setText("50");
else
{
jTxtPriceChocolate.setText("0");
jTxtQtyChocolate.setText("0");
}
if(jChkVinella.isSelected()==true)
jtxtPriceVinella.setText("30");
else
{
jtxtPriceVinella.setText("0");
jTxtQtyVinella.setText("0");
}
int r1,r2,r3,q1,q2,q3,a1,a2,a3,gt;
r1=Integer.parseInt(jTxtPriceStrawberry.getText());
r2=Integer.parseInt(jTxtPriceChocolate.getText());
r3=Integer.parseInt(jtxtPriceVinella.getText());
q1=Integer.parseInt(jTxtQtyStrawberry.getText());
31
q2=Integer.parseInt(jTxtQtyChocolate.getText());
q3=Integer.parseInt(jTxtQtyVinella.getText());
a1=r1*q1;
jTxtAmtStrawberry.setText(""+a1);
a2=r2*q2;
jTxtAmtChocolate.setText(""+a2);
a3=r3*q3;
jTxtAmtVinella.setText(""+a3);
gt=a1+a2+a3;
jTxtTotalAmt.setText(""+gt);
}
Ans.(b)
private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt)
{
jTxtPriceStrawberry.setText("");
jTxtPriceChocolate.setText("");
jtxtPriceVinella.setText("");
jTxtQtyStrawberry.setText("");
jTxtQtyChocolate.setText("");
jTxtQtyVinella.setText("");
jTxtAmtStrawberry.setText("");
jTxtAmtChocolate.setText("");
jTxtAmtVinella.setText("");
jchkStrawberry.setSelected(false);
jChkChocolate.setSelected(false);
jChkVinella.setSelected(false);
}
Ans: (c)
private void jBtncloseActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}
4. Read the following case study and answer the questions that follow.
TeachWell Public School wants to computerize the employee salary section.
The School is having two categories of employees : Teaching and Non Teaching. The
Teaching employees are further categorized into PGTs, TGTs and PRTs having different
Basic salary.
The School gives addition pay of 3000 for employees who are working for more than 10
years.
32
Employee Type Basic DA (% of Basic Sal) HRA (% of Basic Sal) Deductions
Salary (% of Basic sal)
Non-Teaching 25001 31 30 12
PGT 14500 30 30 12
TGT 12500 21 30 12
PRT 11500 20 25 12
(a) Write the code to calculate the Basic salary, deductions, gross salary and net salary based on
the given specification. Add 3000 to net salary if employee is working for more than 10 years.
Gross salary=Basic salary + DA + HRA
Net salary = Gross salary – deductions
(b)Write the code to exit the application.
(c)Write the code to disable textfields for gross salary, deductions and netsalary.
Ans: (a)
double bs=0,da=0,net=0,ded=0,gross=0,hra=0;
if (rdnon.isSelected()==true)
{
bs=12500;
da=(31*bs)/100;
hra=(30*bs)/100;
ded=(12*bs)/100;
}
else if (rdpgt.isSelected()==true)
{
bs=14500;
da=(30*bs)/100;
hra=(30*bs)/100;
ded=(12*bs)/100;
}
else if (rdtgt.isSelected()==true)
{
33
bs=12500;
da=(21*bs)/100;
hra=(30*bs)/100;
ded=(12*bs)/100;
}
else if (rdprt.isSelected()==true)
{
bs=11500;
da=(20*bs)/100;
hra=(25*bs)/100;
ded=(12*bs)/100;
}
gross=bs+da+hra;
net = gross – ded;
if(chk10.isSelected()==true)
{
net=net+3000;
}
tfded.setText(“ ”+ded);
tfgross.setText(“ ”+gross);
tfnet.setText(“ ”+net);
tfbs.setText(“ ”+bs);
Ans:(b)
System.exit(0);
Ans:(c)
tfgross.setEditable(false);
tfded.setEditable(false);
tfnet.setEditable(false);
5. ABC School uses the following interface built in java to check the eligibility of a student for a
particular stream from science, commerce and humanities. The user first enters the total percentage
and selects the desired stream by selecting the appropriate option button. An additional 5% is marks
is given to students of NCC. Write Java Code for the following
a. On Action event of the button ‘Calc Percentage’ Net percentage of the student is calculated
and displayed in the appropriate text filed. Net percentage is same as that of the actual
percentage if the student doesn’t opts for NCC otherwise 5% is added to actual percentage.
b. On Action event of the button ‘Result’, the applica tion checks the eligibility of the
students. And display result in the appropriate text field. Minimum percentage for science
is 70, 60 for commerce and 40 for humanities.
c. On the Click event of the clear button all the text fields and the check boxes get cleared.
d. On the click event of the close button the application gets closed.
34
Ans:
a.
private void jBtnCalcPerActionPerformed(java.awt.event.ActionEvent evt)
{
int p;
p=Integer.parseInt(jTextField2.getText());
if (jCheckBox1.isSelected())
p=p+5;
jTextField3.setText(Integer.toString(p));
}
b.
private void jBtnResultActionPerformed(java.awt.event.ActionEvent evt)
{
int p;
p=Integer.parseInt(jTextField3.getText());
if( jRadioButton1.isSelected())
{
if ( p>=70)
jTextField4.setText(“Eligible for all subject”);
else
jTextfield4.setText(“Not Eligible for science”);
}
35
else if( jRadioButton2.isSelected())
{
if ( p>=60 )
jTextField4.setText(“Eligible for Commerce and Huma nities”);
else
jTextfield4.setText(“Not Eligible for Science and C ommerce”);
}
else
{
if ( p>=40 )
jTextField4.setText(“Eligible for Humanities”);
else
jTextfield4.setText(“Not Eligible for any subject ” );
}
}
c.
private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt)
{
jTextField1.setText(“ “) OR jTextField1.setText(nul l)
jTextField1.setText(“ “) OR jTextField1.setText(nul l)
jTextField1.setText(“ “) OR jTextField1.setText(nul l)
jTextField1.setText(“ “) OR jTextField1.setText(nul l)
jCheckbox1.setSelected(false);
}
d.
private void jBtnCloseActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}
Unsolved Questions:
1. Describe the relationship between properties, methods and events.
2. What is container tag?
3. What does a getPassword() method of a password field returns?
4. What will be the contents of jTextArea1 after executing the following statement: 1
5. jTextArea1.setText("Object\nOriented\tProgramming");
6. What is difference between jRadioButton and jCheckBox?
7. What does a JList fire when a user selects an item?
8. What is Layout Manager? Discuss briefly about layout managers offered by NetBeans?
9. Name three commonly used properties and methods of the following controls.
10. (a) text field (b) text area (c) label (d) Check Box (e) button.
11. What is dispose() used for ?
12. What is the difference between-
36
13. (a) Text field & Text area
14. (b) List & Combo
15. (c) Radio Button & Check Box
16. What is the significance of following properties of a text area?
17. (a) lineWrap (b) wrapStyleword
18. What is the significance of a button group ? How do you create a button group?
19. Discuss about some commonly used properties of lists and a combo boxes.
20. What methods obtain the current selection of a combo box? Give a code example.
21. The FOR U SHOP has computerized its billing. A new bill is generated for each customer.
The shop allows three different payment modes. The discount is given based on the payment
mode.
a) Write the code for the CmdClear Button to clear all the Text Fields.
b) Write the code for the CmdCalc Button to display the Discount Amount and Net Price in the
TxtDisc and the TxtNet Text Fields respectively.
37
JAVA GUI PROGRAMMING REVISON TOUR –III
What is an object?
An object is an identifiable entity with some characteristics and behavior.
“Yourself are also an example of object. Your uniq ue identity is your name. Your characteristics
are: you have eyes, nose, ears, hands ,legs, heart, brain etc.
Your behavior is :” you can walk, talk, eat ,sleep, sing, dance. etc
Class:- A class is a blueprint that represents a set of similar objects.
Solved Questions
38
For example:
public class student
{
String Name;
int rollno;
String fname;
String DOB;
void getAdmission( )
{
……………
……………….
}
void getTransfer( )
{……………….
………………….
}
void feeDeposit( )
{
……………..
……………
}
Q3. What is the difference between instance and static variable?
Ans. Instance Variable:- These data member are created for every object of the class i.e. replicated
with objects.
Class Variable(Static):- These data members that is declared once for each class and all objects
share these members. Only a single copy is maintained in the memory. These are declared with
static keyword.
Q4. What do you understand by methods? What are the advantages of methods?
Ans. A method or function is sequence of statement which are written to perform a specific job in
the application. In object oriented Programming, Method represents the behavior of the object. A
message can be thought as a call to an object’s method. The following three advantages/reasons
describes that why we use methods.
To cope with complexity:
When programs become more complex and big in size, it is best technique to follows “Divide and
Conquer”. i.e. a complex problem is broken in to sm aller and easier task.,so that we can make it
manageable.
Hiding details:
Once a method is defined, it works like a Black-Board and can be used when required without
concerning that “How it Works?”
Reusability of code:
Once a method is implemented, it can be invoked or called from anywhere in the program when
needed i.e. Method can be reused. Even a packaged method may be used in multiple applications.
This saves our time and effort.
39
various Access Specifiers to control the accessibility of class members.
Private: A variable or method declared as private, may not be accessed outside of the class.
Only class member can access them, since they are private to others.
Protected: Protected members can be accessed by the class members and subclasses(derived
classes) and current package, but they are not accessible from beyond package or outside.
Public:-Class members declared as public are accessible to any other class i.e. everywhere, since
they are public.
Package(default):-if no any specifier is mentioned ,default or friendly access is assumed .Class
member may be accessed by any other class members available in the same package, but not
accessible by the other classes outside the package, even subclasses.
Private Access Specifier:-
Members declared as private are accessible by the members of the same class, since they are
private.
A private key word is used to specify.
class abc{
private int p;
private void method1()
{
P=10;
System.out.print(“ I am private method”);
}
}
class xyz
{
…
void method2()
{
abc x=new abc();
x.p=10;
x.method1();
}
}
Protected Access Specifier
Protected members are accessible by all the classes in the same package and subclasses (same or
different package).A protected keyword is used to specify. package mypackage;
class abc
{
protected int p;
protected void method1()
{
p=10;
System.out.print(“protected method”);
}
}
class xyz
{
40
…………..
void method2()
{ abc x=new abc();
x.p=10;
xmethod1();}
}
Lets another package..
package yourpackage;
import mypackage.*;
class pqr extends abc
{
void method3()
{
abc x =new abc();
pqr y=new pqr();
x.p=10;
x.method1();
y.p=10;
y.method1();
}
}
Public Access Specifier
Public Members can be access at anywhere i.e. same or different package.A public keyword is used
to specify.
package mypackage;
class abc
{
public int p;
public void method1()
{
p=10;
System.out.print(“public method”);
}
}
package ourpackage;
import mypackage.*;
class xyz
{……….
void method2()
{
abc x=new abc();
x.p=10;
x.method1();
}
}
41
Package (friendly) access specifier
If no specifier is explicitly specified, Java assumes default (friendly) access ie. All the members are
accessible in all other classes of the same package only, since they are trusted or friends. This is
called package level access. No any key word is used to specify default access. package
mypackage;
class abc
{
int p;
void method1()
{
p=10;
System.out.print(“package method”);
}
}
class xyz
{………………
void method2()
{
abc x=new abc();
x.p=10;
x.method1();
}
}
A set of ready-made software routines that can reused in new programs, is called in new programs,
is called a Library.
String Library:
1. Concat():- This method appends one String to the end of another. The method returns a
String with the value of the String passed in to the method appended to the end of the
String used to invoke this method.
Syntax: String concat(String s)
42
This would produce the following result
String Length is : 17
6. SubString() : This method returns a new string that is a substring of other string. The
substring begins with the character at the specified index and extends to the end of this
string or up to endIndex,- 1 if second argument is given.
43
String Str = new String("Welcome to KENDRIYA VIDYALAYA SECTOR-22 ROHINI");
System.out.print("Return Value :" );
System.out.println(Str.substring(11) );
System.out.print("Return Value :" );
System.out.println(Str.substring(11, 15) );
}
INHERITANCE :-
Inheritance is a act of deriving a new class from an existing one. Inheritance can be defined as the
process where one object acquires the properties of another. With the use of inheritance the
information is made manageable in a hierarchical order.. Basics of inheritance
When a class is defined in normal class declaration, it is called a base class. A class at the top of the
hierarchy is the base class and the other class is the derived class. That is a child class o one parent
can itself be the parent of another derived class. Furthermore, multiple classes can be
44
derived from a single parent..
Base class
Inherit
properties
Derived
Types of inheritance
1. Single inheritance
2. Multilevel
3. hierarchical
45
}
void newset(int n) //member function of base class
{
counter=n;
}
void factorial(void);
}
Child class
class childclass extends baseclass
{
public childclass()
{
}
void changecounter(int n)
{
newest(n);
factorial();
}
}
DEMONSTRATING INHERITANCE
class baseclass
{
int counter; Enter the number to find factorial
baseclass(){
counter=0; Factorial is
}
public void factorial()
factorialal exit
{
int i=1;
double fact=1.0;
for(i=1;i<=counter;i++)
fact=fact*i;
Txtfact.setText(Double.toString(fact));
}
}
class childclass extends baseclass
{
void changeval(int n)
{
counter=n;
}
}
46
On double click of factorial button
int n= Integer.parseInt(txtnum.getText());
Childclass obj1=new childclass();
Obj1.changeval(n);
Obj1.factorial();
Solved Questions :
1. What do you understand about inheritance? Write the advantages of inheritance. Ans.
Inheritance is a form of software reusability in which new classes are created form
existing classes by absorbing their attributes and behaviors and overriding these with
capabilities ,the new classes require.
The advantage is that, when creating a new class, instead of writing completely new data
members and members functions, the programmer can designate that the new class is to inherit
the data members and member function of a previously defined base class. The new class is
referred to as a derived class.
2. Describe the relationship between a parent class and a child class
Ans. A child class is derived from a parent class using inheritance. The methods and a variables
of the parent automatically become a part of the child class to the rules of the visibility
modifiers used to declare them.
3. How does inheritance support software reuse?
Ans. Because a new class can be derived from an existing one, the characteristics of the parent
class can be reused without the error prone process of copying and modifying code.
47
JAVA DATABASE CONNECTIVITY TO MYSQL:-
Important points
1. Classes used for Database Connectivity
(a) Driver Manager Class
(b) Connection Class
(c) Statement Class
(d) Resultset Class
2. Prerequisites for connecting to MYSQL from java
MYSQL provides connectivity for client application developed in the java programming
language via a JDBC driver known as MYSQL Connector/J.
3. Connection: A connection is the session between the application program and the database.
To do anything with database, one must have a connection object.
4. Connecting to MYSQL from Java:
Steps for creating Database Connectivity Application
There are mainly six steps:-
Step 1:- Import the packages required for database programming.
Step 2:- Register the JDBC Driver.
Step 3:- Open a connection
Step 4:- Execute a Query
Step 5:- Extract Data from resultSet.
Step 6:- Clean up the Environment.
Now to connect to a database, you need to know database’s complete URL, the user’s ID
and password:-
Jdbc:mysql://localhost/<database-name>?user=”userna me”&password=”password”
Result Set Methods
A result set(represented by a rEsult Set object) refers to a logical set records that are fetched
from the database by executing a query and made available to the application
program. There are various resultset methods such as:-
1. next() :-moves the cursor forward on row.
2. first ( ):- Moves the cursor to the first row in the resultset object.
3. last ( ):- Moves the cursor to the last row in the resultset object.
48
4. relative(in rows):- moves the cursor relative to its current position.
5. absolute (int r-no):- moves the cursor on the r-noth row of the resultset object.
6. getRow( ):- retrieves the current row number the cursor is pointing at. If cursor is at first
row the getRow() will return 1.
Solved Questions
Q1. What is the importance of java.sql.*; in java jdbc connection?
Ans. The java.sql.package has to be imported first before we can create a java jdbc
connection to the database.
Q2. What is Driver Manager?
Ans. DriverManager a class of java.sql package that controls a set of JDBC drivers.
Each driver has to be registers with this class.
Q.3 What is the purpose of connection.close() method?
Ans. This method is used for disconnecting the connection. It frees all the resources
occupied by the database.
Q4. Name the four component of JDBC?
Ans. JDBC consist of four component: The JDBC API, JDBC Driver Manager, JDBC
Test Suite and JDBC-ODBC bridge.
Q5. What is resultset?
Ans. A result set refers to a logical set of records that are fetched from the database by
executing a query and made available to the application program.
Q6 What type of parameter that used in executeQuery() method?
Ans. The executeQuery() method has a single String parameter.This parameter must be
valid SQL statement.
Q7. What is connection? What is its role?
Ans. A connection is the session between the application program and the datatbase.To
do anything with database, one must have a connection object.
Q8. Name the methods which are useful for executing SQL statements.
Ans. There are two methods which are responsible for executing SQL statements are:
a. executeQuery():-For sql statements that produce a single result set
b. executeUpdate():- for executing INSERT,UPDATE or DELETE statements and also
SQL DDL (Data Definition language) statements
49
WEB APPLICATION DEVELOPMENT:-
50
HTML-I : BASIC HTML ELEMENTS:-
The World Wide Web (or simply the Web or WWW) is a system of sharing interlinked
hypertext documents over the internet. These documents are stored on web-servers on the
internet and contain text, images, videos and other multimedia. These documents also contain
hyperlinks to navigate among them. HTML (Hyper Text Markup Language) is the basic
language which is used to create Hypertext documents. In this lesson we are going to learn
how to create hypertext documents using HTML.
51
HTML-II :LISTS, TABLES AND FORMS:-
<LI> list tag is used to denote the beginning of each new list item.
The TYPE attribute is used to change the bulleted symbol in a list. The attribute may have a
value of circle, disc, or square. For example, <UL TYPE=disk>.
The list items are marked with bullets (typically small black circles).
The START attribute is used to change the beginning value of an ordered list. Normally, the
ordered list starts with 1. For example, <OL START = A>
Table
A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the
<td> tag). The letters td stands for “table data”, which is the content of a data cell.
<Table> </Table> is used to specify that Table is to be created
Attributes which may be used in Table tag are Border, Align, Background, Bgcolor,
Height, Width etc.
<TR> </TR> is used to specify that table row is specified
<TD> </TD> is used to specify columns of the table by specifying Table Data.
e.g.
52
For example, we might want to create header cells for each department in our table of names and
phone numbers. In this table, the header cells in the first and fifth rows span across two columns to
indicate the department for each group of names.
<TABLE BORDER=2 CELLPADDING=4>
<TR> <TH COLSPAN=2>Production</TH> </TR>
<TR> <TD>Raha Mutisya</TD> <TD>1493</TD> </TR>
<TR> <TD>Shalom Buraka</TD> <TD>3829</TD> </TR>
<TR> <TD>Brandy Davis</TD> <TD>0283</TD> </TR>
<TR> <TH COLSPAN=2>Sales</TH> </TR>
<TR> <TD>Claire Horne</TD> <TD>4827</TD> </TR>
<TR> <TD>Bruce Eckel</TD> <TD>7246</TD> </TR>
<TR> <TD>Danny Zeman</TD> <TD>5689</TD> </TR>
</TABLE>
Production
Raha Mutisya 1493
Sales
Forms
HTML Forms are required when you want to collect some data from the site visitor. For example
during user registration you would like to collect information such as name, email address, credit
card, etc.
A form will take input from the site visitor and then will post it to a back-end application such as
CGI, ASP Script or PHP script etc. The back-end application will perform required processing on
the passed data based on defined business logic inside the application.
There are various form elements available like text fields, textarea fields, drop-down menus, radio
buttons, checkboxes, etc.
HTML Form Controls
There are different types of form controls that you can use to collect data using HTML form:
Text Input Controls
Checkboxes Controls
Radio Box Controls
Select Box Controls
File Select boxes
Hidden Controls
Clickable Buttons
Submit and Reset Button
Example:
<form method=”post” action=”datacollection.php”>
Name<input type=”text” name=”txtname”>
<br>
Name<input type=”text” name=”txtname”>
53
</form>
Similarly other form tags may be used . The visual example shows the FORM in the form of table
so form will be create dinside the table <td> tag. It basically nests the two major tags.
Problem 1
<html>
<body>
<P ALIGN =RIGHT>
<RIGHT><H1>PIZZA FACTORY</H1></RIGHT>
<form method="post">
<p aling=right
<right><h1><hr>PIZZA ORDER
FORM</hr></h1></right>
Name
<input type="text"name="name"/>
<br>
Address
<input type="text"name="address"/>
<br />
<p aling=right>
<right><h1>SIZE</h1></right>
</p>
<input type="radio" name="size" value ="small"/>small
<br />
<input type="radio" name="size" value ="medium"/>medium
<br />
<input type="radio" name="size" value ="large"/>large
<br />
54
<p aling=right>
<right><h1>TOPPINGS</h1></right>
</p>
<br />
<input type ="checkbox"name="s1" value="cheese">cheese
<br />
<input type ="checkbox"name="s2" value="olives">olives
<br/>
<input type ="checkbox"name="s3" value="pepperoni">pepperoni
<br />
<input type ="checkbox"name="s4" value="bacon">bacon
<br />
<p>
<input type="submit"name="request" value="process order">
<input type ="reset"name="clear"value="clear"> <br />
Problem 2
<html>
<body>
55
<form...>
first name:
<input type="text" name ="first_name" />
<br>
e.mail
<input type = "text" name ="e.mail" />
<p>select choose the one thing you love best of my pages</p>
<br>
<input type ="radio" name ="choose the one thing you love best of my pages"
value ="that gorgeous picture of you and your dogs"/> that gorgeous picture
value ="the inspiring recap about youe childhood" />the unspiring recap
value ="the detailed list of your hobbies"/>the detailed list of your hobbies
<br>
<p> Check all that apply:</p>
<input type ="checkbox" name = "s1" value ="i really like your web site"/>
i really like your web site
<br>
<input type ="checkbox" name = "s2" value ="one of the best site i've seen"/>
one of the best site i've seen<br>
<input type ="checkbox" name = "s3" value ="i have no taste so your site
didn't do much for me"/>i have no taste so your site didn't do much for me
56
<html>
<head>
<title>first page</title>
</head>
<body>
<table border=all>
<tr>
<td rowspan=3>A<br>C<br>G</td>
<td colspan=3>B</td>
</tr>
<tr>
<td>D</td>
<td>E</td>
<td rowspan=2>F</td>
</tr>
<tr>
<td colspan=2>H</td>
</td>
</table>
</form>
</body>
</html>
57
eXentensible Markup Language:-
2 HTML tags are predefined New tags can be created as per our
3 HTML may not have closing tags. XML must have closing tags.
4 HTML tags are not case sensitive XML tags are case sensitive.
5 HTML documents are directly viewable XML documents are viewed only if proper
in a browser. style sheet file is also available.
58
UNIT – 3
Relational Database Management System
MYSQL REVISION TOUR
A database system is basically a computer based record keeping system. There are different data
models are available. The most popular data model is Relational Data Model (RDBMS). In
RDBMS data is arranged in the form of table. MYSQL is software to manipulate database. It is
free, open- source RDBMS.
In order to access data within MYSQL database, all programs and users must use, Structured
Query Language (SQL).SQL is the set of commands that is recognized by nearly all RDBMs. SQL
commands can be classified into three categories. These are:
DDL (Data Definition Language)
DML (Data Manipulations Language) and
TCL (Transmission Control Language).
Apart from MYSQL is commands, it has various functions that performs some operation and
returns a single value.
59
The Network Data Model
o In this model data are represented by collection of records & relationships
among data. The collections of records are connected to one another by means of
links.
The Hierarchical Data Model
oIn this model records are organized as trees rather than arbitrary graphs.
Object Oriented Data Model
o Data and associated operations are represented by objects. An object is an
identifiable entity with some characteristics and behavior.
Relation:
oTable in Database
Domain:
oPool of values from which the actual values appearing
Tuple:
oAny single row of a relation
Attribute:
oAny column of relation
Degree:
oNumber of attributes(fields) in a relation
Cardinality:
oNumber of tuples(rows) in a relation
View:
o Virtual table that does not really exist in its own right but can be used to vies
Primary Key:
o Set of one or more attributes that can uniquely identify tuples with in the
relation.
Candidate Key:
o A Candidate Key is the one that is capable of becoming Primary key i.e., a
field or attribute that has unique value for each row in the relation.
Alternate Key:
oA candidate key that is not primary key is called alternate key.
Foreign Key:
o A non-key attribute, whose values are derived from the primary key of
some other table.
Integrity Constraints
o Integrity Constraints are the rules that a database must comply all the times. It
determines what all changes are permissible to a database.
60
DATA TYPES IN MySQL
61
Constraints name Description
Not Null and Default constraints can be applied only at column level rest all constraints can be
applied on both column level and table levels.
■ SELECT COMMAND:
The SELECT command is used to make queries on the database. A query is a command that is
given to produce certain specified information from the database table(s). The SELECT command
can be used to retrieve a subset of rows or columns from one or more tables. The syntax of Select
Command is:
SELECT <Column-list>
FROM <table_name>
[Where <condition>]
[GROUP BY <column_list>]
[Having <condition>]
[ORDER BY <column_list [ASC|DESC ]>]
62
Example:
SELECT * FROM ADDRESS WHERE SNo=100;
■ ORDER BY clause:
It is used to sort the results of a query. SELECT
<column name> [, <column name>, .] FROM
<table name>
[WHERE <condition>] [ORDER BY <column name>];
63
SELECT * FROM ADDRESS WHERE SNo>50 ORDER BY City;
■ SQL Constraint:
A Constraint is a condition or check applicable on a field or set of fields.
■ NOT NULL/UNIQUE/DEFAULT/CHECK/PRIMARY KEY/FOREIGN KEY Constraint:
CREATE TABLE student (rollno integer NOT NULL );
CREATE TABLE student (rollno integer NOT NULL, Sclass integer, Sname varchar(30),
Sclass DEFAULT 12 );
CREATE TABLE student (rollno integer CHECK (rollno>0), Sclass integer, Sname
varchar(30));
CREATE TABLE student (rollno integer NOT NULL PRIMARY KEY, Sclass integer,
Sname varchar(30));
CREATE TABLE teacher (Tid integer NOT NULL, FOREIGN KEY (Studentid )
REFRENCES student (Sid));
64
To delete all tuples from emp table:
DELETE FROM emp;
MySQL functions:
A function is a special type of predefined command set that performs some operation and
returns a single value.
Single-row functions return a single result row for every row of a queried table. They are
categorized into: Numeric functions, String functions, and Date and Time functions.
1) Numeric Functions
• POWER( ) : Returns the argument raised to the specified power. POW ( ) works the same
way.
Example: (i) POW(2,4); Result:16 (ii) POW(2,-2); Result:0.25 (iii) POW(-2,3) Result: -8
• ROUND( ) : ROUND(X) Rounds the argument to the zero decimal place, Where as
ROUND(X,d) Rounds the argument to d decimal places.
Example :(i) ROUND(-1.23); Result: -1 (ii) ROUND(-1.58); Result: -2
(iii) ROUND(1.58); Result: 2 (iv)ROUND(3.798, 1);Result: 3.8
(v) ROUND(1.298, 0); Result: 1 (vi) ROUND(23.298, -1); Result: 20
2) Character/String Functions
• LENGTH( ) : Returns the length of a string in bytes/no.of characters in string.
Example: LENGTH(‘INFORMATICS’); Result:11
• CHAR( ) : Returns the corresponding ASCII character for each integer passed.
Example : CHAR(65) ; Result : A
• CONCAT( ): Returns concatenated string i.e. it adds strings.
Example : CONCAT(‘Informatics’,’ ‘,‘Practices’); Result : Informatics Practices
65
• MID( )/SUBSTR( ) : Returns a substring starting from the specified position in a given
string.
Example: MID(‘INFORMATICS PRACTICES’,3,4); Result : FORM
3) Date/Time Functions
CURDATE( ) : Returns the current date
Example: CURDATE( ); Result:'2014-07-21'
66
Some of the most frequently used Aggregate functions in MySQL are:
S.No Name of the Function Purpose
■ The GROUP BY clause groups the rows in the result by columns that have the same values.
Grouping can be done by column name, or with aggregate functions in which case the
aggregate produces a value for each group.
■ The HAVING clause place conditions on groups in contrast to WHERE clause that place
conditions on individual rows. While WHERE condition cannot include aggregate functions,
HAVING conditions can do so.
■ ALTER TABLE COMMAND:-
The ALTER Table command is used to change the definition (structure) of existing table.
Usually , it can:
(i) Add columns to a table
(ii) Delete columns
(iii) Modify a column
The syntax of this command is:
For Add or modify column:
ALTER TABLE <Table_name> ADD/MODIFY <Column_defnition>;
For Delete column
ALTER TABLE <Table_name> DROP COLUMN <Column_name>;
Example :
To add a new column address in EMP table command will be :
ALTER TABLE EMP ADD (address char (30));
To modify the size of sal column in EMP table, command will be:
ALTER TABLE EMP MODIFY (sal number(9,2) );
67
To delete column Address from Table EMP the command will be:
ALTER TABLE EMP DROP COLUMN address;
• Cartesian Product (or Cross Join): Cartesian product of two tables is a table obtained by
pairing each row of one table with each row of the other. A Cartesian product of two tables
contains all the columns of both the tables.
• Equi-Join: An equi join of two tables is obtained by putting an equality condition on the
Cartesian product of two tables. This equality condition is put on the common column of the
tables. This common column is, generally, primary key of one table and foreign key of the other.
• Foreign Key: It is a column of a table which is the primary key of another table in the same
database. It is used to enforce referential integrity of the data.
• Referential Integrity: The property of a relational database which ensures that no entry in a
foreign key column of a table can be made unless it matches a primary key value in the
corresponding column of the related table.
• Union: Union is an operation of combining the output of two SELECT statements.
68
If you add a WHERE clause causing tables to be matched on the values of certain columns, the
join becomes what is known as an equi-join because you're selecting only rows with equal
values in the specified columns:
mysql> SELECT t1.*, t2.* FROM t1, t2 WHERE t1.i1 = t2.i2;
+---- +----+---- +---- +
| i1 | c1 | i2 | c2 |
+---- +----+---- +---- +
|2 |b |2 |c |
|3 |c |3 |b |
+---- +----+---- +---- +
The JOIN and CROSS JOIN join types are equivalent to the ',' (comma) join operator.
Solved Questions :-
Q1. Consider the following tables ACTIVITY and COACH. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (viii).
Table: ACTIVITY
ACode ActivityName ParticipantsNum PrizeMoney ScheduleDate
1001 Relay 100x4 16 10000 23-Jan-2004
1002 High jump 10 12000 12-Dec-2003
1003 Shot Put 12 8000 14-Feb-2004
1005 Long Jump 12 9000 01-Jan-2004
1008 Discuss Throw 10 15000 19-Mar-2004
Table: COACH
PCode Name ACode
1 Ahmad Hussain 1001
2 Ravinder 1008
3 Janila 1001
4 Naaz 1003
(i) To display the name of all activities with their Acodes in descending order.
(ii) To display sum of PrizeMoney for each of the Number of participants groupings (as shown
in column ParticipantsNum 10,12,16).
(iii)To display the coach’s name and ACodes in ascending order of ACode from the table
COACH.
(iv) To display the content of the GAMES table whose ScheduleDate earlier than 01/01/2004 in
ascending order of ParticipantNum.
(v) SELECT COUNT(DISTINCT ParticipantsNum) FROM ACTIVITY;
(vi)SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM ACTIVITY;
(vii) SELECT SUM(PrizeMoney) FROM ACTIVITY;
(viii) SELECT DISTINCT ParticipantNum FROM COACH;
Ans :
(i) SELECT ActivityName, ACode FROM ACTIVITY ORDER BY Acode DESC;
(ii) SELECT SUM(PrizeMoney),ParticipantsNum FROM ACTIVITY GROUP BY
ParticipantsNum;
69
(iii)SELECT Name, ACode FROM COACH ORDER BY ACode;
(iii) SELECT * FROM ACTIVITY WHERE ScheduleDate<’01-Jan-2004’ ORDER BY
ParticipantsNum;
(v) 3
(vi) 19-Mar-200412-Dec-2003
(vii) 54000
(viii) 16
10
12
Q2. Consider the following tables GAMES and PLAYER. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (viii).
Table: GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004
Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103
70
Q3. Consider the following tables HOSPITAL. Give outputs for SQL queries (i) to (iv) and
write SQL commands for the statements (v) to (viii).
Q4. Consider the following tables BOOKS. Write SQL commands for the statements (i) to (iv)
and give outputs for SQL queries (v) to (viii).
Table : BOOKS
B_Id Book_Name Author_Name Publisher Price Type Quantity
C01 Fast Cook Lata Kapoor EPB 355 Cookery 5
F01 The Tears William First 650 Fiction 20
Hopkins
71
T01 My C++ Brain & FPB 350 Text 10
Brooke
T02 C++ Brain A.W.Rossaine TDH 350 Text 15
F02 Thuderbolts Anna Roberts First 750 Fiction 50
i). To list the names from books of Text type.
ii). To display the names and price from books in ascending order of their price.
iii). To increase the price of all books of EPB publishers by 50.
iv). To display the Book_Name, Quantity and Price for all C++ books.
v). Select max(price) from books;
vi). Select count(DISTINCT Publishers) from books where Price >=400;
vii).Select Book_Name, Author_Name from books where Publishers = ‘First’;
viii).Select min(Price) from books where type = ‘Text’;
Q5. Consider the tables ITEMS & COMPANY. Write SQL commands for the statements (i) to
(iv) and give the outputs for SQL queries (v) to (viii).
Table : ITEMS
ID PNAME PRICE MDATE QTY
T001 Soap 12.00 11/03/2007 200
T002 Paste 39.50 23/12/2006 55
T003 Deodorant 125.00 12/06/2007 46
T004 Hair Oil 28.75 25/09/2007 325
T005 Cold Cream 66.00 09/10/2007 144
T006 Tooth Brush 25.00 17/02/2006 455
Table : COMPANY
ID COMP City
T001 HLL Mumbai
T008 Colgate Delhi
T003 HLL Mumbai
T004 Paras Haryana
T009 Ponds Noida
T006 Wipro Ahmedabad
72
i). To display PNAME, PRICE * QTY only for the city Mumbai.
ii). To display product name, company name & price for those items which IDs are equal to the
IDs of company.
iii). To delete the items produced before 2007.
iv). To increase the quantity by 20 for soap and paste.
v). SELECT COUNT(*) FROM ITEMS WHERE ITEMS.ID=COMPANY.ID;
vi). SELECT PNAME FROM ITEMS WHERE PRICE=SELECT MIN(PRICE) FROM ITEMS;
vii). SELECT COUNT(*) FROM COMPANY WHERE COMP LIKE “P_ _ _ _”;
viii). SELECT PNAME FROM ITEMS WHERE QTY<100;
Ans :
(i) SELECT PNAME, QTY*PRICE FROM ITEMS
WHERE ITEMS.ID = COMPANY.ID AND COMPANY.City=’Mumbai’;
(ii) SELECT PNAME, COMP, PRICE FROM ITEMS, COMPANY
WHERE ITEMS.ID = COMPANY.ID;
(iii) DELETE FROM ITEMS WHERE MDATE < {01/01/2007};
(iv) UPDATE ITEMS SET QTY = QTY + 20
WHERE PNAME = ‘Soap’ OR PNAME = ‘Paste’;
(v) 4
(vi) Soap
(vii) 2
(viii) Paste
Deodorant
Unsolved Problems :
2. Consider the table STUDENT given below, write SQL Commands for (i) to (iv) and
output for (v) to (viii)
73
(i) To Display all information about class XII students.
(ii) List the name of made student of class X.
(iii) List names all class of all students in descending order of DOB.
(iv) To count the number of student in XII Class of Mumbai city.
(v) SELECT DISTINCT(Sex) FROM Student.
(vi) SELECT AVERAGE(Marks) FROM Student GROUP BY Sex.
(vii) SELECT COUNT(*)FROM Student where Class = ‘XI’
(viii) SELECT MAX(Marks) FROM Student.
3. (a) Write an SQL query to create the table books with following structure.
(b) Following two tables are shown below are preset in database-
BOOK
EID EbookName Author
3 Internal terms Okhla
4 RDBMS Steve
5 NetBeans Gosling
COST
Subj ID EID Cost
E40 1 2000
E41 4 1700
E42 3 1800
E43 5 1250
74
Client
CID CliName City PID
01 Rakesh Delhi TP01
02 Prakash Mumbai TP05
03 Suresh Delhi TP03
04 Dinesh Delhi TP02
05 Pravesh Banglore TP04
Table : issued
Book_Id Quantity Issued
T0001 4
C0001 5
F0001 2
75
5. Write the SQL query commands based on following table
Table : SchoolBus
Rtno Area_overed Capacity Noofstudents Distance Transporter Charges
1 Vasant kunj 100 120 10 Shivamtravels 100000
2 Hauz Khas 80 80 10 Anand travels 85000
3 Pitampura 60 55 30 Anand travels 60000
4 Rohini 100 90 35 Anand travels 100000
5 Yamuna Vihar 50 60 20 Bhalla Co. 55000
6 Krishna Nagar 70 80 30 Yadav Co. 80000
7 Vasundhara 100 110 20 Yadav Co. 100000
8 Paschim Vihar 40 40 20 Speed travels 55000
9 Saket 120 120 10 Speed travels 100000
10 Jank Puri 100 100 20 Kisan Tours 95000
(b) To show all information of students where capacity is more than the no of student in order of
rtno.
(c) To show area_covered for buses covering more than 20 km., but charges less than 80000.
(d) To show transporter wise total no. of students traveling.
(e) To show rtno, area_covered and average cost per student for all routes where average cost
per student is - charges/noofstudents.
(f) Add a new record with following data:
(11, “ Moti bagh”,35,32,10,” kisan tours “, 35000)
(g) Give the output considering the original relation as given:
(i) select sum(distance) from schoolbus where transporter= “ Yadav travels”;
(ii) select min(noofstudents) from schoolbus;
(iii) select avg(charges) from schoolbus where transporter= “ Anand travels”;
(iv) select distinct transporter from schoolbus;
76
(e) Give the output of following sql statement based on table GRADUATE:
(i) Select MIN(AVERAGE) from GRADUATE where SUBJECT=” PHYSICS”;
(ii) Select SUM(STIPEND) from GRADUATE WHERE div=2;
(iii) Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;
(iv) Select COUNT(distinct SUBDJECT) from GRADUATE;
(f) Assume that there is one more table GUIDE in the database as shown below:
Table: GUIDE
MAINAREA ADVISOR
PHYSICS VINOD
COMPUTER SC ALOK
CHEMISTRY RAJAN
MATHEMATICS MAHESH
g) What will be the output of the following query:
SELECT NAME, ADVISOR FROM GRADUATE, GUIDE
WHERE SUBJECT= MAINAREA;
7. Write SQL command for (i) to (vii) on the basis of the table SPORTS
Table: SPORTS
Student NO Class Name Game1 Grade Game2 Grade2
10 7 Sammer Cricket B Swimming A
11 8 Sujit Tennis A Skating C
12 7 Kamal Swimming B Football B
13 7 Venna Tennis C Tennis A
14 9 Archana Basketball A Cricket A
15 10 Arpit Cricket A Atheletics C
(a) Display the names of the students who have grade ‘C’ in either Game1 or Game2 or both.
(b) Display the number of students getting grade ‘A’ in Cricket.
(c) Display the names of the students who have same game for both Game1 and Game2.
(d) Display the games taken up by the students, whose name starts with ‘A’.
(e) Assign a value 200 for Marks for all those who are getting grade ‘B’ or grade ‘A’ in both
Game1 and Game2.
(f) Arrange the whole table in the alphabetical order of Name.
(g) Add a new column named ‘Marks’.
8. Write SQL command for (i) to (vii) on the basis of the table Employees & EmpSalary
77
Table: Employees
Empid Firstname Lastname Address City
010 Ravi Kumar Raj nagar GZB
105 Harry Waltor Gandhi nagar GZB
152 Sam Tones 33 Elm St. Paris
215 Sarah Ackerman 440 U.S. 110 Upton
244 Manila Sengupta 24 Friends street New Delhi
300 Robert Samuel 9 Fifth Cross Washington
335 Ritu Tondon Shastri Nagar GZB
400 Rachel Lee 121 Harrison St. New York
441 Peter Thompson 11 Red Road Paris
Table: EmpSalary
Empid Salary Benefits Designation
010 75000 15000 Manager
105 65000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
441 28000 7500 salesman
Write the SQL commands for the following :
(i) To show firstname,lastname,address and city of all employees living in paris
(ii) To display the content of Employees table in descending order of Firstname.
(iii) To display the firstname,lastname and total salary of all managers from the tables
Employee and empsalary , where total salary is calculated as salary+benefits.
(iv) To display the maximum salary among managers and clerks from the table Empsalary.
78
DATABASE TRANSACTIONS
79
SOLVED QUESTIONS
1. What are the two ways in which multiple transactions can be executed?
Ans. - Multiple transactions can be executed in one of the following two ways:
(i) Serially (ii) Concurrently
2. What is a savepoint?
Ans. - Savepoints are special operations that allow you to divide the work of a
transaction into different segments. In case of a failure, you can execute rollbacks to the
savepoint only, leaving prior changes intact.
3. What to you understand by a database transaction?
Ans. - A database transaction is a logical unit of work that must succeed or fail in its
entirely.
4. Why do understand by transaction COMMIT and ROLLBACK?
Ans-COMMITing a transaction means all the steps of a transaction are carried out
successfully and all data changes are made permanent in the database. Transaction
ROLLBACK means transaction has not been finished completely and hence all data
changes made by the transaction in the database if any, are undone and the database returns
to the state as it was before this transaction execution started.
5. What do you understand by ACID properties of database transaction?
Ans. -To ensure the data-integrity, the database system maintains the following properties of
transaction. The properties given below are termed as ACID properties-an acronym derived
from the first letter of each of the properties.
(i) Atomicity-This property ensures that either all operations of the transactions are
reflected properly in the database, none are. Atomicity ensures either al-or-none
operations of a transaction are carried out.
(ii) Consistency-This property ensures that database remains in a consistent state before
the start of transaction and after the transaction is over.
(III) isolation-Isolation ensures that executing transaction execution in isolation i.e. is
unaware of other transactions executing concurrently in the system.
(IV) Durability-This property ensures that after the successful completion of a
transaction i.e. when a transaction COMMITs, the changes made by it to the
database persist i. e remain in the database irrespective of other failures.
6. What the function is of redo and undo logs?
Ans. -Every database has a set of redo log files. It records all change in data including both
committed and uncommitted changes. Undo logs stored roll backed data.
7. What TCL commands are supported by SQL?
Ans. -SQL supports following TCL commands
BEGIN |START TRANSACTION-Marks the beginning of a transaction
COMMIT-Ends the current transaction by saving database changes and starts a new
transaction.
ROLLBACK-Ends the current transaction by discarding changes and starts a new
transaction.
80
SAVEPOINT-Defines breakpoints for the transactions to allow partial rollbacks.
SET AUTOCOMMIT-Enables or disable the default autocommit mode.
8. Which two statements complete a transaction?
a. DELETE employees;
b. DESCRIBE employees;
c. ROLLBACK TO SAVEPOINT C;
d. GRANT SELECT ON employees TO SCOTT;
e. ALTER TABLE employees
MODIFY COLUMN sal;
f. Select MAX(sal)
FROM employees
WHERE department_id=20;
Ans. - C, E
UNSOLVED QUESTIONS
1. What is the benefit of transaction?
2. Define a transaction.
3. What are the five states of the transactions?
4. What will happen when COMMIT statement is issued?
5. What will happen when ROLLBACK statement is issued?
6. How can you start a new transaction?
81
UNIT-4
IT- Applications
Brief Summary
Three major groups of IT applications covered in this chapter are: e-Governance,e-Business, and e-
Learning.
e-Governance involves applications which are used by government agencies/ organizations
to provide better governance.
e-Business applications use technology to effectively access and deliver business
related services and perform various kinds of business transactions.
e-Learning applications use technology to effectively deliver and monitor learning and
teaching processes. They help the trainer to organize and manage his/her lesson plans,
present them to students/learners, evaluate and take the feedback to enhance & fine-tune this
process in future.
An IT application has two major parts: Front-end (The user interface) and back-end(The
database).
The front-end of an IT application is usually a group of one or more forms through which
the user enters the input values and is shown the corresponding output.
The back-end of an IT application is the database in which all the data is stored. This
database resides in the server. All the data which is requested by the front-end is supplied by
back-end. A good back-end ensures sustainability, efficiency and easy modification of the
application.
ICT stands for Information and Communication Technology. Like everything else that is used
by common man, ICT (Information and Communication Technology) also has impacted the society.
ICT has impacted the society in a much wider way than any other technology. Most of these
impacts are positive, though there are some negative impacts also.
Social and Economic benefits of ICT:
• Social networking sites help people remain in touch with their nears and dears even when
they are staying on opposite sides of the globe.
• Social networking sites help like-minded people come together and work for some cause.
• e-Governance sites help people save their productive time by performing various
government related jobs like getting some forms, depositing bills online.
• ICT helps economy grow at a faster rate as it provides transparency in the processes and
helps the government to keep check on defaulters.
• Due to e-Banking and use of plastic money more money is put in circulation leading to
faster growth of GDP.
• e-Learning sites make quality study material available even to the students staying at
remote places.
e-Business- To reach the customers and business associates in an effective and fast manner business
houses (now a days many small shops like snacks corners and paan shops also) provide their
services on the net.
82
These ICT enabled counters are used to get orders and feedbacks from the customers and also for
inter-business transactions. This helps the businesses to widen their customer base.
1. Amazon.com ( e-Business site of Amazon.com) - Amazon is the world's largest online
store. Through this URL Amazon does its online business
2. flipkart.com – Very popular online shopping stor e offering a range of products at very
reasonable prices.
e-Learning : e-Learning has multiple goals. It is much more than having a net connection and/or
CDs through which people learn. E-Learning is about giving freedom to people to learn whatever
they want to learn and whenever they want to learn. This is irrespective of (except in exceptional
cases) age, caste, gender, economical background, or qualification of the learner. The only
requirement is the will to learn. E-learning is available on almost all the topics imaginable.
1. www.khanacedemy.com (e-Learning site) - You will access free tutorials in all web
development technologies and almost on any topic of learning from a vast variety of subjects.
Matter is available in interactive video formats.
2. www.cbsecsnip.in - It is an educational site where subject content and solved papers are present
along with sample projects , from which students can benefit.
3. www.kvselearning.in- This portal provides interactive modules for students to learn various
topics on informatics practices using interactive video lessons.
Q. What are Front-end (The user interface) and back-end (The database) ?
Answer : An IT application has two major parts: Front-end (The user interface) and backend (The
database) .The front-end of an IT application is usually a group of one or more forms through
83
which the user enters the input values and is shown the corresponding output. A good front-end
ensures the acceptance of the application in the first go. The back-end of an IT application is the
database in which all the data is stored. This database resides in the server.
All the data which is requested by the front-end is supplied by back-end. A good back-end
ensures sustainability, efficiency and easy modification of the application.
Q. Is it a good practice to take in the inputs using Text Fields only? Justify your answer.
Answer : Text Field is used to get small textual information like Name, RollNo, email address,
quantity, etc. Disabled/Uneditable Text Fields are also used to display such information so it is a
good practice to take in the inputs using Text Fields. But we may also use Dialog to take input.
84
English can also have access to the information. Language should not be a hindrance but a support
to learning.
Understanding the importance of regional languages, many websites have also provided translation
services so that the same page can be viewed in any language of user's choice.
Q. What Components are used for creating Front-end of any software? Give details about those
components.
Ans: To create a front-end various components, like those studied in Java GUI application
development, are used. Some of the most commonly used components are discussed below:
Text Field: Text Field is used to get small textual information like Name, RollNo, email
address, quantity, etc.
Text Area: Text Area is used to get long textual information which may span multiple lines
of text. E.g. to get Address, Complaint, Suggestion etc.
Radio Button: Radio buttons are used to get an option out of several mutually exclusive (out
of which only one can be selected) options. Examples of such options are Gender (Male or
Female or Other), Type of Credit Card (Master or Visa or Other), Type of internet
connection (DialUp or Braodband), etc.
Check Box: Check boxes are used to get one or more options out of several given options
which are not mutually exclusive. Examples of such options are Hobbies (a user may have
zero or more hobbies), Magazines to subscribe for (a user may subscribe to zero or more of
the given magazines) etc.
List: A list is used to get one or more options out of several given options which may or
may not be mutually exclusive. This may seem to be the case where Check Boxes are to be
used, but the difference is in the number of options available. If the number of options is
small, then Check Boxes can be used. In case of large number of options, using Check
Boxes may take up a lot of space on the form and it may also be inconvenient for the user to
select the desired options. In such cases Lists are preferred over checkboxes. Examples of
such cases are: To select cities out of a given list of cities, to select magazines out of a given
list of magazines, etc.
Combo Box: A Combo Box is used to get an option out of several given options which are
mutually exclusive. This may seem to be the case where Radio Buttons are to be used, but
the difference is in the number of options available. If the number of options is small, then
85
Radio Buttons can be used. In case of large number of options, using Radio Buttons may
take up a lot of space on the form and it may also be inconvenient for the user to select the
desired option. In such cases Combo Boxes are preferred over radio buttons. Examples of such
cases are: To select a city out of a given list of cities, to select a train out of a given list of trains, etc.
Password Field: A Password Field is used to get some secret textual information like
Password, CVV number of a credit card etc.
86
Sample Paper
Subject : Informatics Practices (065)
Time Allowed : 3 hours Class: XIIth Max. Marks : 70
1 (a) Which Protocol is used for the transfer of hypertext document on the internet? 1
(b) Two doctors in the same room have connected their Palm Tops using Bluetooth for working
on a Group presentation. Out of the following, what kind of Network they have formed? 1
LAN, MAN, PAN, WAN
(c) Arrange the following communication channels in ascending order of their data transmission
rates.
Ethernet Cable, Optical Fiber, Telephone Cable, Co-axial Cable 1
(d) Which of the following are open standards? 1
(i) .OGG (ii) .DOC (iii) .TTF (iv) . JPEG
(e) Jai Khanna is confused between the terms Domain Name and URL. Explain the difference
with the help of appropriate examples of each. 2
(f) Define any two threats to Network Security. 2
(g) Differentiate between Star and Bus Topology of networks. 2
2 (a) While working in Netbeans, Ms Kanta Surbhi wants to display 'Cleared' or'Re-attempt
required' message depending the marks entered in jTextField. Help her to choose more
appropriate statement out of 'If statement' and 'Switch statement' 1
(b) What is the purpose of break statement in a loop? 1
(c) How is <UL> tag different from <OL> tag of HTML? 1
(d) What is the use of <H1> tag in an HTMT document? 1
(e) How many times are the following loops executed? 2
int num=5;
do
{
System.out.println(num+1);
num- -;
} while (num !=0);
(f) Differentiate between HTML and XML. 2
(g) Write Java code that takes the price of a pencil from jTextField1 and quantity of pencils
from jTextField2 and calculates total amount as price * quantity to be displayed in
jTextField3 and also find 10% tax amount to be displayed in jTextField4. 2
3 (a) If a database "Student" exists, which MySql command helps you to start working in that
database? 1
(b) Sahil created a table in Mysql. Later on he found that there should have been another
column in the table. Which command should he use to add another column to the table? 1
(c) Pooja, a student of class XI, created a table "Book". Price is a column of this table. To find
the details of books whose prices have not been entered she wrote the following query: 1
Select * from Book where Price = NULL;
Help Pooja to run the query by removing the errors from the query and rewriting it.
(d) Rama is not able to change a value in a column to NULL. What constraint did she specify
87
when she created the table? 1
(e) Distinguish between a Primary key and Candidate key with the help of suitable example of
each. 2
(c) What will be displayed in jTextArea1 after executing the following statement? 1
jTextAreal.setText ("cbse\nFinal_Exam \ tIp") ; .
88
i = i +1;
}
(e) Given a String object namely 'subject' havingvalue as “123” stored in it. What will be result
of the following? 1 JOptionPane.showMessageDialoge (null, " " + (subject.length ( ) +
Integer.parselnt (subject)));
(f) The following code has some error(s). Rewrite the correct code underlining all the corrections
made: 2 int Sum=0, Step=5 ;
int I ;
for (i = 0, i =<5, i++)
{
Step+=5,
Sum+=Step ;
}
jTextAreal.showText{" "+Sum) ;
(g) Mr. Radhey Shyam Bansal the owner of the Kiddi Land Enterprises has asked his programmer
Ekta to develop the following GUI in Netbeans:
Mr. Ram accepts payment through three types of credit cards. The offers is given according to the
following scheme:
Type of Card Offer
Platinum 20% of amount
Gold 15% of amount
Silver 10% of amount
89
If the Bill amount is more than Rs, 25,000, then the customer gets an additional discount of 5%.
Write Java code for' the following:
(i) To assign Additional Discount as 0 (jTextField4) and Net Amount as 0 (jTextField5). Also set
them as un-editable. 2
5 (a) Explain the purpose of DDL and DML commands used in SQL. Also give two examples
of each. 2
(c) Consider the table SPORTS given below. Write commands in SQL for (i) to (iv) and
output for (v) to (viii) 6
Table : SPORTS
StudentNo Class Name Game1 Grade1 Game2 Grade2
10 7 Sammer Cricket B Swimming A
11 8 Sujit Tennis A Skating C
12 7 Kamal Swimming B Football B
13 7 Venna Tennis C Tennis A
14 9 Archana Basketball A Cricket A
15 10 Arpit Cricket A Athletics C
(i) Display the names of the students who have grade ‘A’ in either Game1 or Game2 or
both.
(ii) Display the number of students having game ‘Cricket’.
(iii) Display the names of students who have same game for both Game1 and Game2.
(iv) Display the games taken by the students whose name starts with ‘A’.
(v) SELECT COUNT(*) FROM SPORTS.
(vi) SELECT DISTINCT Class FROM SPORTS.
90
(vii) SELECT MAX(Class) FROM STUDENT;
(vii) SELECT COUNT(*) FROM SPORTS GROUP BY Game1;
6 (a) Write an SQL query to create the table 'Item'with the following structure: 2
Field Type Constraint
ItemCode Varchar(5) Primary Key
ItemName Varchar(20)
Category Varchar(20)
Price Decimal(5,2)
Customer
CustNo SetNo CustAddress
1 N2 Delhi
2 B1 Mumbai
3 N2 Mumbai
4 N1 Kolkata
5 B1 Delhi
With reference to these tables, Write commands in SQL for (i) and (ii) and output for (iii)
below:
(i) Display the CustNo, CustAddress and corresponding SetName for each customer. 2
(ii) Display the Customer Details for each customer who uses a Nokia handset. 2
(iii) Select SetNo, SetName 2
from Handsets, customer
where SetNo = SetCode
and CustAddress = 'Delhi';
(c) Answer the following questions based on above given two tables (i.e. Handsets
& Customer) 2
(i) How many rows and how many columns will be there in the Cartesian product of these two
tables?
(ii) Which column in the 'Customer' table is the foreign key?
91
(i) A message "Enter Marks" in front of a Text Field.
(ii) An input to choose more than one subject from a set of choices.
(iii) An input for entering remarks
(iv) An input for accepting Gender.
92
Marking Scheme
93
(f)
HTML XML
Defines how webpage is displayed Defines, stores and retrieves the data
HTML tags are predefined XML tags are not predefined.
New tags cannot be defined New tags can be created as per need
HTML tags may not have closing tag XML tags must have a closing tag.
HTML tags are not case-sensitive. XML tags are case-sensitive.
(1 mark each for any 2 correct differences)
4. (a) 32
(2 marks for correct answer)
(b) switch (code)
{
94
case 1: Month = "January";
break;
case 2: Month = "February";
break; .
case 3: Month = "March";
break;
case 4: Month = "April";
break;
default: Month = "No Match";
}
(02 marks for correct answer)
(c) cbse
Final_Exam<tab>IP
OR
cbse
Final_Exam IP
(1 mark for correct output)
(d) int i, sum = 0;
for ( i=1; i<10; i++)
sum = sum + i ;
( 1 mark for correct answer )
(e) 126
(1 mark for correct answer)
(f) int Sum = 0, Step = 5;
int i;
for (i=0 ; i <= 5 ; i++)
{
Step + = 5;
Sum + = Step;
}
jTextAreal.setText ("" + Sum);
(2 marks for correcting any four errors or 1 mark for only identifying any four
errors - without making any correction)
g (i) jTextField4.setText ("0") ;
jTextField5.setText ("0") ;
jTextField4.setEditable(false) ;
jTextField5. setEditable(false) ;
(½ mark for assigning 0 to each of the textfields)
(½ mark for setting each textfield as un-editable)total 02 marks
(ii) double discount = 0.0 ;
double billAmount = Double.parseDouble(jTextField2.getText());
if (jRadioButton1.isSelected())
discount = 0.20;
if (jRadioButton2.isSelected())
discount = 0.15;
95
(jRadioButton3.isSelected())
discount = 0 .10;
jTextField3.setText(billAmount * discount + “ “) ;
if (billAmount > 25000)
jTextField4.setText (billAmount*0.05+ );
jButton2.setEnabled(true) ;
(1 mark for calculating discount correctly)
(½mark for calculating additional discount correctly)
(½mark for enabling the button)
(Any Object names are acceptable for JRadioButton objects)
(iii) doube netAmount = Double.parseDouble(jTextField2.getText()) -
Double.parseDouble(jTextField3.getText()) -
Double.parseDouble(jTextField4.getText()) ;
jTextField5.setText(netAmount + " ") ;
(2 marks for calculating the net amount)
5 (a) DDL: Data Definition Language. DDL commands are used to create, destroy, and to
restructure the database objects.
Example: CREATE, ALTER (or any other two correct examples)
DML: Data Manipulation Language. DML commands are used to insert, delete and
change data in tables.
Example: SELECT, DELETE (or any other two correct examples)
(½ Mark each for purpose and examples of DDL)
(½ Mark each for purpose and examples of DDL)
(b)
i) 9
ii) RDBMS MYSQL
iii) 1
iv) 7
( ½ Mark for each correct output )
(c)
(i) Select Name from SPORTS where Grade1=’A’ OR Gra de2=’A’;
(ii) Select count(*) from SPORTS Where Game1=’Cricket’ OR Game2=’Cricket’;
(iii) Select Name from SPORTS where Game1=Game2;
(iv) Select Game1,Game2 from SPORTS where Name LIKE ‘A%’;
( 1 Mark for each correct sql statement )
(v) 6
(vi) 7
8
9
10
(vii) 10
(viii) 2
2
1
1
( ½ Mark for each correct output )
96
6 (a) CREATE TABLE Item
(itemcode varchar(5) primary key,
itemname varchar(20),
category varchar(20),
price decimal(5,2));
( ½ Mark for CREATE TABLE Item)
( ½ Mark for appropriately putting Primary Key constraint)
( ½ Mark for correct data types)
( ½ Mark for correct syntax of the query)
97
(c)
(i) Label
(ii) ListBox/Check Box
(iii) TextArea [Most Appropriate answer] TextField [Also acceptable]
(iv) RadioButton
( ½ marks for each correct answer)
*****************
98
Previous Year (2014) CBSE Question Paper
99
100
101
102
103
104
105
106