149
1. UNIT 1: NETWORKING AND OPEN STANDARDS Computer Network:- A computer network is a collection of interconnected computers and other devices which are able to communicate with each other and share hardware and software resources. Need For Networking 1. Load sharing 2. Data transformation 3. Reliability 4. Cost factor 5. Sharing of resources 6. Flexible working environment Application of Networks 1. Sharing of data, services and resources 2. Access to remote database 3. Communication facilities Elementary Terminology of Networks 1. Nodes (Workstations):- The term nodes refer to the computers that are attached to a network and are seeking to share the resources. 2. Server:- A computer that facilitates the sharing of data, software and hardware resources on the network 3. Network Interface Unit (NIU) (MAC Address):- A network interface unit is interpreter that helps in establishing the communication between the server and the client. 4. IP Address:- Every machine on a TCP bar IP Network has a unique identifying no. called an IP Address.

dsUnzh; fo|ky; laxBudavbhilai.org/downloads-file/IP_study_material.docx  · Web viewDoc, .docx, .ppt etc) Media format (e.g. .wma,.wmvetc) Apple Media formats (such as .mov) are

  • Upload
    lamdat

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

1.

UNIT 1: NETWORKING AND OPEN STANDARDS

Computer Network:- A computer network is a collection of interconnected computers and other devices which are able to communicate with each other and share hardware and software resources. Need For Networking 1. Load sharing

2. Data transformation

3. Reliability

4. Cost factor

5. Sharing of resources

6. Flexible working environment

Application of Networks

1. Sharing of data, services and resources

2. Access to remote database

3. Communication facilities

Elementary Terminology of Networks

1. Nodes (Workstations):- The term nodes refer to the computers that are attached to a network and are seeking to share the resources.

2. Server:- A computer that facilitates the sharing of data, software and hardware resources on the network

3. Network Interface Unit (NIU) (MAC Address):- A network interface unit is interpreter that helps in establishing the communication between the server and the client.

4. IP Address:- Every machine on a TCP bar IP Network has a unique identifying no. called an IP Address.

5. Domain Name:-It is a way to identify and locate the computers connected to the internet. It must be unique.

Communication/Transmission Media:- A transmission medium is a medium of data transfer over a network. It can be wired or wireless.

Wired Media – A number of various types of cables are used to transfer data over computer networks. These are Twisted Pair Cable, Co-axial Cable, and Optical Fiber Cable. Twisted Pair Cable- It contains four twisted pairs covered in an outer shield. These pairs are color coded. An RJ-45 connecter is used to connect this cable to a computer. It is of two types: 1. UTP (Unshielded Twisted Pair): individual pairs are not shielded.

Characteristics of UTP cable: • low-cost cable available for setting up small networks. • a thin (External diameter app. 0.43cm) and flexible cable and therefore it offers ease

of installation. • can carry data up to a length of 100m at a stretch.

2. STP (Shielded Twisted pair): It is the same cable as the UTP, but with each pair shielded

individually. An outer shield then covers all the pairs like in UTP. Characteristics of STP cable:

• As compared to UTP, STP offers better immunity against internal and external electromagnetic interferences.

• expensive than UTP cable. • As compared to UTP cable, STP cable is difficult to install.

Coaxial Cable (or coax):It consists of two conductors that share a common axis. The inner conductor is a straight wire and the outer conductor is a shield that might be braided or a foil. Characteristics of Co-axial cable:

• It can carry data for a larger distance (185m - 500m) at a stretch. • Less susceptible to electromagnetic fields

• Bulkier and less flexible than twisted pair. • Due to its thickness (1cm diameter) and less flexibility, it is difficult to install as

compared to twisted pair cable. Optical Fiber Optical Fibers are long, thin strands of glass about the thickness of a human hair. They are arranged in bundles called optical fiber cables and used to transmit data through light signals over long distances. Characteristics of Optical Fiber Cable:

• It can carry data for a very large distance at a stretch. • Not susceptible to electromagnetic fields • Especially skilled people are required to install optical fiber cables. • Till date it is the most expensive and at the same time the most efficient cable

available for computer networks.

Wireless Media Electromagnetic waves are used for wireless communication over computer networks. Based on their frequencies, electromagnetic waves are categorized into various categories. These

categories are (in increasing order of frequencies): radio waves, microwaves, infrared radiation, visible light, ultraviolet radiation, X-rays, and Gamma rays. Out of these only radio waves, microwaves, and infrared rays are used for wireless communication.

Radio Waves - Radio waves have a frequency range of 3 KHz to 3GHz. Radio waves are used for communication over distances ranging from a few meters (in walkie-talkies) up to covering an entire city. These waves are easy to generate, can travel long distances and can penetrate buildings easily. Cordless phones, AM and FM radio broadcast, Garage door openers etc. are examples of radio wave transmission.

Characteristics of Radio Wave Transmission:

• These waves are omni-directional.

• Relatively inexpensive than wired media.

• It offers ease of communication over difficult terrain

• The transmission can be interfered by motors or other electrical equipment

• Permission from concerned authorities is required for use of radio wave transmission • Less secure mode of transmission

Micro Waves - Microwaves travel in straight lines and cannot penetrate any solid object.

Therefore for long distance microwave communication, high towers are built and microwave

antennas are put on their tops. Distance between two microwave towers depends on many

factors including frequency of the waves being used and heights of the towers. These waves

travel in straight lines and therefore the sending and receiving antennas have to be aligned with

each other.

Characteristics of Micro Wave Transmission:

• Free from land acquisition rights • Relatively inexpensive than wired media • Offers ease of communication over difficult terrain • The transmission is in straight lines so the transmitting and receiving antennas need

to be properly aligned ( line of sight transmission) Infrared Waves - Infrared waves have a frequency range of 300 GHz to 400 THz. Infrared waves are so called because they have a frequency range of just less than that of red light. These waves are used for short range communication (approx. 5m) in a variety of wireless communications, monitoring, and control applications. Home-entertainment remote-control devices, Cordless mouse, and Intrusion detectors are some of the devices that utilize infrared communication.

Characteristics of Infrared Wave Transmission:

• It is a line of sight transmission; therefore information passed to one device is not leaked to another device.

• No government license is required for their use • It is a line of sight transmission, therefore at a time only two devices can

communicate.

• The waves do not cross any solid object in between • Performance drops with longer distances

Bluetooth - Bluetooth technology uses radio waves in the frequency range of 2.402 GHz to 2.480

GHz. This technology is used for short range communication (approx. 10m) in a variety of devices

for wireless communication. Baby monitors, door openers, and cell phones are some of the

devices that utilize Bluetooth communication.

Characteristics of Bluetooth Transmission:

• Line of sight between communicating devices is not required. (Think Why?) • Bluetooth can connect up to eight devices simultaneously.

• Slow data transfer rate (up to 1Mbps). Satellite Link - Satellite links are used for very long distance wireless communication which may range from intercity to intercontinental. Transmission from the earth to a satellite is known as uplink. Transmission from a satellite to the earth is known as downlink.

Characteristics of Transmission using satellite link:

• Satellites cover large area of earth • Since communication over very long distances is possible, this becomes a

commercially attractive option. • This system is expensive • Requires legal permissions.

Network Topologies Network topologies describe the ways in which the elements of a network are mapped. They describe the physical and logical arrangement of the network nodes. Let us look at the advantages the different network topologies offer and get to know their

shortfalls. 1. Bus Topology: - it is a series of node connected to a backbone.It has a terminator at either end to absorb signals.

a. It is easy to handle and implement. b. It is best suited for small networks. c. Easy to extend. Disadvantages of Bus Topology

Advantages of Bus Topology

a) The cable length is limited. This limits the number of stations that can be connected. b) This network topology can perform well only for a limited number of nodes. c)Entire network shuts down if there is a break in main cable. 2. Ring Topology:- A Ring network is circular in shape and every node will have one node on either side of it. Data travels only in one direction.

Advantage of Ring Topology a) The data being transmitted between two nodes passes through all the intermediate

nodes. b) A central server is not required for the management of this topology. c) Short cable

length. d) Suitable for Optical Fiber. Disadvantages of Ring Topology a) The failure of a single node of the network can cause the entire network to fail. b) The movement or changes made to network nodes affects the performance of the entire network. c)

Difficult to extend. 3. Mesh Topology: - Mesh topology is a group of nodes which are all connected to each other and many types of connections are possible in a mesh topology.

Advantage of Mesh Topology

a) The arrangement of the network nodes is such that it is possible to transmit data from one node to many other nodes at the same time. Disadvantage of Mesh Topology b) The arrangement wherein every network node is connected to every other node of the network, many of the connections serve no major purpose. This leads to the redundancy of many of the network connections. 4. Star Topology:- A Star topology is based on a central node which acts as a hub.Each node is directly connected to the hub.

Advantages of Star Topology. a) Due to its centralized nature, the topology offers simplicity of operation. b) It also achieves an isolation of each device in the network. c) Easy to install. Disadvantage of Star Topology a) The network operation depends on the functioning of the central hub. Hence, the failure of the central hub leads to the failure of the entire network. b) Require more cable length. 5. Tree Topology:- In a tree topology, stations are attached to a shared transmission medium.

Advantages of Tree Topology: a)

Easy to extend

b) Fault isolation

Disadvantage of Tree Topology: a)

Dependent on the root.

Types of Networks

1. Personal area network:- A personal area network (PAN) is a computer network used for communication among computer and different information technological devices close to one person. Some examples of devices that are used in a PAN are personal computers, printers, fax machines, telephones, PDAs, scanners, and even video game consoles. A PAN may include wired and wireless connections between devices. The reach of a PAN typically extends to 10 meters.

2. Local area network: -A local area network (LAN) is a network that connects computers and devices in a limited geographical area such as home, school, computer laboratory, office building, or closely positioned group of buildings. Each computer or device on the network is a node.

3. Wide area network:- A wide area network (WAN) is a computer network that covers a large geographic area such as a city, country, or spans even intercontinental distances, using a communications channel that combines many types of media such as telephone lines, cables, and air waves. A WAN often uses transmission facilities provided by common carriers, such as telephone companies.

4. Metropolitan Area network:- These are spread over a country.e.g. Cable TV networks.

Functions of network devices:- Separating (connecting) networks or expanding network

e.g. repeaters, hubs, bridges, routers, brouters, switches, gateways, Remote access Hub:- A Hub is an electronic device that connects several nodes to form a network and

redirects the received information to all the connected nodes in broadcast mode.

Bridges:- it is isolate network traffic and computers. It is Used to examine incoming packet source and destination addresses. Switches:- Switches operate at the Data Link layer (layer 2) of the OSI model. Switches resemble bridges and can be considered as multiport bridges. A Switch is an intelligent device that connects several nodes to form a network and redirects the received information only to the intended node(s).

Repeater: A Repeater is a device that is used to regenerate a signal which is on its way through a communication channel. A repeater regenerates the received signal and retransmits it to its destination. Routers:- Routers work at the OSI layer 3 (network layer).They use the “logical address” of packets and routing tables to determine the best path for data delivery. Modems:- Allow computers to communicate over a telephone line. Sending end: MODulate the computer’s digital signal into analog signal and transmits. Receiving end: DEModulate the analog signal back into digital form

Gateway:- A Gateway is a device, which is used to connect different types of networks and

perform the necessary translation so that the connected networks can communicate properly.

Network Protocols A network protocol is a set of rules for communication among networked devices. Protocols

generally includes rules of how and when a device can send or receive the data, how is the sent

data packaged, and how it reaches its destination.

There are a number of protocols defined for computer networks. Here we discuss three of them -

HTTP, TCP/IP, PPP.

HTTP (Hyper Text Transfer Protocol): HTTP is used to transfer all files and other data (collectively called resources) from one computer to another on the world wide web.

TCP/IP (Transmission Control Protocol / Internet Protocol): It is the basic protocol of the Internet. Communication between two computers on internet is done using TCP/IP protocol.

PPP (Point to Point Protocol): It is a protocol for direct communication between two computers, typically a personal computer connected by phone line to a server.

Identification of computers and users over a network MAC (Media Access Control) address: a unique 12 digit (6 digits for manufacturer code and

6 digits for serial number) hexadecimal number assigned to each NIC. MAC address of an NIC

never changes.

IP Address: a unique 4 digit hexadecimal number assigned to each node on a network. IP

address settings of a node can be changed by the user

Two versions of IP addresses: version 4 (IPv4) and version 6 (IPv6). IPv6 uses 128 bits (IPv4 uses

32 bits) for an IP address.

Domain Name: a name assigned to a server through Domain Name System (DNS). A domain

name usually has more than one part: top level domain name or primary domain name and

subdomain name(s).

Domain Name Resolution: process of getting corresponding IP address from a domain name.

Network Security The term Network Security refers to all activities undertaken to protect a computer network from attacks to its security.

Some kinds of attacks on network security are as follows:

Denial of service attacks: A Denial of Service (DoS) attack is an attempt to make one or more

network resources unavailable to their legitimate users. Examples of such attacks are:

• Denial of Access to Information: Corrupting, Encrypting, or changing the status of

information so that it is not accessible to its legitimate user.

• Denial of Access to Application: Forced shutting of an application as soon as the user opens it.

• Denial of Access to Resources: Blocking a resource, may be a printer or scanner or

USB port, of a computer from proper working.

• Denial of Access to a Website: Continuously sending bulk requests to a website so

that it is not available to any other user.

Intrusion Problems: An Intrusion problem is an attempt to mischievously steal some information from someone's computer. Example of intrusion are – snooping, eavesdropping,

Snooping - gaining unauthorized access to another person's or organization's data.

Eavesdropping- gaining unauthorized access to another person's or organization's data while

the data is on its way on the network

To protect a network from security attacks, a number of steps are taken. These steps include:

-> Login-Password

-> Firewall: It is a hardware device or a software that is installed to monitor the data entering the computer/Network or leaving it.

-> Anti Virus Software

-> File Permissions

OPEN SOURCE CONCEPTS

1. Free software Free Software means the software is freely accessible and can be freely used, changed, Improved, copied and distributed by all who wish to do so. And no payments are needed to be made for free software. Free Software is a matter of liberty, not price. To understand the concept , you should think of “free” as in free speech,” not as in free beer.” More precisely. it refers to four kinds of freedom, for the users of the software: The freedom to run the program, for any propose to (freedom 0). Etc. A program is free software if users have all of this freedom”

2. Open Source Software Open Source Software, can be freely used but it doesn’t have to be free of charge. Open source s/w may receive payments concerning support, further development “Open source s/w is officially defined by the open source definition at opensource.org/doc/definition_plain.html.” 3. OPEN SOURCE/FREE SOFTWARE This section is going to talk some such s/w. Let us begin with Linux. a) Linux Linux is the name of popular Computer Operating System. In underlying source code is available to all and anyone can freely openly use it

b) Mozilla

It is free, cross-platform, Internet software suite tah include: 1. A web browser 2. An email client 3. AN HTML editor 4. IRC client. Netscape Communication Corporation initiated Mozilla’s development c) Apache Server It as an open source web server for many platforms such as BSD, Linux, Unix, Microsoft windows etc. d) MySQL

Pronounced “my ess cue el” (each letter separately) and not “my SEE kwill.” is a multithreaded, Multi-user, relational database server. e) PostgreSQL Pronounced “post gress cue ell.” PostgreSQL is an open source database system that began as an enhancement to the POSTGRES research prototype DBMS. Where POSTGRES used the PostQuel query language, PostgreSQL uses a subset of SQL. f) Pango Pango is a library for lying out and rendering of text, with an emphasis on internationalization. Pango can be used anywhere that text layout is needed, though most of the work on Pango so far has been done in the context of the GTK+ widget toolkit. Pango forms the core of text and font handling for GTK+-2.x. g) OpenOffice OpenOffice.org (OO.o or OOo), commonly known as OpenOffice, is an open sourcesoftware application suite available for a number of different computer operating systems. It is distributed as free software and written using its own GUI toolkit. ... h) Tomcat Tomcat is an application server that executes Java servlets and renders Java Server Page i) PHP PHP: Hypertext Preprocessor (the name is a recursive acronym) is a widely used, general-purpose scripting language that was originally designed j). Python Python is a general-purpose high-level programming language whose design philosophy emphasizes code readability. Python aims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive. 4. TYPE OF STANDARDS

A technical standards or simply a standards basically a refers to an established set of rules or requirement, The technical standards can be broadly categorised into: 1. Proprietary standards and 2. Open standards. 1. Proprietary standards Proprietary standards are owned by a single company or a group of vendors. Standards like Microsoft office formats (E.G . . . Doc, .docx, .ppt etc) Media format (e.g. .wma,.wmvetc) Apple Media formats (such as .mov) are proprietary standards as they are the property of their respective owners. 2. Open standards “An open standard is a standard that is publicly available and has various rights to use associated with it, and may also have various properties of how it was designed (e.g. open process).” Principal of open standards are being listed below in the words of Bruce Perens

• Availability

• Maximize End-User Choice.

• No Royalty.

5. COMMON OPEN STANDARDS FORMATS (i) Plain text(ASCII) (ii) Hyper Text Markup Language(HTML)

(iii) Tex,LaTex and device Independent Format(DVI) (iv) DVI.

(v) Open Document Format for Office Application(ODF)

(vi) Joint Photographic Expert Group(JPEG)

(vii) PNG(Portable Network Graphics)

(viii) Scalable Vector Graphics(SVG)

(ix) Ogg Vorbis(OGG)

(x) Free Lossless Audio Codes(FLAC)

Open Document Format (ODF)

The Open Document Format (ODF) is an open source standard for office documents (text, spreadsheets, presentations etc.). It is used eg by OpenOffice or StarOffice and other similar open source tools. INDIAN LANGUAGE COMPUTING

Indian Language Computing refers to ability to interact in diverse Indian Language on electric system ISCII Indian Standard Code for Information Interchange (ISCII) is a coding scheme for representing various writing systems of India. It encodes the main Indic...

UNICODE According to Unicode Consortium – Unicode provides a unique number for every character, No matter what the platform, No matter what the program, No matter what the language.

Fonts “A font refers to a set of displayable text characters having specific style and size”.

Different Types of Fonts Post

• True Type - These fonts contain both the screen and printer font data in a single component, making the fonts easier to install.

• Open Type - Like True Type fonts, this contains both the screen and printer font data in a single component. However, open type fonts support multiple platforms and expanded character sets.

• Static font- In these types of fonts the characters are designed and digitized and then stored in font files. Every time printing takes place, same character will appear with same shape e.g. Times New Roman, Arial etc.

• Dynamic font- a web browser technology used when visiting any website that uses fonts which are not installed on client's machine. The web browser would not be able to display the page properly, but will select one of fonts available on client machine

Entering Indian language text Many tools have been developed to facilitate the typing of Indian language text.

• Phonetic Text Entry- traditional keyboards with English keys are used. But while typing, the Indian alphabets are written phonetically (i.e., the way they sound as per the pronunciation) in English Script and then converted to corresponding language word.

• Keymap based Text Entry- In this method the keyboard keys are mapped to specific characters using a keymap.

UNIT –II : PROGRAMMING Important Terms & Definitions

1. Integrated Development Environment (IDE): It is a software tool to help programmer to edit, compile, interpret and debug the program in the same environment. i.e Eclipse, NetBeans, VB etc.

2. OOP: Object Oriented Programming, emphasis on objects and the interaction between objects. An object is a self-contained entity that describes not only certain data but the procedures to manipulate that data.

3. Class: A class in OOP is a template for objects. In other words, a class is a specification of the data and the functions to be encapsulated with data.

4. Object: Objects in the real world can be represented by objects in the program. Each object contains data and code to manipulate data.

5. JVM: Java Virtual Machine (JVM) is a program which behaves as interpreter and translates byte code into machine language as they go called just in time compilation.

6. RAD: Rapid Application Development is software programming technique that allows quick development of software application.

7. Source Code: The core program or text which is written in a language like C,C++ or Java is called source code.

8. Object Code: The program which only is understood by the computer in the form of machine instructions or binary instructions called object code. In Java JVM is used to generate object code in the form of byte code.

9. Byte code: A byte code is long instruction that the Java compiler generates and Java interpreter executes. When the compiler compiles a .java file, it produces a series of byte codes and stores them in a .class file. The Java interpreter (JVM) can execute the byte codes stored in the .class file.

10. GUI: A graphical user interface (GUI) presents a pictorial interface to a program. GUI allows

the user to spend less time trying to remember which keystroke sequences do what and spend more time using the program in a productive manner.

11. Primitive Data Types:

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:

• byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

• short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).

• int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

• long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).

• float: The float data type is a single-precision 32-bit IEEE 754 floating point.

• double: The double data type is a double-precision 64-bit IEEE 754 floating point.

• boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions.

• char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

12. Reference Data Types : These are constructed by using primitive data These are

constructed by using primitive data types, as per user need. Reference data types types, as per user need. Reference data types store the memory address of an object. Class, store the memory address of an object. Class, Interface and Array are the example of Interface and Array are the example of Reference Data types.

13. Literals: A literal is the source code representation of a fixed value;

As shown below, it's possible to assign a literal to a variable of a primitive type:

boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000;

14. Operators: Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

Operators Precedence postfix expr++ expr-- unary ++expr --expr +expr -expr ~ ! multiplicative * / % additive + - shift << >> >>> relational < > <= >= instanceof equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND &&

logical OR || ternary ? :

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

15. Control Flow Statements: The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.

Decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language.

Selection Statement If Statement –

The if statement allows selection (decision making) depending upon the outcome of a condition. Syntax: if (conditional expression) {

Statement Block; } else if(conditional expression) {

Statement Block; } else {

Statement Block; } Switch Statement - This selection statement allows us to test the value of an expression with a series of character or integer values. switch (Variable/Expression)

{ case Value1:statements1 ;

break ; case Value2:statements2 ;

break ; . .

default:statements3 ; }

The limitations of switch are as follows:

• It doesn't allow ranges, eg case 90-100. • It requires either integers or characters and doesn't allow useful types like String.

Iteration Statements :

for loop - The loop has four different elements that have different purposes. These elements are:

a) Initialization expression: Before entering in a loop, its variables must be initialized. b) Test Expression: The test expression decides whether the loop body will be executed or

not. If the test condition is true, the loop body gets executed otherwise the loop is terminated.

c) Increment/Decrement Expression: The Increment/Decrement expression changes the value of the loop variable.

d) The Body of the loop: The statements, which are executed repeatedly while the test expression evaluates to true form the body of the loop. Syntax for( initialization; test exp; increment/decrement/Update exp) { statements; } The three expressions inside the round braces of for loop are optional.

While Loop - The while loop is an entry-controlled loop. It means that the loop condition is tested before executing the loop body. If the loop condition is initially false, for the first iteration, then loop may not execute even once. A loop control variable should be initialized before the loop begins and the loop variable should be updated inside the body of the while loop.

Syntax while(test expression) {

loop body }

Do..While Loop - Do..While loop is an exit-controlled loop. In the do..while loop, the test occurs at the end of the loop. This ensures that the do..while loop executes the statements included in the loop body at least once.

Syntax do {

loop body } while (test expression);

16. Swing GUI: The classes that are used to create the GUI components are part of the Swing

GUI components from package javax.swing.

Swing Components Uses

JFrame A JFrame is superclass which provides the basic attributes and behaviors of a windows(like other window)

JLabel An area where uneditable text or icons can be displayed

JTextField An area in which the user inputs data from the keyboard. The area can also display information.

JButton An area that triggers an event when clicked

JCheckBox A GUI components that is either selected or not selected.

JComboBox A drop-down list of items from which the user can make a selection by clicking an item in the list or by typing into the box,if permitted.

JList An area where a list of items is displayed from which the user can make a selection by clicking once on any element in the list.Double clicking an element in the list generates an action event. Multiple elements can be selected.

JPanel A container I which components can be placed

17. Escape Sequence: When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. Escape sequences are normally used to control printed or displayed output. For example, \a, \b, \n, \t, etc.

18. Type Conversion of strings: There is a standard class named Integer that contains several subroutines and variables related to the int data type. In particular, if str is any expression of type string, then Integer.parseInt (str) is a function call that attempts to convert the value of str into a value of type int. for example, the value of Integer.parseInt (“10”) is the int value 10. If the parameter to Integer.parseInt does not represent a legal int value, then an error occurs.

19. parseByte(String S): It converts a String argument to an 8 bits integer value. Class Byte is part of the package java.long. For example, if a jTextField entry has value as 10 then to convert into a byte data type variable bVal, the command is:

byte bVal = Byte.parseByte(jTextField1.getText());

20. parseShort (String S): It converts a String argument to a 16 bits integer value. Class Short is a part of the package java.long. For example, if a jTextField entry has value as 1110 and

to convert into a short data type variable sVal, the command is short sVal = Short.parseSort(jTextField1.getText());

21. parseFloat (String S): It converts a String argument to a 32 bits single precision

floatingpoint value. Class Float is part of the package java.long. For example, if a jTextField entry has value as 120.44 and to convert into a floating-point type variable fVal, the command is:

float fVal = Float.parseFloat(jTextField1.getText()); 22. parseDouble (String S): It converts a String argument to a 64 bits single precision double

floating-point value. Class Double is part of the package java.long. For example, if a jTextField entry has value as 8979677.23 and to convert into a double precision data type variable dVal, the command is:

double dVal = Double.parseDouble(jTextField1.getText());

23. parseLong (String S): It converts a String argument to a 64 bit integer value. Class Long is part of the package java.long. For example, if a jTextField entry has value as 58987654 and to convert into a long data type variable lVal, the command is:

long Val = Long.parseLong (jTextfield1.getText ());

24. How are protected members different from public and private members of a class?

Ans: Protected members can be directly accessed by all the classes in the same package, as that of the class in which the member is and sub classes of other package. Whereas private members cannot be accessed outside the class, even in subclasses of the class and public members can be directly accessed by all other classes.

25. Define an abstract class and abstract method.

Ans: An Abstract Class is the one that simply represents a concept and whose objects can’t be created. It is created through the use of keyword abstract. Abstract methods are methods with no method statements. Subclasses must provide the method statements for the inherited abstract methods e.g. in the following code class. Shape is abstract class and method display( ) is abstract modified.

26. Math functions: The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, power, rounding, maximum, minimum and trigonometric functions. For example, sin(), cos(), log(), pow(), sqrt(), abs(), ceil(), floor(), max(), min(), round(), random(), etc. All Math functions used with the Math class object.

MATH DESCRIPTIONS EXAMPLE

FUNCTIONS

sin() Returns the trigonometric sine of an angle.

sin(double a)

cos() Returns the trigonometric cosine of an angle.

cos(double a)

log() Returns the natural logarithm (base e) of a double value.

log(double a

pow() This function returns you the number raised to the power of a first given value by another one.

pow(double a, double b)

sqrt() Returns a double value that is the square root of the parameter.

math.sqrt(100)

abs() Returns the absolute value of a number. Whereas the number can be int, float, double or long.

math.abs(-100)

ceil() Returns the next whole number up that is an integer.

math.ceil(1.1)

floor() Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.

math.floor(-99.1)

max() Returns the maximum value from the two given value.

math.max(-1,-10)

min() Returns the minimum value from the two given value.

math.min(1,1)

round() Rounds to the nearest integer. So, if the value is more than half way towards the higher integer, the value is rounded up to the next integer.

math.round(1.01)

random() Returns a random number between 0.0 and 1.0

math.random()*100

27. String class: The String class includes methods for examining individual characters of a string sequence, for converting strings to uppercase or lowercase, for extracting substrings, for joining two strings together, for calculating the length of a string and also for creating a new string by omitting the leading and trailing whitespaces. Some of the String class methods are follow:

Method Description

concat(String str) Concatenates the specified string to the end of this string.

length() Returns the length of the string.

substring (int beginpos

[, int endpos])

Returns a substring of the characters between the two specified positions of the string. The second parameter is optional; if not included then all characters from the start position to the end of the string are included. The character at the ending position (n2) is not included.

toLowerCase() Returns the string converted to lower case.

toString() Returns the object as a string.

toUpperCase() Returns the string converted to upper case.

trim() Returns the string, after removing the leading and the trailing whitespaces

28. Swing Control Methods and Properties: These are the Swing Controls available with NetBeans IDe and their concern methods and properties are given below.

Swing Controls Methods Properties

jButton

• getText() • setText()

• Background • Enabled • Font • Foreground • Text • Label

jLabel • getText() • setText()

• Background • Enabled • Font • Foreground • Text

jTextField • getText() • isEditable() • isEnabled() • setText()

• Background • Editable • Enabled • Font • Foreground • Text

jRadioButton • getText() • setText() • isSelected() • setSelected()

• Background • Button Group • Enabled • Font • Foreground • Label

• Selected

jCheckBox • getText() • setText() • isSelected() • setSelected()

• Button Group • Font • Foreground • Label • Selected • Text

jButtonGroup • Add

jComboBox •getSelectedItem() •getSelectedIndex() • setModel()

• Background • ButtonGroup • Editable • Enabled • Font • Foreground • Model •SelectedIndex • SelectedItem • Text

jList • getSelectedValue()

• Background • Enabled • Font • Foreground • Model • SelectedIndex • SelectedItem • SelectionMode • Text

jTable • addRow() • getModel()

• model

JoptionPane • showMessageDialog()

• getRowCount() • removeRow() • addRow()

29. Constructors: A class contains constructors that are invoked to create objects from the

class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.

30. The classes for which objects are required to be declared are known as concrete classes like JLabel, JTextField, JComboBox etc. The classes for which it is not essential to declare objects to use them are known as abstract classes like JOptionPane.The extends keyword is used to inherit data members and methods of the base class and allows the derived class to use these methods.

QUESTIONS ON FLOW OF CONTROLS – JAVA (1 Mark Questions)

1. What is a conditional Statement? The conditional statement checks for a condition. If the condition is true a statement is executed otherwise the else part of the condition is executed.

2. What is the name of the construct used in the following statement and how does it operate? a= (b>c)? b : c; The statement uses the conditional operator. If b is greater than c then a is assigned the value of b, if the test expression is false, a takes the value of c.

3. What is the purpose of a default clause in a switch statement? The default statement gives the switch construct a way to take action if the value of the switch variable does not match any of the case constants.

4. What is nested if statement An if statement can be contained within another if statement. This is referred as nested if statement.

5. What restrictions are placed on the values of each case of a switch statement? During compilation the values of each case of a switch statement must evaluate to a value that can be promoted to an int value

6. What is the difference between an if statement and a switch statement? If statement is used to select among two alternatives. It uses a Boolean expression to decide which alternative should be executed. The switch statement is used to select among many alternatives. It uses an integer expression to determine which alternative should be executed.

7. Name the loop statements available in java While , do-while and for 8. What are the three expressions given in a for statement

Initialization expression, test expression, increment/decrement expression 9. What are the two ways to get out of a loop Normal exit and abnormal exit 10. How are commas useful in the initialization an iteration parts of a for statement Commas

are used to separate multiple statements within the initialization and iteration parts of a for statement

11. Which expression can be omitted in for statement? In a for loop initialization expression, test expression and update expression are optional

12. Where can you apply the break statement in Java programming? The break statement can be applied in any of the loops and in switch statement

13. Name the jumping statements in java Return, break and continue 14. What happens to the scope of a variable if it is declared inside a for loop

When it is declared we should remember that scope of that variable ends when the for statement ends. That is scope of the variable is limited to the scope of for loop

15. What is wrong with the following programme? int x=3; int y=1; if(x=y) jLabel1.setText(“Not

equal”); else jLabel1.setText(“equal”);

An error at “ if (x=y)” causes compilation to fail. It should be if(x==y) 16. Give the output of the following statement for(int i=10;i>6;i=i-2)

jTextArea1.append(String.valueOf(i)+”\n”); Output 10 8

17. Differentiate between do-while loop and for loop Do-while loop is exit controlled and for loop is entry controlled loop

18. Write one limitation and one advantage of a switch statement Compact code but floating numbers cannot be compared

19. Use an if statement to compare the value of an integer called sum against the value 65 and if it is less print the text string “Sorry Try again” if(sum < 65) jLabel1.setText( “Sorry Try again”);

20. Write an appropriate for loop for the following A loop is to be repeated 200 times except the loop is to be terminated if the value of the variable x becomes 175 for(x=1; x<=200; x++) if( x==175) Break;

(2 marks)

1. What happened if a semicolon is placed as the for/while statement terminator If a semicolon is placed at the end of a for or while statement it is considered as an empty loop and the loops control variable initialized condition is tested , variables value is updated but no other statements outside the loop is treated as part of the loop

2. Differentiate between if construct and while loop If statement conditionally executes a section of the code whereas while section while section executes a section of code more than once.

3. How an entry controlled loop is different from an exit controlled loop In case of an entry controlled loop test condition is checked at the time of entering into the loop whereas in an exit controlled loop the test condition is checked at the time of exiting from the loop

4. What is the difference between while and do-while loo. In do-while the condition is checked at the end whereas in while it is at the beginning. Hence the statements within the do block are always executed at least once. Do-while is an exit controlled whereas while is an entry controlled loop

5. What will be the value of A & B after execution of the following code int A=100,B; for(B=10;B<=12;B++) A+=B; jOptionpane.showMessageDialog(this,”A” +A+”B”+B+” “); A 133 b 12

6. Rewrite the following if-else-if construct using switch case statement if(opt==1) jLabel1.setText(“You entered one”); else if(opt==10) jLabel1.setText(“You entered ten”); else if (opt==100) jLabel1.setText(“You entered hundred”); else (opt==1000) jLabel1.setText(“You entered one thousand””); else jLabel1.setText(“invalid entry); Ans: switch(opt) { case 1 : jLabel1.setText(“You entered one”); break; case 10: jLabel1.setText(“You entered ten”); break; case 100: jLabel1.setText(“You entered hundred”); break; case 1000: jLabel1.setText(“You entered thousand”); break; default: jLabel1.setText(“invalid entry); }

7. Given the following code fragment: i=2; do{ System.out.println (“”+i); i += 2; } while (i < 51); jOptionPane.showMessageDialog( null, “Thank you” );

Rewrite the above code using a while loop I=2; Whle ( I < 51) {

System.out.println (“”+i); i += 2;

} jOptionPane.showMessageDialog( null, “Thank you” );

8. Find the output of the following code fragments ?

(a) int s = 14; (b) int s = 14; if(s<20) if(s<20)

System.out.print(“Under”); System.out.print(“Under”); else else { System.out.print(“Over”); System.out.print(“Over”); System.out.print(“ the limit”); System.out.print(“ the limit”);

} (c) int s = 94;

If (s < 20) { System.out.print(“Under”); } else { System.out.print(“Over”); } System.out.println(“ the limit”);

Ans: (a) Under the limit (b) Under (c) Over the limit

9. What will be the output of the following code fragment when the value of ch is (a) ‘A’ (b) ‘B’ (c) ‘D’ (d) ‘F’ switch (ch) { case ‘A’ : System.out.print ln (“Grade A”); case ‘B’ : System.out.print ln (“Grade B”); case ‘C’ : System.out.print ln (“Grade C”); break; case ‘D’ : System.out.print ln (“Grade D”); default : System.out.print ln (“Grade F”); } (a)Grade A Grade B Grade C (b)Grade B Grade C (c) Grade D Grade F (d) Grade F

10. Predict the output of following code fragments: (a) int i, j, n; (b) int i=1, j=0, n=0;

n=0; i=1; while (i<4) { do { for(j=1; j<=I; j++) { n++; i++; n+=1; } while (i<=5); }

i=i+1; } System.out.print ln(n);

(c) int i=3, n=0; (d) int j=1, s=0; while (i<4) { while(j<10) { n++; i--; System.out.print(j+ “+”); } s=s+j; System.out.print ln(n); j=j+j%3;

} System.out.print ln(“=”+s);

QUESTION ON FRONT-END INTERFACE COMPONENTS IN JAVA: (1 MARKS QUESTIONS) 1.What does getPassword() on a password field return? (a) a string (b) an integer (c) a character array. Ans: (c) a character array 2. Which of the following component is the best suited to accept the country of the user? A.

List B. Combo box C. Radio button D. Check box Ans: B. Combo box

3. What command do you need to write in actionPerformed() event handler of a button, in order to make it exit button?

a. System.out.println(); b. System.exit(0); c. System.out.print() Ans: b. System.exit(0); 4.What method would you use, in order to simulate a button’s(namely Okbtn) click event, without any mouse activity from user’s side?

a. Okbtn.setText() b.Okbtn.getText() c. Okbtn.doClick() Ans: Okbtn.doClick() 5. What would be the name of the event handler method in the ListSelection listener interface for a

list namely CheckList to handle its item selections? a. CheckListValueChanged() b. getSelectedValue() c. clearSelection() Ans: a. CheckListValueChanged() 6. Which control displays text that the user cannot directly change or edit? a.TextField b. Checkbox c. Combobox d. Label Ans: d.Label 7.Which control provides basic text editing facility?

a.TextField b. Checkbox c. Combobox d. Label Ans: a. TexfField 8. Occurrence of an activity is called: a. Function b. Class c. Object d. Event Ans: d.Event. 9. Which property is used to set the text of the Label? a. font b.text c.name d. icon Ans: b.text 10. The object containing the data to be exhibited by the combo box by which property. a. editable b. model c.selectedIndex d.selectedItem Ans: b. model 11. What is GUI programming? Ans: A GUI(Graphical User Interface) is an interface that uses pictures and other graphic entities along with text, to interact with user. 12. How is swing related to GUI programming? Ans: We can create a GUI application on Java platform using Swing API (Application Programming Interface), which is part of Java Foundation Classes(JFC). 13. Which property would you like to set to make a Combo box editable? Ans: editable. 14. What is the default name of action event handler of a button namely TestBtn? Ans: private void TestBtnActionPerfomed(java.awt.action.ActionEvent evt){ }. 15. What property would you set to assign access key to a button? Ans: mnemonic property is used to assign access key or shortcut (Alt + Key). 16. Which method can programmatically performs the click action of a push button? Ans: private

void TestBtnActionPerfomed(java.awt.action.ActionEvent evt){ }. 17. Which property would you set the setting the password character as ‘$’? Ans:echoChar 18. Which method returns the password entered in a password field? Ans: char [] getPassword().

19. Which list property do you set for specifying the items for the list. Ans: model 20. Which method would you use to determine the index of selected item in a list? Ans: int

getSelectedIndex(). 21. Which method would you use to insert an item at specified index, in the list? Ans: void

setSelectedIndex( int index). 22. How you can determine whether 5th item in a list is selected or not? Ans: isSelectedIndex(4). 23. Which method you would use to insert ‘Hello’ at 10th position in the Text Area control.

Ans:void insert(“Hello”, 9). 24. Which method you would like to use to insert an Icon (picture) on a Push Button. Ans: void

setIcon(Icon). 25. Which property would you like to set to make a Combo box editable? Ans: editable. (2 MARKS QUESTIONS) 1. What is an event? What is event handler? 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. Three things are important in Even Handling- Event Source: It is the GUI component that generates the event, e.g. 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 event etc. 2. What is Layout Manager? Name the layout managers offered by NetBeans? Ans: Layout managers enable you to control the way in which visual components are arranged in GUI forms by determining the size and position of components within containers. There are seven types of layout are available–

Flow Layout • Grid Layout • Card Layout • Spring Layout • Border Layout • GridBag Layout • Box Layout

3. Name three commonly used properties and methods of the following controls. (a) text field (b) text area (c) Check Box Ans: (a) Properties: text, font, editable. Methods: void setText(), String getText(), void setEditable(boolean). (b) Properties: enabled, editable, wrapStyleWord Methods: setText(), getText(), isEditable() (c)

Properties:font, text, selected . Methods: getText(), isEnabled(), isSelected(). 4. What is dispose() used for ?

Ans: dispose() is used for hide and dispose of the frame when the user closes it. This removes the frame from the screen and frees up any resources used by it. 5. What is the difference between Text field & Text area? Ans: A text field’s text property can hold single line of text unless it is an HTML text. While a text area’s text can hold any number of lines of text depending upon its rows property. 6. What is the difference between Text field & password field? Ans: Though a text field and a password field can obtain a single line of text from the user, yet these are different. A password field displays the obtained text in encrypted form on screen while text field displays the obtained text in unencrypted form. 7. What is the Radio Button? Explain Ans: Radio Button: A jRadioButton control belongs to JRadioButton class of Swing controls. It is used to get choices from the user. It is grouped control, so that only one can be selected at a time among them. Radio Button works in group, so that they must be kept in a ButtonGroup container control like so that only one can be selected at the same time. Some features of jRadioButton control are-

It can be used to input choices typed input to the application. Only one Radio button can be selected at a time. They must be kept in a Button Group container control to form a group.

8. What do you mean by Check Box? Check box: A jCheckBox control belongs to JCheckBox class of Swing controls. It indicates whether a particular condition is on or off. You can use Check boxes to give users true/false or yes/no options. Check Boxes may works independently to each other, so that any number of check boxes can be selected at the same time. Some features of jCheckBox control are-

It can be used to input True/False or Yes/No typed input to the application. Multiple check boxes can be selected at the same time.

9. What is the significance of following properties of a text area ? (a) lineWrap (b) wrapStyleword Ans: (a) Defines Wrapping feature enable/disable (b) Determines where line wrapping occurs. If true, the component attempts to wrap only at word boundaries. This property is ignored unless linewrap is set to true. 10. What is the significance of a button group? How do you create a button group? Ans: We must add a ButtonGroup control to the frame to group the check boxes by using Button Group property of the check box. By dragging buttongroup control from palette window. (4/5/6 MARKS QUESTIONS) Q1. 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 Excellent Customer Feedback Maximum Count Customer

10 8 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:

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)); } Q2. 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 application 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.

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

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

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

Employee Type Basic Salary

DA (% of Basic Sal) HRA (% of Basic Sal) Deductions (% of Basic sal)

Non Teaching 12500 31 30 12

PGT TGT PRT

14500 12500 11500

30 21 20

30 30 25

12 12 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) { 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); Q4. 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 application 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.

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”); } else if( jRadioButton2.isSelected()) { if ( p>=60 ) jTextField4.setText(“Eligible for Commerce and Humanities”); else jTextfield4.setText(“Not Eligible for Science and Commerce”); } 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(null) jTextField1.setText(“ “) OR jTextField1.setText(null) jTextField1.setText(“ “) OR jTextField1.setText(null) jTextField1.setText(“ “) OR jTextField1.setText(null) jCheckbox1.setSelected(false); } d. private void jBtnCloseActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); }

Some Other Important Questions with Answers Q. What is event driven programming? Ans:- This programming style responds to the user events and is driven by the occurrence of userevents. Q. What are containers? Give examples. Ans: - Containers are those controls inside them e.g., frame (JFrame), Panel (JPanel), label (JLabel) etc. are containers. Q. Name the character set supported by Java. Ans: - Unicode. Q. What is an identifier? Ans:- Identifiers are fundamental building block of a program and are used as the general terminology for the names given to different parts of the program viz. variables, objects, classes, functions, arrays etc. Q. What is the result of the types of the logical expressions given below? (i) (3<5) || (6=5) || (3! =3) (ii)(5! =10) && ((3=2+1)|| (4<2+5)) (iii)!(5==2+3) && !(5+2 !=7-5)? Ans:- (i) true || false || false =true (ii) true && (true || true) =true && true = true (ii) ! true && ! true = false && false = false Q. What is casting? When do we need it? Ans:- Casting is a conversion, which uses the cast operator to specify the type name in parenthesis and is placed in front of the value to be converted. For example: Result = (float) total / count ; They are helpful in situations where we temporarily need to treat a value as another type. Q. What is the purpose of break statement in a loop? Ans:- In a loop, the break statement terminates the loop when it gets executed.

Q. How is the if…else if combination more general than a switch statement? Ans:- The switch statement must be by a single integer control variable, and each case section must correspond to a single constant value for the variable. The if…else if combination allows any kind of condition after each if. Q. What is a container component? Ans:- A container is a special type of component that can hold other components.Some Swing Containers are jPanel, jFrame, jApplet, jWindow, jDialog and jInternalFrame. The components contained in a container are called child component. 1. Identify the possible error(s) in the following code fragment: Underline error(s) and correct the code.

f=1; for(int a=40; (>30); a--) f*=a; s=0; for(int a=1; a<40/a++) s+=a;

Ans: Error in the first and second for loop line ,and the corrected code should be as follows: for ( int a =40 ; (a >30); a - - )

for ( int a =1 ; (a <40); a ++ ) Q1 Find the output of the following code: (a)

int I =1; while(I<5) { System.out.print( I+ “ ” ); I=1*2; }

(b) int total=0,sum=0;

for(int I=0;I>=10;I++) sum += I; System.out.println(total);

Ans: a) 1 2 4 b) 0 Q2 Find the output of the following code: (a) int I =0;

while(I<10) { if( I % 2 ) = = 0) { x = x+ I:

System.out.print(x + “ ” ); }I++: }

(b) int I =0; for(I=1;I<=20;I++){ System.out.print(i + “ ” ); I =I+2:

}

Ans: a) 0 2 6 12 20 b) 1 4 7 10 13 16 19 Q3 What will be the output of the following segment?

int I =0,x = 0: do{ if (I% 5 = = 0){ x ++: System.out.print(x + “ ” ); }

++i: }

while(I<20); System.out.print(“\n + x );

Ans:- 1 2 3 4 4 Q4 What will be the output of the following segment?

int I =0,x = 0; for (I=0;I<5;++I) for (I=0;j<i;j++) { x += (I+j-1); System.out.print(i + “ ” ); } System.out.print(“\n +x ); }

Ans:- 0 1 3 5 8 12 15 19 24 30 30 Q5 What will be the output of the following segment?

int I =0,x = 0; for (I=1;I<10;I* = 2){ x ++: System.out.print( x + “ ” ); }

System.out.print( “\n” + x); Ans: 1 2 3 4 4 1. Rewrite the following fragment using switch:

if ( ch == ‘E’) eastern ++; if ( ch == ‘W’) western ++; if (ch ==’N’) northern++; if (ch == ‘S’) southern++; else unknown++;

Ans: switch(ch) {

case ‘E’ : eastern ++; break; case ‘W’ : western ++; break; case ‘N’ : northern ++; break; case ‘S’ : southern ++; break; default }

: unknown++;

2. Given the code fragment:

i = 2; do { System.out.println(i); i+=2; }while(i<51);

jOptionPane.showMessageDialog(null, “Thank you”); Rewrite the above code using a while loop.

Ans: i = 2; while(i<51) { System.out.println(i); i+=2; } jOptionPane.showMessageDialog(null, “Thank you”);

3. Rewrite following while loop into a for loop

int stripes = 0; while ( stripes <=13) {

if ( stripes % 2 == 2) { System.out.println(“Colours code Red”);

} else { System.out.println(“Colours code Blue”); }

System.out.println(“New Stripe”); stripes = stripes + 1; }

Ans: for ( int stripes =0; stripes <=13; stripes++) { if stripes % 2 == 2) { System.out.println(“Colours code Red”); }

else { System.out.println(“Colours code Blue”); }

System.out.println(“New Stripe”); }

4. Predict the output of the following code fragments. (a) 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);

(b) int i,j,n; n=0, i= 1; do {

n++; i++; } while(i<=5); (c) 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);

(d) int j=1, s=0; while(j<10) {

System.out.println(J+ “+”); s = s +j; j = j + j % 3;

} System.out.println(“=” + s);

Ans: a) x = 15, b) No output c) 6 d) 1+2+4+5+7+8= 27

Q1.Create a Java Desktop Applicant to find the Discount of an item on the basis of Category of item[Electrical Appliance/Electronic Gadget /Stationery]. The Categories will be implemented in JRadioButton controls. The discount will be calculated as follows:

The extra Discount will be calculated as follows:

Calculate the total discount as: discount on cost+ discount on category Calculate the discount amount as: cost*discount Using a JButton’s (Compute Discount) click event handler, display the discount in a JTextField control. Also implement the following settings for IDE:

Control Property Name Property Value

JFrame JLabel1 JLabel2

Title Text Text

Discount calculator Enter cost Dsicount: Choose Category

Cost Discount (%)

<= 1000 otherwise

5 10

Category Discount (%)

Electrical Appliance Electrical Gadget Sttionery

3 2 1

JPanel ButtonGroup1 JRadioButton1

Title Border [None] Text ButtonGroup

[None] Electrical Appliance buttonGroup1

JRadioButton2 JTextField1 JTextField2 JButton1 JButton2

Text buttonGroup Text Variable Name Text Variable Name Editable Text Variable Name Text Variable Name

Stationery buttonGroup1 [None] txtCost [None] txtDisc False Compute Discount BtnDisc Exit btnExit

private void btnDiscActionPerformed (java.awt.ActionEvent evt) {

int cost = 0; double discount =0; cost=Integer.parseInt(txtCost.getText());

if(cost<=1000){ discount= 0.05; } else{

discount=.10; }

if (jRadioButton1.isSelected ( )) { discount = discount + 0.03;

} else if ( jRadioButton2.isSelected( )) { discount = discount +0.02;

else { discount = discount + 0.1;

} txtDisc.setText( “ “ + Math.round (cost*.discount));

} private void btnExitActionPerformed (java.awt.ActionEvent evt) { System.exit ( 0 ); } Q2. 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 Excellent Customer Feedback

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

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

Q3. Create a Java Desktop Application to convert a given temperature Farenheit to Celsius and vice versa using switch case statements. For an incorrect choice or input,an appropriate error message should be displayed. (Hints: C= 5/9 (F-32) and F = 1.8 (C+32) ) Using a JButton’s (Convert ) click event handler, display the corresponding temperature value in aJTextField control. Assume the nomenclature of the swing components of your own. Note: That the JFrame from IDE window will be shown as given :

Ans:- private void btnConActionPerformed (java.awt.ActionEvent evt) { int ch = 0;

if ( jRadioButton1.isSelected()) { ch = 1;

} if ( jRadioButton2.isSelected()) {

ch = 2; } int F,C; double C1=0,F1=0; switch(ch) { case 1: F= Integer.parseInt (txtTemp.getText());

C1=5.0 /9* (F-32); txtCon.setText(“” + Math.round(C1)); break;

case 1: F= Integer.parseInt (txtTemp.getText()); F1 = 1.8 *C +32; txtCon.setText(“” + Math.round(F1)); break;

default : txtCon.setText(“Invalid Choice !!!”); }

}

4.Read the following case study and answer the question that follows:

Object type Object Name Description

Text Field Product TF QtyTF RateTF AmountTF DiscountTF NetTF

To enter the name of the product To enter quantity sold To enter rate per unit To display total amount as quantity* rate To display the discount amount based on membership type To display net amount as discount

Radio Buttuns PlatinumrRB GoldRB SilverRB

To specify membership type

Button Group MembershipBG Button Group for membership radio buttons

Button CalcBTN ExitBTN

To calculate the amount, discount and net amount To close the application

(a) Write the code to disable the text fields AmountTF, DiscountTF and NetTF. (b) Write the code for calcBTN to calculate the amount, discount and net amount as per the given

descriptions and conditions. (c) Write the code to remove the decimal part from the text field NetTF so that the net amount

contains only the integer portion in Rupees. Where (in which event handler) would you place this code to have its impact?

(d) Write the code for ExitBTN to close the application, but before the application is closed it should check the net amount and if the net amount > 10,000 the membership of the customer should be upgraded and displayed. For example, if the customer already has Silver membership it should be upgraded to Gold (similarly from Gold to Platinum) and he should be informed of the same using a message box.

Ans: (a) AmountTF.setEnabled ( false);

DiscountTF.setEnabled( false); NetTF.setEnabled ( false);

(b) private void calBTNActionperformed (…..) { double amt = 0, disc = 0,

netamt = 0; int qty = Integer.parseInt(Qty.getText( )); double rate = Double.parseDouble (RateTF.getText( )); amt = qty * rate;

if ( PlatinumRB.isSelected( )) disc = amt * 0.10; else if ( GoldRB.isSelected( )) disc = amt * 0.05; else disc = amt * 0.03; netamt = amt – disc;

AmountTF.setText( “ “+ amt); DiscountTF.setText( “ “ + disc); NetTF.setText ( “ “ + netamt);

} ( c ) double neamt = Double.parseDouble (NetTF.getText( ) ); int

net = ( net) Math.floor ( netamt); NetTF.setText(“ “ + net);

( d) Private void ExitBTNActionPerformed (…..) {

int net = Integre.parseInt(NetTF.getText( ) ); if ( net > 10000) { if ( GoldRB.isSelected ( ) ) { PlatinumRB.setSelected (true); JoptionPane.showMessageDialog ( null ,

“Congratulations.U have been upgraded to platinum membership”);

} else if (SilverRB.isSelected ( ) ) { GoldRB.setSelected(true); JOptionPane. showMessageDialog ( null

, “Congratulations.U have been upgraded to gold membership”);

} } System.exit ( 0); }

Concepts of Inheritance Basic Concepts and Important Terms 1. Inheritance: Inheritance is the capability of one class to inherit properties from an existing class.

Inheritance supports reusability of code and is able to simulate the transitive nature of real life objects.

2. Derived/Sub and Base/Super classes

A class from which another class is inheriting its properties is called base class and the class inheriting properties is know as a sub class and derived class.

2. Single ( 1:1)

when a class inherits from a single base class.

3. Hierarchical (1:M)

when several classes inherit from the same class.

4. Multilevel (1:1:1)

When a subclass is the base class of another class. 5. Method overriding: If Base class has a method with same signature as in sub class the method

of subclass overshadows the method of base class , it is called Method overriding.

6. Method Overloading: Two methods with same name but different signatures are there in the same scope of program.

7. Abstract Class: The class that is used as only base class, no object of this class is used in the program.

8. Dialog Type:

There are four built-in dialog styles: 1) Message dialog JOption.ShowMessageDialog() displays the message dialog

2) Input dialog JOption.ShowInputDialog() displays the input dialog

3) Confirm dialog JOption.ShowConfirmDialog() displays the confirm dialog

4) Option dialog JOption.ShowOptionDialog() displays the option dialog

Database Connectivity to MySQL 1. Classes used for Database Connectivity

Driver Manager Class, Connection Class, Statement Class, Resultset Class)

2. Preriquisites For connecting to MySQL from Java MySQL provides connectivity for client applications 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 Result set 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=”username” & password=”password” 5. Resultset Methods A result set (represented by a ResultSet 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:-

next() :moves the cursor forward on row.

first() :moves the cursor to the first row in the ResultSet Object.

Last() :moves the cursor to the last row in the ResultSet object.

relative(in rows) :moves the cursor relative to its current position.

Absolute(int rno) :positions the cursor on the rno-th row of the ResultSet object.

getRow :Retrieves the current row number the cursor is pointing at. That is if cursor is at first row the getRow() will return 1.

• A GUI (The Front-End) helps the user to design forms to accept data and provide instructions for retrieving information from the backend.

• A database (The Back-End) helps in storing data in organized manner for future reference and use

• A link needs to be established between the front end form and the back end table using jdbc driver (or an equivalent) to facilitate communication between the two.

• A complete application requires a combination of all three concepts i.e. it requires a user friendly interface, an efficient connection link and a database

• The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver.

• The JDBC Connection interface defines methods for interacting with the database via the established connection.

• To execute SQL statements, you need to instantiate (create) a Statement object using the connection object.

• The getConnection() method of the DriverManager class is used to establish a connection to the database.

• The getMessage() method is used to retrieve the error message string. • The executeUpdate() method of the Statement class is used to update the database

with the values given as an argument. • The executeQuery() method is used when we simply want to retrieve data from a

table without modifying the contents of the table. • The next() method of the result set is used to move to the next record of the

database. • The getModel() method is used to retrieve the model of a table. • The getRowCount() method is used to retrieve the total number of rows in a table. • The removeRow() method is used to delete a row from a table. • It is possible to add Multilingual support in MySQL database by setting the

appropriate character set while creating the database.

QUESTIONS ON JAVA DATABASE CONNECTIVITY TO MYSQL:- Solved Questions (1 mark) 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 Solved Questions(2 marks) Q1. What tasks does JDBC performs ? Ans:Mainly JDBC performs following tasks from within java application code:

i. Establishing a connection with a database. ii. Sending SQL statements to database server. iii. Processing the results obtained.

Q2. How can you make connection ? Ans: To establish a connection, we need to have the appropriate driver connect to the DBMS. The following line of code illustrates this: String url = “jdbc:mysql://localhost/KVS”; connection con= DriverManager.getConnection (url, “Ashok”, “A1”); Prior to this the driver must be registerered with DriverManager using Class.forName ( ) method. Q3.How can you retrieve data from the ResultSet ? Ans: JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs. ResultSetrs=stmt.executeQuery(“Select bookno,bookname from books;”); int no=rs.getInt(“bookno”): String s1=rs.getString (“bookname”); Q4.What would following code do? Ans: .

.

. . Connection, statement created String sql= “SELECT * from objects table1;” Resultsetrs= stmt.executeQuesry (sql); Rs.last(); Int r=rs.getRow( ); JOptionPane.showMessage(null, “.” +r);

Ans: The above code will return the total number of rows in a result-set. Solved Question(3 marks)

Q1.What do you understand by ODBC ? How is JDBC different from ODBC? Ans: ODBC:(Open Database Connectivity) is aframework used by Microsoft to connect to various types of database. JDBC(Java Database Connectivity ) is a framework developed by Sun Java to help Java connect to different database. JDBC provides database connectivity from within java applications to database whereas ODBC provides database connectivity to non-java front end applications. But ODBC is language independent as it can work with any language but JDBC is language dependent as it works only for java. Q2. Write down the steps to connect MySQL to Java Ans: Steps to connecting to MySQL from Java:

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=”username”&password=”password”

UNIT-3: RELATIONAL DATABASE MANAGEMENT SYSTEM Database: A database is an organized collection of data. Software used to manage databases is called Data Base Management System (DBMS).

Relational Database: A database in which the data is stored in the form of relations (also called tables) is called a Relational Database. In other words a Relational Database is a collection of one or more tables.

RDBMS: A DBMS used to manage Relational Databases is called an RDBMS (Relational Data Base Management System). Some popular RDBMS software available are: Oracle, MySQL, Sybase, Ingress Benefits of using a DBMS are:

a. Redundancy can be controlled b. Inconsistence can be avoided c. Data can be shared d. Security restrictions can be applied

Structure Query Language A non-procedural UGL used for querying upon relational database DDL: Data Definition Language Part of the SQL that facilitates defining creation/modification etc. of database object such as tables, indexes, sequences etc. DML: Data Manipulation Language. Part of the SQL that facilitates manipulation (additions/deletions/modification) of data which residing in the database tables. Meta Data Facts/data about the data stored in table. Data Dictionary A file containing facts/data about the data stored in table Relational Data Model In this model data is organized into tables i.e. rows and columns. These tables are called relations. The Network Data Model 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 In this model records are organized as trees rather than arbitrary graphs. Object Oriented Data Model Data and associated operations are represented by objects. An object is an identifiable entity with some characteristics and behavior. Relation: Table in Database Domain: Pool of values from which the actual values appearing Tuple: A row of a relation Attribute: A column of relation Degree: Number of attributes Cardinality: Number of tuples View: Virtual table that does not really exist in its own right Key: A column or a combination of columns which can be used to identify one or more rows (tuples) in a table Primary Key: Set of one or more attributes that can uniquely identify tuples with in the relation. Candidate Key: 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: A candidate key that is not primary key is called alternate key. Foreign Key: A non-key attribute, whose values are derived from the primary key of some other table.

• Transaction : Logical units of work (LOW) that must be succeed or fail in its entirety. An atomic operation, not divided into smaller operation.

• Transaction execution

A user of transaction in terms of work carried out by it.

• Transaction handling issue: More than one transaction executed at the same time in following two ways

Serially • Concurrently

• Transaction properties: (ACID)

• Atomicity: Either all operations of transaction (ALL OR NONE) execution or none. • Consistency: it implies that database was/is in a consistent state before/after the

start/end of transaction. • Isolation: Each transaction is independent i.e. each transaction is unaware of other. • Durability: After successful completion the changes made by it to the database persist

even if there is system failure. Differentiate between Candidate Key and Alternate Key in context of RDBMS Candidate Key: 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: A Candidate Key that is not a Primary key is called an Alternate Key. Differentiate between Candidate Key and Primary Key in context of RDBMS. Ans: Candidate Key: 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. Primary Key is a designated attribute or a group of attributes whose values can uniquely identify the tuples in the relation. Integrity Constraints Integrity constraints are the rules that a database must comply at all times. It determines what all changes are permissible to a database. Type Of Constraints

1. Column Constraint 2. Table Constraint

Different SQL commands

SNO Command, Syntax, and Purpose Category

1. Command: CREATE DATABASE Syntax: CREATE DATABASE <databasename>; Purpose: Creates a database with the specified name.

DDL

2. Command: Syntax:

Purpose:

CREATE TABLE CREATE TABLE <tablename>

(<column name1> <data type1> [,<column name2> <data type2>, . . <column nameN> <data typeN>] );

Creates a table with the specified name.

DDL

3. Command: Syntax:

Purpose

ALTER TABLE

ALTER TABLE <tablename> ADD <columnname> <datatype>;

ALTER TABLE <tablename> DROP <columnname>;

ALTER TABLE <tablename> MODIFY <column> <new_definition> Modifies the structure of a table

DDL

4. Command: Syntax:

Purpose:

USE USE <database_name>; Opens the specified database for use.

DML

5. Command: Syntax: Purpose:

SELECT DATABASE() SELECT DATABASE(); Shows the name of the current database

DML

6. Command: SHOW TABLES DML

Syntax: SHOW TABLES;

Purpose:

Shows a list of tables present in the current database.

7. Command: Syntax:

INSERT

INSERT INTO <tablename>

[<column1>, <column2>, ..., <columnn>] VALUES

DML

Purpose:

(<value1>, <value2>, ... <value n>); Inserts data into a table

8. Command:

Syntax:

Purpose:

SELECT

SELECT <* / column name / expression> , [<column name/Expression list>] FROM <table name> [WHERE <condition>] [ORDER BY <column name / expression> [ASC/DESC]]; There are multiple ways to use SELECT. These will be explained with the help of examples in this lesson. Retrieves data from a table

DML

9. Command: Syntax: Purpose:

DESCRIBE DESC[RIBE] <tablename>; Shows the structure of a table.

DML

10. Command: Syntax:

Purpose:

UPDATE UPDATE <tablename> SET <column name> = <value> [,<column

name> = <value>, …] [WHERE <condn>];

Updates/Modifies data in a table

DML

11. Command:

Syntax:

Purpose:

DELETE

DELETE FROM < tablename> [ Where < condition>];

Deletes data from a table

DML

Following are the clauses which can be used with SELECT command:

a. DISTINCT Used to display distinct values from a column of a table.

b. WHERE Used to specify the condition based on which rows of a table are displayed.

c. BETWEEN Used to define the range of values within which the column values must fall to make a condition true. Range includes both the upper and the lower values.

d. IN Used to select values that match any value in a list of Specified values.

e. LIKE Used for pattern matching of string data using wildcard characters % and _ .

f. IS NULL / NOT NULL

Used to select rows in which the specified column is NULL (or is NOT NULL)

g. ORDER BY Used to display the selected rows in ascending or in descending order of the specified column/expression.

Accessing Database in MySql : Through USE keyword we can start any database Syntax: USE <database Name>; Example: USE STUDENT; CREATING TABLE IN MYSQL Through Create table command we can define any table. CREATE TABLE <tablename> (<columnname> <datatype>[(<Size>)],……..); CREATE TABLE Student(SRollNo integer, Sname char(20)); INSERTING DATA INTO TABLE The rows are added to relations using INSERT command. INSERT INTO <tablename>[<columnname>] VALUES (<value>, <value>…); INSERT INTO student (Sid, Sname) VALUES (100,’ABC’); SELECT COMMAND: It lets us make queries on the database. SELECT * FROM tablename WHERE condition; SELECT * FROM student WHERE Sid=100; Eliminating Redundant Data DISTINCT keyword eliminates redundant data SELECT DISTINCT Sid FROM Student; Selecting from all the rows-ALL Keyword SELECt ALL Sid FROM Student; Viewing structure of table: DESCRIBE/DESC <tablename>; DESCRIBE student; Using column aliases: SELECT <column name> AS [columnalias][,…] FROM <tablename>;

SELECT rollno, name AS “studentname” FROM student; Condition based on a range: Keyword BETWEEN used for making range checks in queries. SELECT rollno, name FROM student WHERE rollno BETWEEN 10 AND 20; Condition based on a list: Keyword IN used for selecting values from a list of values. SELECT rollno, name FROM student WHERE rollno IN (10, 20, 60); Condition based on a pattern matches: Keyword LIKE used for making character comparison using strings 1. percent(%) matches any substring 2. underscore(_) matches any character SELECT rollno, name FROM student WHERE name LIKE ‘%ri’; 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>]; SELECT * FROM student WHERE marks>50 ORDER BY name; MySQL functions: A function is a special type of predefined command set that performs some operation and returns a single value.

1. String functions :(Lower / LCASE( ), Upper/UCASE( ), Concate( ), Instr( ), Length( ), RTrim( ),

LTrim( ), Substr( ) )

2. Numeric function :(Round( ), Truncate( ), Mod( ), Sign( ) )

3.Date functions:(Curdate( ), Date( ), Month( ), year( ), DayName( ), DayofMonth( ), DayofWeek( ),

DayofYear( ), Now( ), SysDate( ))

Creating tables with SQL Constraint : CREATE TABLE command is used to CREATE tables CREATE TABLE tablename (columnname datatype size, …);

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 (Srollno integer NOT NULL, …); CREATE TABLE student (Srollno integer UNIQUE, …); CREATE TABLE student (Srollno integer NOT NULL, Sclass integer, Sname varchar(30), Sclass DEFAULT 12 ); CREATE TABLE student (Srollno integer CHECK (Srollno>0), Sclass integer, Sname varchar(30)); CREATE TABLE student (Srollno integer NOT NULL PRIMARY KEY, Sclass integer, Sname varchar(30)); CREATE TABLE teacher (Tid integer NOT NULL, FOREIGN KEY (Studentid ) REFRENCES student (Sid)); Inserting data into table: INSERT INTO command is used to insert data into table INSERT INTO tablename VALUES (value1,….); INSERT INTO student VALUES (1,’Ram’,12); Modifying data in tables: Existing data in tables can be changed with UPDATE command. UPDATE student SET Sclass=11 WHERE Sname=’Ram’; Deleting data from tables: Tuples in a table can be deleted using DELETE command. DELETE FROM student WHERE Srollno>10;

Aggregate Functions- MySQL provides Aggregate or Group functions which work on a number of values of a column/expression and return a single value as the result.

S.No. Aggregate Function Purpose

1 MAX() Returns the MAXIMUM of the values under the specified column/expression.

2 MIN() Returns the MINIMUM of the values under the specified column/expression.

3 AVG() Returns the AVERAGE of the values under the specified column/expression.

4 SUM() Returns the SUM of the values under the specified column/expression.

5 COUNT() Returns the COUNT of the number of values under the specified column/expression.

GROUP BY: GROUP BY clause is used in a SELECT statement in conjunction with aggregate functions to group the result based on distinct values in a column.

HAVING: HAVING clause is used in conjuction with GROUP BY clause in a SELECT statement to put condition on groups.

WHERE Vs HAVING: WHERE is used to put a condition on individual row of a table whereas HAVING is used to put condition on individual group formed by GROUP BY clause in a SELECT statement.

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. Union is an operation of combining the output of two SELECT statements. ALTER TABLE Command: used to Add, Remove, and Modify columns of a table. It can also be used to Add and Remove constraints. DROP TABLE Command: DROP TABLE command is used to delete tables.

DROP TABLE <tablename>;

Consider the following tables item and Customer. Write SQL Commands for the statement (i) to (iv) and give outputs for SQL queries (v) to (viii).

Table: ITEM

I_ID ItemName Manufacture Price

PC01 Personal Computer ABC 35000

LC05 Laptop ABC 55000

PC03 Personal Computer XYZ 32000

PC06 Personal Computer COMP 37000

LC03 Laptop PQR 57000

Table: CUSTOMER

C_ID CustomerName City l_ID

01 MRS REKHA Delhi LC03

06 MANSH Mumbai PC03

12 RAJEEV Delhi PC06

15 YAJNESH Delhi LC03

16 VIJAY Banglore PC01

(i) To display the details of those customers whose city is Delhi. (ii) To display the details of item whose price is in the range of 35000 to 55000 ( both

values included) (iii) To display the customer name, city from table Customer, and itemname and price from

table Item, with their corresponding matching I_ID. (iv) To increase the price of all items by 1000 in the table Item. (v) SELECT DISTINCT City FROM Customer; (vi) SELECT ItemName, MAX(Price), Count(*) FROM Item GROUP BY ItemName; (vii) SELECT CustomerName, Manufacturer FROM Item, Customer

WHERE Item.Item_Id=Customer.Item_Id (viii) SELECT ItemName, Price* 100

FROM Item WHERE Manufacture= ‘ABC’; Answer:

(i) SELECT * FROM CUSTOMER WHERE City = ‘Delhi’;

(ii) SELECT * FROM ITEM WHERE PRICE BETWEEN 35000 TO 55000;

(iii) SELECT CustomerName, City, ItemName, Price FROM CUSTOMER, ITEM WHERE CUSTOMER.I_ID = ITEM.I_ID;

(iv) UPDATE ITEM SET Price = Price + 1000 ;

(v) Delhi Mumbai

Banglore

(vi) Personal computer 37000 3

Laptop 57000 2

(vii)

(viii) Personal computer 3500000 Laptop 5500000 Consider the following tables Product and Clint. Write SQL commands for the statement (i) to (iv) and give outputs for SQL queries (v) to (viii)

Table: PRODUCT

P_ ID ProductName Manufacturer Price

TP01 Talcum Powder LAK 40

FW05 Face Wash ABC 45

BS01 Bath Soap ABC 55

SH06 Shampoo XYZ 120

FW12 Face Wash XYZ 95

Table:CLINT

C_ID ClientName City P_ID

01 Cosmetic Shop Delhi FW05

06 Total Health Mumbai BS01

12 Live Life Delhi SH06

15 Pretty Woman Delhi FW12

16 Dreams Banglore TP01 (i) To display the details of those Clients whose City is Delhi. (ii) To display the details of Products Whose Price is in the range of 50 to 100(Both values

included). (iii) To display the ClientName, City from table Client, and ProductName and Price from

table Product, with their corresponding matching P-ID. (iv) To increase the Price of all Products by 10. (v) SELECT DISTINCT City FROM Client” (vi) SELECT Manufacturer, MAX(Price), Min(Price), Count(*) FROM Product GROUP BY

Manufacturer; (vii) SELECT ClientName, ManufacturerName FROM Product, Client

WHERE Client.Prod-ID=Product.P_ID; (viii) SELECT ProductName, Price * 4 FROM Product;

MRS REKHA PQR

MANSH XYZ

RAJEEV COMP

YAJNESH PQR

VIJAY ABC

Answer:

(i) SELECT * FROM CLIENT WHERE City=”Delhi”;

(ii) SELECT * FROM PRODUCT WHERE Price between 50 to 100;

(iii) SELECT ClientName, City, ProductName, Price FROM CLIENT, PRODUCT WHERE CLIENT.P_ID=Product.P_ID;

(iv) Update PRODUCT SET Price=Price+10 (v) Delhi

Mumbai Bangalore

(vi) LAK 40 40 1 ABC 55 45 2 XYZ 120

95 2

(vii) Cosmetic Shop Face Wash Total Health Bath Soap Live Life Shampoo Pretty Woman Face Wash Dreams

Talcum Powder

(viii) Talcum Powder 160 Face Wash 180 Bath Soap 220 Shampoo 480 Face Wash 380 Consider the following tables. Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (viii) TABLE: SENDER

SenderID SenderName SenderAddress SenderCity

ND01 R Jain 2, ABC Appts New Delhi

MU02 H Sinha 12, Newton Mumbai

MU15 S Jha 27/A, Park Street Mumbai

ND50 T Prasad 122-K, SDA New Delhi TABLE: RECIPIENT

RecID SenderID RecName RecAddress RecCity

KO05 ND01 R Bajpayee 5, Central Avenue Kolkata

ND08 MU02 S Mahajan 116, A Vihar New Delhi

MU19 ND01 H Singh 2A, Andheri East Mumbai

MU32 MU15 P k Swamy B5, C S Terminus Mumbai

ND48 ND50 S Tripathi 13, B1 D, Mayur Vihar

New Delhi

(i) To display the names of all Senders from Mumbai (ii) To display the RecID, SenderName, SenderAddress, RecName, RecAddress for every

Recipient (iii) To display Recipient details in ascending order of RecName (iv) To display number of Recipients from each city (v) SELECT DISTINCT SenderCity FROM Sender; (vi) SELECT A.SenderName, B.RecName FROM Sender A, Recipient b WHERE A.SenderID=B.SenderID AND B.RecCity= ‘Mumbai’; (vii) SELECT RecName, RecAddress FROM Recipient WHERE RecCity NOT IN (‘Mumbai’, ‘Kolkata’); (viii) SELECT RecID, RecName FROM Recipient WHERE SenderID= ‘MU02’ or SenderID= ‘ND50’; Answer: (i) SELECT SenderName FROM Sender WHERE SenderCity= “Mumbai”; (ii) SELECT RecID, SenderName, SenderAddress, RecName, RecAddress FROM Sender, Recipient WHERE Sender.SenderID= Recipient.SenderID; (iii) SELECT * FROM Recipient ORDER BY RecName Asc; (iv) SELECT RecCity, count (*) FROM Recipient GROUP BY RecCity; (v) New Delhi Mumbai (vi) R Jain H Singh

S Jha

P K Swamy

(vii) S Mahajan 116, A Vihar S Tripathi

13, B1 D, Mayur Vihar

(viii) ND08 S Mahajan ND45 S Tripathi Consider the following tables Consignor and Consignee. Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (viii).

TABLE: CONSIGNOR

CnorID CnorName CnorAddress City

ND01 R Singhal 24, ABC Enclave

New Delhi

ND02 Amit Kumar 123, Palm Avenue

New Delhi

MU15 R Kohli 5/A, South Street

Mumbai

MU50 S Kaur 27-K, Westend Mumbai

TABLE: CONSIGNEE

CneeID CnorID CneeName CneeAddress City

MU05 ND01 Rahul Kishore 5, Park Avenue

Mumbai

ND08 ND02 P Dhingra 16/J, Moore Enclave

New Delhi

KO19 MU15 A P Roy 2A, Central Avenue

Kolkata

MU32 ND02 S Mittal P 245, AB Colony

Mumbai

ND48 MU50 B P Jain 13, Block D, A Vihar

New Delhi

(i) To display the names of all Consignors from Mumbai. (ii) To display the CneeID, CnorName, Cnoraddress, CneeName, CneeAddress for every

Consignee. (iii) To display Consignee details in ascending order of CneeName. (iv) To display numbers of Consignors from each city.

(v) SELECT DISTINCT City FROM Consignee; (vi) SELECT A.CnorName, B.CneeName FROM Consignor A, Consignee B WHERE A.CnorID=B.CnorID AND B.CneeCity= ‘Mumbai’; (vii) SELECT CneeName, CneeAddress FROM Consignee WHERE CneeCity NOT IN ( ‘Mumbai’, ‘Kolkata’); (viii) SELECT CneeID, CneeName FROM Consignee WHERE CnorId= ‘MU15’ OR CnorId= ‘ND01’; Answer: (i) SELECT CnorName FROM CONSIGNOR WHERE City= “Mumbai”; (ii) SELECT CneeID, CnorName, CnorAddress, CneeName, CneeAddress FROM CONSIGNOR, CONSIGNEE WHERE CONSIGNOR. CnorID= CONSIGNEE.CNorID (iii) SELECT * FROM CONSIGNEE ORDER BY CneeName ASC; (iv) SELECT CneeCity, Count (CneeCity)) FROM CONSIGNEE GROUP BY CneeCity (v) There is no column by the name City in the table CONSIGNEE. However, if we change the

column from City to CneeCity, the query result as: CneeCity Mumbai New Delhi Kolkata (vi) R. Singhl Rahul kishore Amit Kumar

S Mittal

(vii) P Dhingra 16/J Moore Enclave BP Jain 13, Block D, A Vihar (viii) MU05 Rahul kishore

KO19 A P Roy

Unit 4- IT Applications

E-GOVERNANCE:

It refers to application of electronic means in governance with an aim of fulfilling the requirements of common man at affordable costs and in fastest possible time.

E-BUSINESS:

It refers to any form of transaction (exchange) that uses an electronic medium to facilitate the transaction.

E-LEARNING: It is a flexible term used to describe a means of teaching through technology such as a network, browser, CDROM or DVD multimedia platform. .

Some E-learning websites are: www.moodle.org, w3schools.c om

GUI AND ITS IMPORTANCE

GUI (Graphical User Interface) that uses a graphical interface to interact with the user also it is a collection of elements called objects. o Front End:

It is the end that interacts with the user and collects inputs from the user. o Back End:

It is the end that is not visible but that processes the user requests as received by the front –end.

FRONT-END INTERFACE Front end and back end are generalized terms that refer to the initial and the end stages of a process. The front end is responsible for collecting input in various forms from the user and processing it to conform to a specification the back end can use. The front end is an interface between the user and the back end.

Design of a GUI Front-end

• Visibility of system status • Match between system and the real world • User control and freedom • Consistency and standards • Error prevention • Recognition rather than recall • Flexibility and efficiency of use • Aesthetic and minimalist design • Help users recognize,diagnose,and recover from errors • Help and documentation

Contents and Features of Front-end

The graphical objects that facilitate with users are also known as User-Interface Objects

Features of Front-end: Display features • Functionality features • Display Features of Fronts End • Conventional use of Icon • Use of Conventionality Reserved Words • Provides Visual Feedback(Also Responsiveness features) • Rare Use of Audible Feedback • Use Controls Correctly in Conventional way

Functionality features

• Provided Keyboard Support(Performance features) • Effective Usage of Modal and Modeless Windows(Performance features) • Takes Validates and its types • Required fields • Formatting • Logical

Security features

BACKEND DATABASE A database is collection of interrelated data and a database system is basically computers based recordkeeping system.

FRONT_END AND DATABASE CONNECTIVITY

Database connectivity refers to a programming interface that lets a front-end access a database on a backend, via some means.

The benefits of database connectivity include

• Almost any database can be accessed from within application code if its connectivity • Drivers is available • Distribution of apply logic in terms of front-end and backend leads to betters

performance

Sample Question Paper INFORMATICS PRACTICES Class-XII

TIME : 3 hours MM : 70

1 (a) Tara Nathani wants to upload and download files from/to a remote intenet server, write the name of the relevant communication protocol, which will let her do the same.

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

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

(d) Which of the following is not a characteristic of Open Source Software?

• Its source code is available for modification

• It is owned by a company or an individual

• It can be downloaded from internet

(e) Jai Khanna is confused between the terms Domain Name and URL. Explain the difference with the help of appropriate examples of each.

(f) Define any two threats to Network Security.

(g) Differentiate between Star and Bus Topology of networks.

2 (a) While working in Netbeans, Rajmeeta included a Listbox in the form. Now she wants the list of her friends' names to be displayed in it. Which property of Listbox control should she use to do this?

(b) What is the purpose of default clause in a switch statement?

(c) Which HTML tag inserts a horizontal straight line on a web page?

(d) How is <P> tag different from <BR> tag in HTML?

(e) How many times will each of the following loops execute? Which one of these is an entry control loop and which one is an exit control loop?

Loop1:

int sum = 0, i = 5;

do

{ sum += i;i++;} while (i<5);

Loop2: int sum = 0, i = 5;

while (i<5)

{sum += i;i++;}

(f) Write a function in java that takes two numbers two numbers as input from textfields and

displays their sum.

(g) How are tags used in XML different from tags in HTML? Write 2 points.

3 (a) If a database "Employee" exists, which MySql command helps you to start working in that database?

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

(c) Pooja, a students 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:

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 when she created the table?

(e) Distinguish between a Primary key and Candidate key with the help of suitable ex- ample of each.

(f) The LastName column of a table "Directory" is given below: LastName Batra Sehgal Bhatia

Sharma Mehta

Based on this information, find the output of the following queries:

a) SELECT lastname FROM Directory WHERE lastname like "_a%";

b) SELECT lastname FROM Directory WHERE lastname not like "%a";

(g) A table "Stock" in a database has 5 columns and contains 17 records. What is the degree and

cardinality of this table? 4 (a) Define a class with reference to object oriented programming.

(b) What will be the content of jTextField1 after executing the following code:

int Num = 6; Num = Num + 1; if ( Num > 5)

jTextField1.setText(Integer.toString(Num)); else jTextField1.setText(Integer.toString(Num+5));

(c) What will be the contents of jTextArea1 after executing the following statement:

jTextArea1.setText("Object\nOriented\tProgramming");

(d) Rewrite the following program code using switch statement:

if (d == 1)

day = "Monday"; else if (d == 2) day = "Tuesday"; else if (d == 3)

day = "Wednesday";

else

day = "-";

(e) The following code has some error(s). Rewrite the correct code underlining all the cor- rections made:

int i=2; j=5;

while j>i

{jTextField1.getText("j is greater");

j--;++i;} JOptionPane.showMessageDialog("Hello");

(f) What will be the contents of jTextField1 and jTextField2 after executing the following code:

String s = "ABC Micro Systems"; jTextField1.setText(s.length()+" ");

jTextField2.setText(s.toLowerCase());

(g) Glamour Garments has developed a GUI application for their company as shown below :

The company accepts payments in 3 modes- cheque , cash and credit cards.The discount given as per mode of payment is as follows.

Mode of Payment Discount Cash 8% Cheque 7% Credit Card Nil

If the Bill Amount is more than 15000 then the customer gets an additional discount of 10% on Bill Amount.

(i) Write the code to make the textfields for Discount (named txtDisc) and Net Amount (named txtNetAmt) uneditable.

(ii) Write code to do the following:

a. When "Calculate Discount" button is clicked the discount should be calculated as per the given criteria and it should be displayed in the discount textfield. "Calculate Net Amount" button (named btnCalcNetAmt) should also be enabled.

b. When "Calculate Net Amount" button is clicked the net amount should be calculated and it should be displayed in the net amount textfield.

5 (a) Explain the purpose of DDL and DML commands used in SQL. Also give two examples of each.

(b) Write the output of the following SQL queries:

a) SELECT ROUND(6.5675, 2);

b) SELECT TRUNCATE(5.3456, 1);

c) SELECT DAYOFMONTH('2009-08-25');

d) SELECT MID('Class 12', 2,3);

(c) Consider the table TEACHER given below. Write commands in SQL for (1) to (4) and output for (5) to (8)

TEACHER

ID Name Department Hiredate Category Gender Salary

1 Tanya Nanda SocialStudies 1994-03-17 TGT F 25000

2 Saurabh Sharma Art 1990-02-12 PRT M 20000

3 Nandita Arora English 1980-05-16 PGT F 30000

4 James Jacob English 1989-10-16 TGT M 25000

5 Jaspreet Kaur Hindi 1990-08-01 PRT F 22000

6 Disha Sehgal Math 1980-03-17 PRT F 21000

7 Siddharth Kapoor Science 1994-09-02 TGT M 27000

8 Sonali Mukherjee Math 1980-11-17 TGT F 24500

i. To display all information about teachers of PGT category. ii. To list the names of female teachers of Hindi department.

iii. To list names, departments and date of hiring of all the teachers in ascending order of date of joining

iv. To count the number of teachers in English department. v. SELECT

MAX(Hiredate) FROM Teacher;

vi. SELECT DISTINCT(category) FROM teacher;

vii. SELECT COUNT(*) FROM TEACHER WHERE Category = "PGT"

viii. SELECT AVG(Salary) FROM TEACHER group by Gender;

6 (a) Write an SQL query to create the table 'Menu' with the following structure: Field Type Constraint ItemCode Varchar(5) Primary Key ItemName Varchar(20)

Category Varchar(20) Price Decimal(5,2)

(b) In a database there are two tables 'Customer' and 'Bill' as shown below:

Customer

CustomerID CustomerName CustAddress CustPhone

1 Akhilesh Narang C4,Janak Puri,Delhi 9811078987

2 Purnima Williams B1, Ashok Vihar,Delhi 9678678711

3 Sumedha Madaan 33, South Ext.,Delhi 6767655412

Bill

BillNo CustID Bill_Amt

1 2 12000

2 1 15000

3 2 13000

4 3 13000

5 2 14000

(i) How many rows and how many columns will be there in the Cartesian product of these two tables?

(ii) Which column in the 'Bill' table is the foreign key?

(c) Consider the tables HANDSETS and CUSTOMER given below:

Handsets

SetCode SetName TouchScreen PhoneCost

N1 Nokia 2G N 5000

N2 Nokia 3G Y 8000

B1 BlackBerry N 14000

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.

(ii) Display the Customer Details for each customer who uses a Nokia handset.

(iii) S elect SetNo, SetName from Handsets, customer where SetNo = SetCode and CustAddress =

'Delhi';

7 (a) How does e-business improve customer satisfaction- Write one point.

(b)How has our society benefited from e-governance? Write 2 points.

(c) Vijayan works for the Customs Department. He wishes to create controls on a form for the following functions. Choose appropriate controls from Text box, Label, Option button, Check box, List box, Combo box, Command button and write in the third column.

SNo Control used to: Control

1 Enter last name

2 Enter Gender

3 Choose City from a list of cities

4 Submit Form

Sample Question Paper - I MARKING SCHEME INFORMATICS PRACTICES

Class XII

Time: 3 hours M.M.: 70 1(a) FTP. (1 Mark for Abbreviation and/or Full Form) (b) PAN (1 Mark for correct answer) (c) Telephone Cable, Ethernet Cable, Co-axial Cable, Optical Fiber (1 Mark for correct answer) (d) It is owned by a company or an individual (1 Mark for correct answer) (e) A URL (Uniform Resource Locator) is the complete address of a document on the

web, whereas a domain name specifies the location of document's web server. A domain name is a component of the URL used to access web sites.

For example the web address http://www.example.net/index.html is a URL.

In this URL www.example.net is the domain name. (2 marks for correct explanation of difference with the help of example) (f) Denial of Service: It refers to any threat that prevents the legitimate users from

accessing the network resources or processing capabilities. Snooping: It refers to any threat that results in an unauthorized user obtaining information about a network or the traffic over that network.

(1 mark each for correctly defining any two threats) (g) Star Topology: It is characterized by central

switching node (communication controller) and unique path (point to point link) for each host. It is easy to add and remove hosts easily. STAR Bus Topology: It is characterized by common transmission medium shared by all the connected hosts, managed by dedicated nodes. It offers simultaneous flow of data and control.

BUS

(2 marks for correct difference) 2(a) Model.

( 1 mark) (b) Default clause is used to handle the case when no match of any case in the switch

statement is found.

( 1 mark for correct answer) (c) <HR> tag. (1 mark for correct answer) (d) <P> tag inserts a blank line and starts a new paragraph whereas <BR> tag forces

text to a new line like the <P> tag, but without inserting a blank line.

(1 mark for correct difference)

(e) Loop1 will execute once and Loop2 will execute 0 times. Loop1 is exit control loop and Loop2 is entry control loop.

( ½ mark for each correct no. of times of loop execution) ( ½ mark each for correctly identifying the type of loop)

(f) Int

a=Integer.parseInt(jTextField1.getText());

int

b=Integer.parseInt(jTextField2.getText());

int c;

c=a+b;

jTextField3.setText(""+c);

( ½ mark for getting the input) (1 mark for calculating sum) ( ½ mark for displaying in text field)

(g) XML tags HTML tags New tags can be created using XML tags cannot be empty tags.

New tags cannot be created using HTML tags can be empty tags.

(1 mark for each correct difference) 3(a) Use employee (1 mark for correct answer) (b) Alter table (1 mark for correct answer) (c) Select * from Book where Price IS NULL; (1 mark for correct answer) (d) She specified 'NOT NULL' constraint for that column while creating the table. (1 mark for correct answer) (e) Candidate key is a column or a group of columns that is capable of becoming the

primary key. A table can have multiple candidate keys but it can have only one primary key. Example:

A table STUDENT contains the columns AdmNo, RollNo,Name, Address, PhoneNo. In this table AdmNo and RollNo (both are unique for every row in the table) are candidate keys. Out of these any one can be chosen as the primary key of the table.

(1 mark for correct difference, 1 mark for suitable example) (f) a) Last Name: Batra

b) Last Name: Sehgal

(1 mark for each correct answer) (g) Degree = 5. Cardinality = 17 (1 mark for each part) 4(a) A class is an abstract user-defined data type that is used as a blueprint to define the

objects of that class. ( 1 mark for correct definition) (b) 7

(1 mark for correct answer) (c) Object Oriented Programming

(1 mark for contents to be printed) ( ½ mark each for writing the effect of '\n' and ' \t')

(d) switch(d)

{ case 1:

day = "Monday";

break; case 2:

day = "Tuesday";

break; case 3:

day = "Wednesday";

break; default: day = "-";}

(2 marks for correct answer)

(e) int i=2, j=5;

while (j>i)

{ jTextField1.setText("j is greater");

j--;

++i;

} jOptionPane.showMessageDialog(this,"Hello");

( ½ mark each for identifying and correcting 4 errors) (f) jTextField1: 17

jTextField2: abc micro systems (1 Mark for 17)

(1 Mark for abc micro systems)

(g) (i) txtDisc.setEditable(false);

txtNetAmt.setEditable(false);

(1 mark each for both parts)

(ii) (a) float BillAmt, NetAmt, Disc; String ModeofPayment;

BillAmt = Float.parseFloat(txtBillAmt.getText()); ModeofPayment = (String)

cmbMode.getSelectedItem(); if (ModeofPayment.equals("Cash"))

Disc = BillAmt*8/100;

else if (ModeofPayment.equals("Cheque")) Disc = BillAmt*7/100;

else Disc = 0;

if (BillAmt > 15000)

Disc = Disc + BillAmt*10/100; btnCalcNetAmt.setEnabled(true); txtDisc.setText(Disc+"");

( ½ Mark for variable declaration with appropriate data types) ( ½ Mark for extracting Bill Amount correctly from the text box) ( ½ Mark for extracting Mode of Payment correctly from Combo Box) ( ½ Mark for calculating correct Discount based on Mode of Payment) ( ½ Mark for calculating Discount based on Bill Amount and displaying it) ( ½ Mark for Enabling btnCalNetAmt)

(b) float BillAmt, NetAmt, Disc;

BillAmt = Float.parseFloat(txtBillAmt.getText()); Disc =

Float.parseFloat(txtDisc.getText()); NetAmt = BillAmt -

Disc; txtNetAmt.setText(NetAmt+"");

( ½ Mark for calculating Net Amount) ( ½ Mark for Displaying 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) a) 6.57 b) 5.3 c)25 d) las ( ½ Mark each for each correct answer)

(c) i. SELECT * FROM teacher WHERE category = 'PGT';

ii. SELECT name FROM teacher WHERE Gender = 'F' AND Department = 'Hindi';

iii. SELECT name, department, hiredate FROM teacher ORDER BY hiredate;

iv. SELECT count(*)FROM teacher WHERE department = 'English';

v. 1994-09-02 vi.

TGT PRT PGT

vii. 1

viii. 24500 24000

(1 Mark each for each correct query) (½ Mark each for each correct output)

6(a) CREATE TABLE Menu

(itemcode varchar(5) primary key, itemname varchar(20),

category varchar(20), price decimal(5,2)

);

( ½ Mark for CREATE TABLE Menu) ( ½ Mark for appropriately putting Primary Key constraint) ( ½ Mark for correct data types) ( ½ Mark for correct syntax of the query)

(b) (i) 15 rows and 7 columns

(ii) CustID

( ½ Mark each for stating number of rows and columns) (1 mark for choosing the correct foreign key)

(c) (i) SELECT CustNo, CustAddress, SetName

FROM Customer, Handsets

Where SetNo = SetCode;

(ii) SELECT Customer.* FROM Customer, HandSets

WHERE SetNo = SetCode and setname like "Nokia%";

(iii) setno setname N2 Nokia 3G B1 BlackBerry

(i) (1 mark for correct use of SELECT and FROM) (1 mark for correct use of WHERE clause )

(ii) (1 mark for correct use of SELECT and FROM) (1 mark for correct use of WHERE clause ) (iii)

(1 mark for each correct line of output)

7(a) • Goods sold through e-business are generally cheaper as cost incurred in e- business is less compared to setting up a traditional business.

• Customers can receive highly customizable service.

• Even Remote area customers are reached in e-business.

• Sellers have better understanding of their customers' needs as customers com- municate through e-mails.

(1 Mark for any correct point)

(b) 1. A lot of productive time of government servants and general public is saved.

2. Transparency has increased and therefore cheating cases have been reduced.

( 1 Mark each for any 2 correct points)

(c) SNo Control used to: Control 1 Enter last name Text Field 2 Enter Gender Option Button 3 Choose City from a list of cities List Box or Combo Box 4 Submit Form Button (Command)

( ½ Mark each for each correct answer)

Sample Paper Grade XII

Informatics Practices (Code: 065) 2014-15

Time: 3Hrs. MM: 70

1 (a) Draw a network layout of bus topology to connect 5 client computers and 1 server computer.

(1)

(b) Mr. John wants to prevent unauthorized access to/from his company's local area network. Write the name of a system (software/ hardware), which he should install to do the same.

(1)

(c) Which of the following are open source softwares :

GNU, MS-Office, BOSS, Windows OS

(1)

(d) Name the government organization that contributes to the growth of FOSS in India. (1)

(e) Read the given activities carefully and mention whether the activity is snooping or eavesdropping:

i. Getting someone’s login information by casually watching what he/she is typing. ii. Setting up unauthorized parallel telephone lines iii. Installing some software/hardware which captures the data while on its

way. iv. Reading the files on someone’s computer in an unauthorized manner.

(2)

(d) Kristen has typed the following text in the address bar:

http://www.cbse-international.com/help.htm

Identify and differentiate the URL and Domain name with reference to the example given above.

(2)

(e) Chanakya has to write a paragraph in English on nobel laureates as a part of his holiday homework. He is using a software in which he types the text in Hindi and the software automatically converts the text into English. For example, if he types “ इस इन ” the software converts it into “Nobel Prize is given in six categories”.

What kind of text entry is it – phonetic text entry OR keymap based text entry? How is it different from the other kind of text entry?

(2)

2 (a) In a java program Rajat wants to use a variable to store the quantity of an item which may be in whole numbers or decimals. Write a suitable java statement to declare the variable for the above mentioned purpose.

(1)

(b) What will be the values of num and num1 after execution of the following code:

int num,num1=0; for(num=100;num<=101;num++) { num1= num+2; --num1; }

(1)

(c) Zia is working with list box. She has placed a list control on her form to display the list of all items available in her shop. She wants to allow the user to select multiple items from her list control. Which property of jList should she use to do the same?

(1)

(d) Raman has typed the following code: int ch=Integer.parseInt(jTextField1.getText()); switch(ch) { case 1:jTextField2.setText("Service"); case 2: jTextField2.setText("Complaint"); case 3: jTextField2.setText("Operator"); break; default: jTextField2.setText("Not a valid entry"); }

On entering the value 1, 2 or 3, he is getting the same output. Mention the possible reason for the same.

(1)

(e) Jennifer wants to write html code to create an ordered list starting with “c”. Help her in writing the code.

(2)

(f) Write any two advantages of xml over html. (2)

(g) Write java code that take any three digit number from the user in jTextField1, calculate the sum of the digits and display it in separate textfield named jTextField2.

For example If the number entered is 432, it should answers as 9 (i.e. 4+3+2).

(2)

3 (a) Saumya had previously created a table named ‘Product’ in a database using MySQL. Later on she forgot the table structure. Suggest her suitable MySQL command through which she can check the structure of the already created table.

(1)

(b) Roli wants to list the names of all the tables in her database named ‘Gadgets’. Which command (s) she should use to get the desired result.

(1)

(c) Kuhu has already created a table ‘Hospital’ as shown below: Patient_No Patient_Name Disease Age Charges P001 Alya Viral Fever 14 500 P002 Kavita Lung Infection 16 1500 P003 Manya Cough and Cold 20 500 P004 Amar Bone Fracture 22 2500 P005 Deep Viral Fever 15 500

Now she wants to add a new column ‘Address’ to the above given table. Suggest

(1)

(d) Amit works as a database administrator in a Multinational bank. He wants to undo the changes made in the current transaction. Suggest to him a suitable MySQL command for the same.

(1)

(e) What will be the output of the following queries on the basis of Employee table:

+-------+-------+--------+ | EmpId | EName | Salary |

+-------+-------+--------+ | A001 | Bob | 5600 | | A002 | John | NULL | | A003 | Tom | 5000 | +-------+-------+--------+

(i) Select avg(Salary) from Employee;

(ii) Select Salary+100 from Employee where EmpId='A002';

(2)

(f) A table named ‘GAMES’ has the following contents:

GCode GameName Number_of_Players PrizeMoney 101 Carom Board 2 5000 102 Badminton 2 12000 103 Table Tennis 4 8000

Write the output that will be displayed by statements (i) and (ii). SELECT * FROM GAMES; SET AUTOCOMMIT = 0; INSERT INTO GAMES VALUES(105,'CHESS’,2,9000); ROLLBACK; SAVEPOINT S1; SELECT * FROM GAMES; ------------ (i) INSERT INTO GAMES VALUES(108,'LAWN TENNIS’,4,25000); SAVEPOINT S2; INSERT INTO GAMES VALUES(109,'CRICKET’,11,20000); ROLLBACK TO S2; SELECT * FROM ITEM; ------------ (ii)

(2)

(g) Observe the given statements carefully:

(i) SELECT * FROM club WHERE salary between 20000 and 30000; (ii) SELECT * FROM club WHERE salary IN ( 20000, 30000); (iii) SELECT * FROM club WHERE salary >= 20000 and salary <=30000; (iv) SELECT * FROM club WHERE salary = 20000 OR salary = 30000;

Make pairs of the equivalent SQL statements given above (which give the same output) and place each pair in a group.

(2)

4 (a) Define inheritance with reference to object oriented programming. (1)

(b) Given a String object named 'code' having value as “908” stored in it. What will be result of the following?

JOptionPane.showMessageDialog(null, " " +(code.length( )+ Integer.parseInt(code)));

(1)

(c) What will be displayed in jTextField1 and jTextField2 after the following code is executed:

int num = 35 , num1 = 46 ;

jTextField1.setText( num + num1 + " " ) ; jTextField1.setText( " " + num + num1 ) ;

(1)

(d) Find output of the following java code snippet: String word="Highrise";

String wordlc = word.toLowerCase(); for

(int i = 0; i < wordlc.length(); i+=4)

{

String extstr = wordlc.substring(i,i+2); jTextArea1.append(extstr+"\

n");

}

(2)

(e) Rewrite the following code using while loop: int a,b;

for(a=10,b=4;a<=16;a++,b+=2){ jTextArea1.append(""+a+

+);}

JOptionPane.showMessageDialog(null,"Finished!!!");

(2)

(f) The following code has error(s). Rewrite the correct code underlining all the corrections made : String str1 = SeemaSurakshabal ; int b; for(int b = 0 ; b < 3 , b++ ) { jTextArea1.showText(str1+"\n" ) ; str1 = str1 + b ; }

(2)

(g) Ms. Rakhi works in an International Bank as an IT Head. She designed a simple interest calculator program as shown below:

The interest rate is given based on the account type as shown below:

ACCOUNT TYPE INTEREST RATE %

SAVING 4 %

RECURRING DEPOSIT 6

% FIXED DEPOSIT 8 %

i. Write the code required for ‘INTEREST RATE’ button to display interest rate as per the above given criteria. ii. Write the code required for ‘SI’ button to calculate and display ‘Simple Interest’ based on the given formulae:

SI=(amount*interest_rate*duration)/100;

(6)

5 (a) Observe the table ‘Club’ given below: Club

Member_id Member_nam e

Address Age Fees

M001

Sumit New Delhi 20 1000

M002

Nisha Gurgaon 19 1500

M003

Niharika New Delhi 21 2100

M004

Sachin Faridabad 18 1500

i. What is the cardinality and degree of the above given table? ii. If a new column contact_no has been added and two more members have

joined the club then how these changes will affect the degree and cardinality

2

of the above given table.

(b) Write the output of the following SQL queries:

i. SELECT INSTR(‘INTERNATIONAL’, ‘NA’); ii. SELECT LENGTH(CONCAT(‘NETWORK’,’ING’)); iii.SELECT ROUND(563.345,-2); iv. SELECT DAYOFYEAR(‘2014-01-30’);

2

(c) Pranay, who is an Indian, created a table named “Friends” to store his friend’s detail. Table “Friends” is shown below. Write commands in SQL for (i) to (iv) and output for (v) to

(vii).

i. To display list of all foreigner friends. ii. To list name, city and country in descending order of age. iii. To count

how many friends have email id on gmail. iv. To list name and city of those friends who don’t have an email id. v. Select name,country from friends where age>12 and name like ‘A%’; vi. Select ucase(concat(name,”*”,city)) from friends where

country like ‘Denmark’; vii. Select mid(name,1,4) as “UID” from friends where

country like ‘USA’;

6

6 (a) Write SQL query to create a table ‘Bank_Customer’ with the following structure: Field Type Constraint Acc_No Integer Primary

Key Cust_Name Not Null

(2)

S_No Name Age City Country Email_id 1 Alice 14 Washington USA [email protected] 2 Charles 12 Copenhagen Denmark [email protected]

3 Angel 16 Chicago USA [email protected] 4 Jasmine 15 Sydney Australia [email protected] 5 Raj 14 New Delhi India [email protected] 6 Jette 13 Nykobing Denmark [email protected] 7 Alexender 15 Melbourne Australia NULL 8 Shashank 16 Banglore India NULL

Varchar(20) Cust_Add

Varchar(20)

Cust_City Varchar(20)

(b) In a Bank’s database, there are two tables ‘Customer_info’ and ‘Transaction Detail’ as shown below:

Customer_info

Acc_No Cust_Name Cust_Add Cust_City Cust_Phone

1001001 Ram Vasundhara Enclave New

Delhi

(2)

8710557614

1001002 Kavita Punjabi Bagh New Delhi 7123545233 1001003 Raj Civil Lines Allahabad 9872136576

1001004 Sohan Krishnanagar Kanpur

9921305453

T003 1001001 Debit 2000 T004 1001004 Credit 6000 T005 1001001 Credit 4000

i. Is it possible to have primary key and foreign key in one table? Justify your

Transa

ction_Detail

Trans_Id Acc_No Transaction_Type Amount

T001 1001001 Credit 5000

T002 1001002 Credit 10000

(c) Consider the tables ‘Flights’ & ‘Fares’ given below:

Flights

FNO SOURCE DEST NO_OF_FL NO_OF_STOP

IC301 MUMBAI BANGALORE 3

2

IC799 BANGALORE KOLKATA 8

3

MC101 DELHI VARANASI 6

0

IC302 MUMBAI KOCHI 1

4

AM812 LUCKNOW DELHI 4

0

MU499 DELHI CHENNAI 3

3

Fares

FNO AIRLINES

FARE

TAX

IC301 Indian Airlines

9425 5

IC799 Spice Jet

8846 10

MC101 Deccan Airlines

4210 7

IC302 Jet Airways

13894 5

AM812 Indian Airlines

4500 6

MU499 Sahara

12000 4

With reference to these tables, write commands in SQL for (i) and (ii) and output for (iii) below:

i. To display flight number, source, airlines of those flights where fare is less than Rs. 10000. ii. To count total no of Indian Airlines flights starting from various cities.

(6)

iii. SELECT FLIGHTS.FNO, NO_OF_FL, AIRLINES FROM FLIGHTS,FARES WHERE FLIGHTS.FNO = FARES.FNO AND SOURCE=’DELHI’;

7 (a) What is the role of a good back-end in an IT application? (1)

(b) Identify e-Governance and e-Learning applications from the following:

i) On-line experiments in a virtual laboratory of a college.

ii)On-line application submission for change of address in the passport. iii) On-line bill payment of Water Charges to Jal Board of any state. iv) On-line

tutorials for physics.

(2)

(c) Raghuram is working as a Manager in the Santushti Enterprises. He wants to create a form with following functions. Choose appropriate controls from Text Field, Label, Radio button, Check box, List, Combo box and write in the third column:

Sno

Control used to : Control

1. Enter the name

2.

Select the department from the available list

3.

Choose type of employee (Permanent / Regular)

4. Display the picture of the employee

(2)

Marking Scheme Class XII

Informatics Practices (Code: 065) 2014-15

Time: 3Hrs. MM: 70

1 (a) Draw a network layout of bus topology to connect 5 client computers and 1 server computer.

(1)

Ans:

(½ mark for correct network topology and ½ mark for correct no of computers)

(b) Mr. John wants to prevent unauthorized access to/from his company's local area network. Write the name of a system (software/ hardware), which he should install to do the same.

(1)

Ans: He should install Firewall. (1 mark for correct answer)

(c) Which of the following are open source softwares :

GNU, MS-Office, BOSS, Windows OS

(1)

Ans: GNU, BOSS

(½ mark for each correct answer)

(d) Name the government organization that contributes to the growth of FOSS in India. (1)

Ans: National Resource Centre for Free and Open Source Software (NRCFOSS) is the government organization that contributes to the growth of FOSS in India.

(1 mark for correct answer)

(e) Read the given activities carefully and mention in front of the activity whether that activity is snooping or eavesdropping:

i. Getting someone’s login information by casually watching what he/she is typing. ii. Setting up unauthorized parallel telephone lines iii. Installing some software/hardware which captures the data while on its

way. iv. Reading the files on someone’s computer in an unauthorized manner.

(2)

Ans: i. Snooping. ii. Eavesdropping iii. Eavesdropping. iv. Snooping.

(½ mark for each correct answer)

(d) Kristen has typed the following text in the address bar:

http://www.cbse-international.com/help.htm

Explain to her the main concept of URL and Domain name with reference to the example given above.

(2)

Ans: URL (Uniform Resource Locator) is the complete address of a document on the web, whereas a domain name specifies the location of document's web server. A domain name is a component of the URL used to access web sites.

For example the web address http://www.cbse-international.com/help.htm is a

URL. In this URL www.cbse-international.com is the domain name.

(1 mark for differentiating between URL and domain name ½ mark for correctly identifying url and ½ mark for correctly identifying domain name)

(e) Chanakya has to write a paragraph in English on nobel laureates as a part of his holiday homework. He is using a software in which he types the text in Hindi and the software automatically converts the text into English. For example, if he types “ इस इन ” the software converts it into “Nobel Prize is given in six categories”. What kind of text entry is it – phonetic text entry OR keymap based text entry? How is it different from the other kind of text entry?

(2)

Ans: It is phonetic text entry. It is different from keymap based text entry as in the keymap based text entry keyboard keys are mapped to specific characters using a keymap whereas in phonetic text entry text translation is done by some software based on probable pronunciation of the entered text. (1 mark for specifying “phonetic text entry”) (1 mark for specifying correct difference)

2 (a) In a java program Rajat wants to use a variable to store the quantity of an item which may be in whole numbers or decimals. Write a suitable java statement to declare the variable for the above mentioned purpose.

(1)

Ans: He can use float or double type of variable. double num; Or float num; (1 mark for each correct declaration)

(b) What will be the values of num and num1 after execution of the following code: int num,num1=0;

for(num=100;num<=101;num++) { num1= num+2; --num1; }

(1)

Ans: The value of both num and num1 will be 102. (½ mark for each correct answer)

(c) Zia is working with list box. She has placed a list control on her form to display the list of all items available in her shop. She wants to allow the user to select multiple items from her list control. Which property of jList should she use to do the same?

(1)

Ans: She should use the selectionMode property (1 mark for correct answer)

(d) Raman has typed the following code: int ch=Integer.parseInt(jTextField1.getText()); switch(ch) { case 1:jTextField2.setText("Service"); case 2: jTextField2.setText("Complaint"); case 3: jTextField2.setText("Operator"); break; default: jTextField2.setText("Not a valid entry"); }

On entering the value 1, 2 or 3, he is getting the same output. Mention the possible reason for the same.

(1)

Ans: Break statement is missing after every case. (1 mark for correct answer)

(e) Jennifer wants to write html code to create an ordered list starting with “c”. Help her in writing the code.

(2)

Ans: <ol type= “a” start=3> (1 mark for OL) (½ mark for type) (½ mark for correct value of start)

(f) Write any two advantages of xml over html. (2)

Ans: 1. HTML is designed to display data and hence focused on the ‘look’ of the data, whereas XML is designed to describe and carry data and hence focuses on ‘what data is’.

2. In HTML tags are predefined, while in XML, tags can be created as per needs. (1 mark each for any two correct advantages)

(g) Write java code that take any three digit number from the user in jTextField1, calculate the sum of the digits and display it in separate textfield named jTextField2.

For example If the number entered is 432, it should answers as 9 (i.e. 4+3+2).

(2)

Ans : int n=Integer.parseInt(jTextField1.getText());

int result=0;

while(n>0)

{

result = result+n%10;

n=n/10;

}

jTextField2.setText(""+result);

(1 mark for correct while loop) (½ mark for correct logic used inside while loop) (½ mark for displaying correct value)

3 (a) Saumya had previously created a table named ‘Product’ in a database using MySQL. Later on she forgot the table structure. Suggest to her the suitable MySQL command through which she can check the structure of the already created table.

(1)

Ans: Desc Product; OR Describe Product;

(1 mark for correct answer)

(b) Roli wants to list the names of all the tables in her database named ‘Gadgets’. Which command (s) she should use to get the desired result.

(1)

Ans: Show tables; (1 mark for correct answer)

(c) Kuhu has already created a table ‘Hospital’ as shown below: Patient_No Patient_Name Disease Age Charges P001 Alya Viral Fever 14 500 P002 Kavita Lung Infection 16 1500 P003 Manya Cough and Cold 20 500 P004 Amar Bone Fracture 22 2500 P005 Deep Viral Fever 15 500

Now she wants to add a new column ‘Address’ in the above given table. Suggest to her

(1)

Ans: Alter table Hospital add Address varchar(20);

(d) Amit works as a database administrator in a Multinational bank. He wants to undo the changes made in the current transaction. Suggest to him a suitable MySQL command for the same.

(1)

Ans: Rollback

(e) What will be the output of the following queries on the basis of Employee table:

+-------+-------+--------+ | EmpId | EName | Salary |

+-------+-------+--------+ | A001 | Bob | 5600 | | A002 | John | NULL | | A003 | Tom | 5000 | +-------+-------+--------+

(i) Select avg(Salary) from Employee;

(ii) Select Salary+100 from Employee where EmpId='A002';

(2)

Ans:

(i)

mysql> Select avg(Salary) from Employee; +-------------+ | avg(Salary) | +-------------+ | 5300.0000 | +-------------+

(ii)

mysql> Select Salary+100 from Employee where EmpId='A002'; +------------+ | Salary+100 | +------------+ | NULL | +------------+ (1 mark for each correct output)

(f) A table named ‘GAMES’ has the following contents:

GCode GameName Number_of_Players PrizeMoney 101 Carom Board 2 5000 102 Badminton 2 12000 103 Table Tennis 4 8000

Write the output that will be displayed by statements (i) and (ii). SELECT * FROM GAMES; SET AUTOCOMMIT = 0; INSERT INTO GAMES VALUES(105,'CHESS’,2,9000); ROLLBACK; SAVEPOINT S1; SELECT * FROM GAMES; ------------ (i) INSERT INTO GAMES VALUES(108,'LAWN TENNIS’,4,25000); SAVEPOINT S2; INSERT INTO GAMES

(2)

VALUES(109,'CRICKET’,11,20000); ROLLBACK TO S2; SELECT * FROM ITEM; ------------ (ii)

Ans: (i) GCode GameName Number_of_Players PrizeMoney 101 Carom Board 2

5000 102 Badminton 2

12000 103 Table Tennis 4

8000 (ii)

(1 mark for each correct output)

(g) Observe the given statements carefully:

(i) SELECT * FROM club WHERE salary between 20000 and 30000; (ii) SELECT * FROM club WHERE salary IN ( 20000, 30000); (iii) SELECT * FROM club WHERE salary >= 20000 and salary <=30000; (iv) SELECT * FROM club WHERE salary = 20000 OR salary = 30000;

Make pairs of the equivalent SQL statements given above (which give the same output) and place each pair in a group.

(2)

Ans: Group A (i)

(iii) Group B (ii) (iv) (½ Mark for each correct answer)

4 (a) Define inheritance with reference to object oriented programming. (1)

GCode GameName Number_of_Players PrizeMoney

101 Carom Board 2 5000

102 Badminton 2 12000

103 Table Tennis 4 8000

108 Lawn Tennis 4 25000

Ans: Inheritance is a process of creating a new class (derived class or sub class) from existing class. The derived class not only inherits capabilities of the base class but also can add new features of their own.

(1 mark for correct definition)

(b) Given a String object named 'code' having value as “908” stored in it. What will be result of the following? JOptionPane.showMessageDialog(null, " " +(code.length( )+ Integer.parseInt(code)));

(1)

Ans: 911 (1 mark for correct answer)

(c) What will be displayed in jTextField1 and jTextField2 after the following code is executed:

int num = 35 , num1 = 46 ;

jTextField1.setText( num + num1 + " " ) ; jTextField1.setText( " " + num + num1 ) ;

(1)

Ans: jTextField1 81 will be displayed jTextField2 3546 will be displayed. (1 mark for each correct answer)

(d) Find output of the following java code snippet: String word="Highrise";

String wordlc = word.toLowerCase(); for

(int i = 0; i < wordlc.length(); i+=4)

{

String extstr = wordlc.substring(i,i+2); jTextArea1.append(extstr+"\

n");

}

(2)

Ans: hi ri (½ mark for each character of output)

(e) Rewrite the following code using while loop: int a,b;

for(a=10,b=4;a<=16;a++,b+=2){

(2)

jTextArea1.append(""+a++);}

JOptionPane.showMessageDialog(null,"Finished!!!");

Ans: int a=10,b=4; while(a<=16)

{ jTextArea1.append(""+a++);

a++; b+=2;}

JOptionPane.showMessageDialog(null,"Finished!!!");

(½ mark for correct while statement, ½ mark for correct increment statement and 1 mark for correct use of variables)

(f) The following code has error(s). Rewrite the correct code underlining all the corrections made : String str1 = SeemaSurakshabal ; int b; for(int b = 0 ; b < 3 , b++ ) { jTextArea1.showText(str1+"\n" ) ; str1 = str1 + b ; }

(2)

Ans: String str1 = “ SeemaSurakshabal”

; int b; for(int b = 0 ; b < 3 ; b++ ) { jTextArea1.append(str1+"\n" ) ; str1 = str1 + b ; } (½ mark for each correct error)

(g) Ms. Rakhi works in an International Bank as an IT Head. She designed a simple interest calculator program as shown below:

(6)

The interest rate is given based on the account type as shown below:

ACCOUNT TYPE INTEREST RATE %

SAVING 4 %

RECURRING DEPOSIT 6

% FIXED DEPOSIT 8 %

i. Write the code required for ‘INTEREST RATE’ button to display interest rate as per the above given criteria. ii. Write the code required for ‘SI’ button to calculate and display ‘Simple Interest’ based on the given formulae:

SI=(amount*interest_rate*duration)/100;

Ans : i. Correct code required for ‘INTEREST RATE’ button to display interest rate as

per the above given criteria:

if(R1.isSelected()==true)

T3.setText("4"); else if(R2.isSelected()==true)

T3.setText("6"); if(R3.isSelected()==true) T3.setText("8");

(1 mark for using correct if statement 1 mark for displaying interest rate value in the suitable text field)

ii. Correct code required for ‘SI’ button double amt=Double.parseDouble(T2.getText()); double int_rate=Double.parseDouble(T3.getText()); int year=Integer.parseInt(T4.getText()); double si=(amt*int_rate*year)/100; T5.setText(""+si);

(1 mark for fetching values in suitable variables 1 mark for calculating and displaying SI)

iii t1.setText(""); t2.setText(""); t3.setText(""); t4.setText(""); t5.setText("");

(1 mark for correct code)

5 (a)

i. ii.

Observe the table ‘Club’ given below: Club

Member_id Member_nam e

Address Age Fees

M001

Sumit New Delhi 20 1000

M002

Nisha Gurgaon 19 1500

M003

Niharika New Delhi 21 2100

M004

Sachin Faridabad 18 1500

What is the cardinality and degree of the above given table? If a new column contact_no has been added and two more members have joined the club then how these changes will affect the degree and cardinality of the above given table.

2

Ans: i. Cardinality:4 Degree: 5 (½ mark for each correct answer)

ii. Cardinality: 6 Degree: 6 (½ mark for each correct answer)

(b) Write the output of the following SQL queries:

i. SELECT INSTR(‘INTERNATIONAL’, ‘NA’); ii. SELECT LENGTH(CONCAT(‘NETWORK’,’ING’)); iii.SELECT ROUND(563.345,-2); iv. SELECT DAYOFYEAR(‘2014-01-30’);

2

Ans: i.6 ii.10 iii. 600 iv. 30

(½ mark for each correct answer)

(c) Pranay, who is an Indian, created a table named “Friends” to store his friend’s detail. Table “Friends” is shown below. Write commands in SQL for (i) to (iv) and output for (v) to (vii).

S_No Name Age City Country Email_id 1 Alice 14 Washington USA [email protected] 2 Charles 12 Copenhage

n Denmark [email protected]

m 3 Angel 16 Chicago USA [email protected]

6

4 Jasmine 15 Sydney Australia [email protected]

5 Raj 14 New Delhi India [email protected]

iii. vii.

6 Jette 13 Nykobing Denmark [email protected]

7 Alexender 15 Melbourne Australia NULL 8 Shashank 16 Banglore India NULL

i. To display list of all foreigner friends. ii. To list name, city and country in descending order of age. To count how many friends have email id on gmail.

iv. To list name and city of those friends who don’t have an email id. v. Select name,country from friends where age>12 and name like ‘A%’; vi. Select ucase(concat(name,”*”,city)) from friends where

country like‘Denmark’; Select mid(name,1,4) as “UID” from friends where country like ‘USA’;

Ans: i. Select name from friends where country not like “India”; ii. Select name,city,country from friends order by age desc; iii. Select count(*) from friends where email_id like “%gmail%; iv. Select name,city from friends where email_id is null; (1 mark

for each correct query)

OUTPUT v.

Name Age Country

Alice 14 USA

Angel 16 USA

Alexender 15 Australia vi.

vii.

( ½ mark for each correct output)

Ucase(concat(name,”*”,city))

Charles*Copenhagen

Jette*Nykobing

UID

Alic

Ange

6 (a) Write SQL query to create a table ‘Bank_Customer’ with the following structure: Field Type Constraint Acc_No Integer Primary

Key Cust_Name

Varchar(20) Not Null

Cust_Add Varchar(20)

Cust_City Varchar(20)

(2)

Ans: Create table Bank_Customer ( Acc_No integer primary key, Cust_Name varchar(20) not null, Cust_Add varchar(20), Cust_City varchar(20) );

(½ Mark for CREATE TABLE Bank_Customer) (½ Mark for appropriately putting constraints) (½ Mark for correct data types) (½ Mark for correct syntax of the query)

(b) In a Bank’s database, there are two tables ‘Customer_info’ and ‘Transaction Detail’ as shown below:

Customer_info

Acc_No Cust_Name Cust_Add Cust_City Cust_Phone 1001001 Ram Vasundhara Enclave New Delhi 8710557614 1001002 Kavita Punjabi Bagh New Delhi 7123545233 1001003 Raj Civil Lines Allahabad 9872136576 1001004 Soha n Krishnanagar Kanpur

9921305453 Transaction_Detail

Trans_Id Acc_No Transaction_Type Amount

T001 1001001 Credit 5000

T002 1001002 Credit 10000

T003 1001001 Debit 2000

T004 1001004 Credit 6000

T005 1001001 Credit 4000

i. Is it possible to have primary key and foreign key in one table? Justify your answer. ii. A table can have maximum how many primary keys and foreign keys?

(2)

Ans: i. Yes, it is possible to have primary key and foreign key column in one table. Primary key column is used to uniquely identify each record of the table while foreign key column is used to maintain referential integrity. As in the above given table ‘Transaction_Detail’, Trans_Id column is a primary key column while Acc_No column may act as a foreign key column.

(½ Mark for correct answer) (½ Mark for correct justification)

ii. A table can have maximum one Primary Key A

table can have any number of foreign Keys

(½ Mark for each correct answer)

(c) Consider the tables ‘Flights’ & ‘Fares’ given below:

Flights

FNO SOURCE DEST NO_OF_FL NO_OF_STOP

IC301 MUMBAI BANGALORE 3

2

IC799 BANGALORE KOLKATA 8

3

MC101 DELHI VARANASI 6

0

IC302 MUMBAI KOCHI 1

4

AM812 LUCKNOW DELHI 4

0

MU499 DELHI CHENNAI 3

3

Fares

MU499 Sahara 12000 4

With reference to these tables, write commands in SQL for (i) and (ii) and output for (iii) below:

i. To display flight number,

(6)

FNO AIRLINES

FARE

TAX

IC301 Indian Airlines

9425 5

IC799 Spice Jet

8846 10

MC101 Deccan Airlines

4210 7

IC302 Jet Airways

13894 5

AM812 Indian Airlines

4500 6

source, airlines of those flights where fare is less than Rs. 10000. ii. To count total no of Indian Airlines flights starting from various cities.

iii. SELECT FLIGHTS.FNO, NO_OF_FL, AIRLINES FROM FLIGHTS,FARES WHERE

FLIGHTS.FNO = FARES.FNO AND SOURCE=’DELHI’;

Ans: i. select flights.fno,source,airlines from flights,fares where flight.fno=fares.fno

and fare<10000;

(1 mark for correct use of select and from) (1 mark for correct use of where clause)

ii. select sum(no_of_fl) from flights,fares where flights.fno=fares.fno group by source having Airlines=‘Indian Airlines’; (1 mark for correct use of select and from) (1 mark for correct use of where and group by clause)

iii. MC101 6 Deccan Airlines MU499

3 Sahara

(1 mark for each correct line of output)

7 (a) What is the role of a good back-end in an IT application? (1)

Ans: A good back-end ensures sustainability, efficiency and easy modification of the application. (1 mark for correct answer)

(b) Identify e-Governance and e-Learning applications from the following:

i) On-line experiments in a virtual laboratory of a college.

ii)On-line application submission for change of address in the passport. iii) On-line bill payment of Water Charges to Jal Board of any state. iv) On-line

tutorials for physics.

(2)

Ans: E_Governance: i) On-line bill payment of Water Charges to Jal Board.

ii)On-line application submission for change of address in the passport eLearning: iii) On-line experiments in a virtual laboratory of a college.

iv) On-line tutorials for physics (½ mark for correctly identifying each application)

(c) Raghuram is working as a Manager in the Santushti Enterprises. He wants to create a form with following functions. Choose appropriate controls from Text Field, Label, Radio button, Check box, List, Combo box and write in the third column:

(2)

Sno Control used to : Control 1. Enter the name

2.

Select the department from the available list

3.

Choose type of employee (Permanent / Regular)

4. Display the picture of the employee

Ans:

Sno Control used to : Control 1. Enter the name Text Field

2.

3.

4.

Select the department from the available list

Choose type of employee (Permanent / Regular)

Display the picture of the employee

Combo Box

Radio Button

Label

CBSE EXAMINATION PAPER 2015

1. (a) A school with 20 stand-alone computers is considering networking them together and adding a server. State 2 advantages of doing this. [1] (b) Distinguish between LAN and WAN. [1] (c) What is the purpose of Modem in network ? [1] (d) Write one example Of Address. [1] (e) Define 'Domain Name Resolution'. [2] (f) Name two threats to security in a network. What is the role of Firewall in Network security ? [2] (g) Write one advantage and one disadvantage of Open Source software over Proprietary software.[2]

2. (a) Write the value Of variable after execution Of the following code : [1] int d; int C ; d=7; c=(5*++d); (b) What is the difference between jTextField and jPasswordField components ? [1] (c) In a

SWITCH statement, what is the purpose Of 'default' section ? [1] (d) After typing the HTML code using a text editor, how do you see how it would look as a web page?

[1] (e) Write Java code to assign the value 500 to variable x. Increase the value of x by 50 and store it in variable y. [2] (f) Write the output that will be generated by the code given below : [2] int

i; i=7; int r; r=8; while (i<=10) { System. out. println (r*i) ; i=i+2; } (g) "With XML there are no predefined tags" — Explain in brief with the help of an example. [2]

3. (a) What is MySQL ? [1] (b) Is NULL value the same as 0 (zero) ? Write the reason for your answer. [1] (c) Write the UPDATE command to increase the commission (Column name : COMM) by 500 of all the Salesmen who have achieved Sales (Column name : SALES) more than 200000. The table's name is COMPANY. [1] (d) While using SQL pattern matching, what is the difference between '_' (underscore) and '%' wildcard symbols ? [1] (e) How is Primary key constraint different from Unique key constraint ? [2] (f) Write one similarity and one difference between CHAR and VARCHAR data types. [2] (g) What is a Transaction ? Which command is used to make changes done by a Transaction permanent on a database ? [2]

4. (a) The following code has some error(s). Rewrite the correct code underlining all the corrections made. [2] int marks , temperature ; marks = jTextFie1d1. getText ( ) ) ; temperature = Integer. parselnt (j TextFie1d2. getText( ) ) ; if (marks < 80) and (temperature >= 40) { System. out.println("Not Good") ; } else { System. out. Println("OK"); } (b) How many times will the following WHILE loop execute ? int y = 7, sum = 0 ; while (y<=15) { sum = sum + y; y=y+2; } (c) Rewrite the following program code using IF ELSE IF instead of SWITCH statement : [2] String tour ; int c1 = Integer.parseInt(jTextField1.getText ( ) ) ,; switch (c1) { case 8: tour ="\n You are going to Camp Ramgarh" ;

break ; case 9 : tour = "\n You are going to Manali, Rohtang Pass" ; break; Case 10: tour = "\n You are going to Chail";

break ; default : tour = "No School tour for you this time" ; } (d) Write the values of sum and x after execution of the following code : [2] int sum x ;

sum = 7; x=5; sum = sum + (x++) ; (e) What will be the contents of jTextField1 and jTextField2 after executing the following code : [2] String s = "Best" ; j TextFie1d1.setText(s.length ( )+" " ) ; jTextFie1d2. setText (s.toUpperCase ( ) ) ; (f) The students of "Shiksha Vidyalaya" work for different extra curricular activities like 'Community

Outreach Programme', 'Swachh Bharat Abhiyan' and Traffic Safety Club'. The Programmer at the school has developed a GUI application as shown below :

• A student can participate in more than one activities. • Each student gets 10 points for each activity — namely Community Outreach Programme,

Swachh Bharat Abhiyan and Traffic Safety Club. Help the programmer to write code for the following : (i) When 'Calculate Total Score' button is clicked, the points for each activity (that is selected) should

be displayed in the text field in front Of that activity's checkbox and the Total Score should be displayed in the appropriate Text field. [3] (ii) When Clear button is clicked, all the Textfields and Checkboxes should be cleared. [1] (iii) When Stop button is clicked, the application should close. [1]

5. (a) Distinguish between Single Row and Aggregate functions of MySQL. Write one example of each. [2] (b) Consider the following table named "SOFTDRINK". Write commands of SQL for (i) to (iv) and output for (v) to (vii). Table : SOFTDRINK

DRINKCODE DNAME PRICE CALORIES

101 Lime and Lemon 20.00 120

102 Apple Drink 18.00 120

103 Nature Nectar 15.00 115

104 Green Mango 15.00 140

105 Aam Panna 20.00 135

106 Mango Juice Bahaar 12.00 150 (i)To display names and drink codes of those drinks that have more than 120 calories. [1] (ii) To display drink codes, names and calories of all drinks, in descending order of calories. [1] (iii) To display names and price of drinks that have price in the range 12 to 18 (both 12 and 18 included). [1] (iv) Increase the price of all drinks in the given table by 10%. [1] (v) SELECT COUNT (DISTINCT (PRICE) ) FROM SOFTDRINK; [1] (vi) SELECT MAX (CALORIES) FROM SOFTDRINK; [1]

(vii)SELECT DNAME FROM SOFTDRINK WHERE DNAME LIKE "%MANGO%"; [1]

(c). What is the degree and cardinality of 'SOFTDRINK' TABLE ? [1]

6. (a) Write MySQL command to create the Table 'LIBRARY with given constraints. [2] Table : LIBRARY

COLUMN_NAME DATA TYPE (SIZE)

CONSTRAINT

BookId Int(10) Primary Key

BookName Varchar(40) Not Null

Type Char(4)

Author Varchar(40)

No_Copies Int(6)

Price Decimal(8,2)

(b) In a Database Company, there are two tables given below : Table : SALES

SALESMANID NAME SALES LOCATIONID

S1 ANITA SINGH ARORA 250000 102

S2 YR. SINGH 1300000 101

S3 TINA JAISWAL 1400000 103

S4 GURDEEP SINGH 1250000 102

S5 SIMI FAZAL 1450000 103

Table : LOCATION

LOCATIONID LOCATIONNAME

101 Delhi

102 Mumbai

103 Kolkata

104 Chennai

Write SQL queries for the following : (i) To display SalesmanID, names of salesmen, LocationID with corresponding location names. [2] (ii) To display names of salesmen, sales and corresponding location names who have achieved Sales more than 1300000. [2] (iii) To display names of those salesmen who have 'SINGH' in their names. [2] (iv) Identify Primary key in the table SALES. Give reason for your choice. [1] (v) Write SQL command to change the LocationID to 104 of the Salesman with ID as S3 in the table

'SALES. [1]

7. (a) How does e-learning allow students to study at their own pace ? [2]

(b) How does e-governance empower citizens ? Write one point. [1] (c) Sabeena is creating a form for the hotel where she works. Help her to choose most appropriate

controls from ListB0x, ComboBox, TextField, TextArea, RadioButton, Checkbox, Label, and Command

Button for the following entries : [2]

S.No. Function

1 To input name

2 To allow enter gender Out of M or F

3 To allow selecting type of room out' of Deluxe, SemiDeluxe, General

4 To allow entering preferences of guest in the form of a paragraph

***************** ALL THE BEST

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