Top Banner
KENDRIYA VIDYALAYA SANGATHAN DEHRADUN REGION (Informatics Practices) Class – XI 2014-15 Chief Patron : Shri Avinash Dikshit, IDAS Commissioner, KVS , New Delhi Patron : Smt. Piya Thakur, Dy. Commissioner KVS Dehradun Region Guidance : Shri Vinod Kumar, Asstt. Commissioner KVS Dehradun Region Co-ordinator : Smt. M.B.Chaturvedi, Principal KV Upper Camp, Dehradun Cantt. Subject Contributors Mr. Rajesh Kumar Mishra, PGT (Comp.Sc.),K.V. Upper Camp, Dehradun Mr. Chandra Kant Bhatt, PGT (Comp.Sc.), K V No.1, HBK, Dehradun STUDY MATERIAL
89

KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Sep 25, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

KENDRIYA VIDYALAYA SANGATHAN

DEHRADUN REGION

(Informatics Practices) Class – XI 2014-15

Chief Patron

: Shri Avinash Dikshit, IDAS Commissioner, KVS , New Delhi

Patron : Smt. Piya Thakur, Dy. Commissioner KVS Dehradun Region

Guidance

: Shri Vinod Kumar, Asstt. Commissioner KVS Dehradun Region

Co-ordinator : Smt. M.B.Chaturvedi, Principal KV Upper Camp, Dehradun Cantt.

Subject Contributors Mr. Rajesh Kumar Mishra, PGT (Comp.Sc.),K.V. Upper Camp, Dehradun

Mr. Chandra Kant Bhatt, PGT (Comp.Sc.), K V No.1, HBK, Dehradun

STUDY MATERIAL

Page 2: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Table of Contents

Unit /Chapters Page No.

Unit-1: Introduction to Computer Systems

Chapter 1: Hardware Concepts 3

Chapter 2: Software Concepts 13

Chapter 3: Information Security 18

Unit-1 : Questions with and Answers 21

Unit-2 : Introduction to Programming

Chapter 4: Getting Started with IDE Programming 25

Chapter 5: JAVA Programming Fundamentals 31

Chapter 6: Control Structures 36

Chapter 7: Programming Guidelines 39

Unit-2 : Questions with and Answers 43

Unit-3 : Relational Database Management Systems

Chapter 8: Introduction to DBMS and MySQL 57

Chapter 9: Working with MySQL 59

Chapter 10 : MySQL Functions 63

Unit-3 : Questions with and Answers 65

Unit-4 : I T Applications

Chapter 11: I T Application 70

Unit-4 : Questions with and Answers 72

Sample Paper -1 (Solved) 73

Sample Paper -2 (Solved) 79

Model Paper (Unsolved) 86

COURSE DESIGN

Unit Topic Periods Marks Theory Practical Total

1 Introduction to Computer Systems 20 08 28 10

2 Introduction to Programming 45 42 87 25

3 Relational Database Management Systems 50 45 95 30

4 I T Applications 10 20 30 05

TOTAL 125 115 240 70

:: 2 ::

Page 3: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT -1 Introduction to Computer Systems

Chapter 1: Hardware Concepts

What is Computer? A computer is an electronic device that processes input data and produces result (output) according to a set of instructions called program. A computer performs basically five major functions irrespective of its size and make.

1. It accepts data or instructions as input. 2. It processes data as per given instructions. 3. It gives results in the form of output 4. It stores data 5. It controls operations of a computer

How Computer works? The following diagram describes the basic layout and working methodology of a computer system. A computer receives data and instructions through "Input Devices" which get processed in Central Processing Unit, "CPU" and the result is shown through "Output Devices". The "Main / primary Memory" and "Secondary / Auxiliary Memory" are used to store data inside the computer.

Input: An input devices (or peripheral) are used to provide data and control signals (commands) to computer. The Key Board and Mouse are commonly used Input Devices. Output: The output produced by the computer after processing must also be kept somewhere in human readable form. The Output devices display the information or result after processing. The Monotor and Printer is commonly used Output Devices. Primary Memory: The Primary memory or Main Memory works as temporary storage for data and programs while processing. It is of two types; one is RAM (Random Access Memory) and ROM (Read Only Memory). The RAM is the volatile memory and the ROM is the non-volatile memory. The volatile memory is the kind of the memory that is erasable and contents will be lost, if power is switched off. Secondary Memory (Storage): The secondary memory is used to store the data permanently in the computer. The commonly used secondary storage devices are hard disk drives, CD/DVD ROM, Flash memory and USB Pen drives etc. Central Processing Unit (CPU): The CPU works as the brain of computer system. Like human brain, it takes all major decisions, makes all calculations and directs different parts of the computer functions by activating and controlling the operations. It is divided in two sub-units i.e. Arithmetic & Logical Unit (ALU) and Control Unit (CU). Both ALU and CU are designed on a single circuit called Microprocessor.

:: 3 ::

Page 4: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Arithmetic Logical Unit (ALU): In computing, an arithmetic and logic unit (ALU) is a digital circuit that performs arithmetic (+,-,/, * etc.) and logical (<, >, = etc.) operations. Control Unit (CU): The control unit coordinates the components of a computer system. It fetches the instructions and directs the operation of the other units by providing timing and control signals. All computer resources are managed by the CU. It directs the flow of data between the Central Processing Unit (CPU) and the other devices

INPUT DEVICES

Input devices are necessary to enter data and instructions in to a form which can be understood by the computer. The followings are the most useful input devices. Keyboard: A 'keyboard' is a human interface device which is represented as a layout of buttons. Keyboard is the most common input device used to enter text, numbers and instructions. It contains several keys or switches which corresponds to a symbol written on it. Generally, a keyboard contains the following types of keys.

Alphabet Keys (A-Z) Number Keys (0-9) Direction Keys Function Keys (F1 – F12) Other Keys (Spacebar, Tab, Shift, Alt, Ctrl, Del, Backspace Caps Lock, Num Lock etc.)

Generally a QWERTY keyboard is used with computers. The term QWERTY indicates the KEYS-LAYOUT on the keyboard.

Mouse: Mouse is a handheld pointing device used to select or point an object displayed on the monitor. The motion of mouse simulates the motion of Mouse pointer on the screen. Generally, it contains Left , Right and Scroll Button. Generally Optical mouse is used in PCs. Now days Wireless (card less) mouse are also available in the market. Light Pen: A light pen, also called a selector pen, is a computer input device in the form of a light- sensitive wand used in conjunction with a computer's CRT display. It allows the user to point to displayed objects or draw on the screen in a similar way to a touch screen.

CPU (Microprocessor)

:: 4 ::

Page 5: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Joystick: Joystick is an input device consist a stick that is used to move object in an angle or direction. It is generally used in playing video games. Microphone: Microphone or Mic is used to input audio data into computer. Generally it is used for sound or voice recording. Web Camera: Web Camera or Webcam is used to capture images or video while Video Chatting or Conferencing. Graphic Tablet: Graphic Tablet or Tablet is input devices that allow enter drawing and sketches into computer. It consists of an electronically sensitive surface on which anything can be written or drawn using stylus or pen. Most commonly it is used to enter digital signatures, sketching and writing something while teaching with computers in classrooms. Smart Card Reader: Smartcards are plastic card containing Magnetic strips (memory) or Microchip to hold some personal data or some security information. Generally these cards are used in companies and organizations as ID-card for identification and Authentication purpose. Smartcard reader is used to access stored information in Smartcard. Scanner: Scanner is an input device that optically scans images, printed text, handwritten text or an object and converts it to a digital image. Generally used for storing, editing or re-printing of image or document. Common examples found in offices are flatbed scanner where the document is placed on a glass window for scanning. Hand-held scanners are also used, where the device is moved by hand on the paper. Optical Character Reader (OCR): OCR device is used to convert images of text into computer editable text. OCR is capable of reading books and documents into electronic file to facilitate computerized record-keeping system in an office, or to publish on-line books. Modern OCR can recognize hand-written with good accuracy. Generally, it is used with Scanner device (as OCR software) to convert scanned text image into editable text/document file. Optical Mark Reader (OMR): OMR device is used to scan marked points on special preprinted forms. Marks can be made with dark

Joystick Microphone (Mic) Web Camera Graphic Tablet

Smart Card Reader

Scanner

:: 5 ::

Page 6: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

pencil or pen in definite shape (circle or box) in OMR sheet that are scanned and process by the computer. Generally, it is used to evaluate Objective-types answer scripts in public examinations or processing of Survey forms. Optical Barcode Reader (OBR): Barcode is a pattern of printed bars (strips) on various types of products. These strips contains product information like price, weight, date of manufacturing, date of expiry etc. in encoded form. Optical Barcode Reader (OBR) reads these barcode to input product details into the computer. This device consists of a light source (laser), a lens and light sensor which reads barcode image. Generally, it is used in shops, shopping malls and Library etc. Magnetic Ink Character Reader (MICR): MICR device is used to read characters printed using special magnetic ink in special font or style. These characters are used in Bank cheques and Postal orders. MICR device is mainly used in banks to read cheque number, IFSC code etc. pre printed on cheque leaves. This device saves time and ensures accuracy of data entry. Biometric Sensor Devices: Biometric Devices are used for identifying a person’s identity using some unique biological properties of a human-beings like Finger print or Retina scan, voice or face recognition etc. Generally, these devices are used to identify a person, mark attendance of employees in organizations or to provide restricted entry for secured area.

Bar Code Reader

Fingerprint scan- Biometric

Device

Retina Scan - Biometric

Device

OMR Device

MICR Coding and MICR Device

:: 6 ::

Page 7: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

OUTPUT DEVICES

Monitor or Visual Display Unit(VDU): A Monitor or VDU is most common output device. It looks like TV screen and available in various types and size. The picture on monitor is made up tiny dots called Pixels. The quality of a picture depends on its Resolution (total number of pixels) i.e. more pixels, the greater quality.

CRT (Cathode Ray Tube) Monitor: These monitor contains a glass tube with phosphorus coating, which is lighted when electron strikes. It works like Television. Liquid Crystal Display (LCD)/TFT Monitor: It contains Liquid Crystals to create tiny pixels. It is also called Thin Film Transistor (TFT) monitor. It is smaller, lighter and consumes less power than CRT monitors. Now days, Plasma display is also popular.

Printer: A printer is a peripheral which produces a hardcopy representation of an electronic document on physical media such as paper. Multifunction printers (MFPs) or All-in-one Printer include a scanner and can copy paper documents or send a fax. Depending on their speed and mechanism of printing, printers are classified as impact and non-impact printers. Impact printers: use the familiar typewriter approach of hammering a typeface against the paper and inked ribbon. Dot-matrix printers are of this type. Non-impact printers: do not hit or impact a ribbon to print. They use electro-static chemicals and ink-jet technologies. Laser printers and Ink-jet printers are of this type. This type of printers can produce color printing and elaborate graphics. Some commonly used Printers are-

Dot Matrix Printer (DMP): It prints character or images by tiny dots on the paper like Type-Writer. These dots are produced by a moveable Printing head containing matrix of Pins, which strikes on the inked-Ribbon and leaves impression (dots) on the paper.

It has low operating cost and can produce carbon copies. It is noisy, slow and produces low quality Black & White output. Mostly used in Banks and Offices.

Ink-jet (bubble-jets) printers: These printers can produce coloured printouts. It prints character by using controlled stream (jet) of liquid ink, which produces tiny droplets of ink on the paper. These coloured droplets forms text or images on paper. Ink-jet printers are Non-Impact Printer since droplets are formed silently by Jet of Ink stored in the cartridge.

It is quite in operation and produces B&W or coloured output in good quality of resolution.

It is little costlier and Ink-cartridge can dry out, if left unused for long period of time. Not suitable for creating carbon copy printout. Most suited for home and small offices.

Laser Printers: These printers use laser technology to produce printed document and works like Photo copier. The image of document is formed on copier drum with the help of laser beam, which electrically charges the drum surface. This charges surface attracts Tonner ink (dry ink), which is

CRT Monitor LCD/TFT Monitor

:: 7 ::

Page 8: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

permanently fused on the paper with heat and pressure. Laser printers print very fast, and cartridges work for a long time.

It is fast, quite and produces good quality output in high resolution (600-1200 dpi-dots per inch) at low running cost.

It is expensive to buy and repair. Not suitable for creating carbon copy printout. Most suited for offices.

Plotters: Plotters are large-scale printers that are very accurate at reproducing line drawings. These devices mostly used for printing Maps, charts or Engineering drawings. The two basic types of plotters are called flatbed plotters and drum plotters.

Flatbed plotters are horizontally aligned with a flat surface to which a piece of paper is attached. The paper remains stationary and the printer moves pens across the paper to draw the image. Drum plotters, also called upright plotters, are vertically positioned. They have a drum that the paper rolls on. Drum plotters usually make more noise and are more compact than flatbed plotters.

Memory

Memory devices are used to store data, information and programs temporarily or permanently. There are two kinds of computer memory: primary and secondary.

Ink jet printer

Laser Printer

Dot Matrix printer

Flatbed Plotter

Drum Plotter

:: 8 ::

Page 9: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Primary Memory Primary Memory is accessible directly by the CPU and used for storing data and programs. The main memory unit is divided into-

Random Access Memory (RAM): It is used to hold data and instructions temporarily, while operation of computer. It is Volatile memory i.e. data will be lost, if power is switched off. Read Only Memory (ROM): It is used to store the program or instructions provided by the manufacturer (Firmware), which is used to carry POST (Power On Self Test) function for basic hardware and to load Operating System in the RAM (Booting). It is permanent and Non-volatile memory.

Secondary Memory (Auxiliary Storage) Device: The Secondary storage, or Auxiliary Storage devices are used to store a large amount of data. These storage devices are also used to store and carry data from one place to another. As per technology, they are divided into three categories.

Magnetic Storage: A magnetic Storage device uses Magnetic flux to represent and store data in binary form (i.e. 0 or 1). These magnetic flux are created when data is being written on the media. Floppy, Magnetic Tape and Hard disk drive belong in this category. Optical Storage: Optical storage technology uses Laser beam to read or write data on the media like CD or DVD. Laser beam creates Pits on the media while writing by burning the surface. CDs, DVDs and Blu-Ray Disk belong in this category. Flash Memory: It is Chip-based technology, which stores data like ROM chip. The chip devices consumes very less power to write or access stored data. Memory Cards, Pen Drives and other Smart chips belong in this category.

Floppy Diskette: Floppy Disk or Diskette is oldest portable data storage device used in early days. The floppy disk consists of a thin and flexible film coated with magnetic material, which is sealed in rectangular-shaped cover. Floppy disk is available in different sizes like 5 ¼” and 3 ½” diameter offering 720 KB to 1.44 MB storage capacity. Floppy disk stores data in concentric circles called tracks which is divided in sectors. A cross area of track and sector is called Allocation unit, which can store 1 KB data. Generally, a floppy contains 9 sectors and 80 tracks.

RAM Chip

ROM

Floppy Disk

:: 9 ::

Page 10: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Hard Disk : It is made from the thin metal platter which is coated on the both sides of the magnetic Disks. A hard disk contains many Plates made from the Magnetic Materials. The hard disk also contains a head which is used for both Reading and Writing the Data from the Hard Disks. The Plate of the hard disk is divided into the Tracks and Sectors and the collection of Tracks makes a Cylinder. Magnetic Tapes: Magnetic Tape is similar to Audio Cassette, which contains a thin strips of bronze metal coated tape rolled within it. Generally, it is used for archival or back-up purpose, because it can store large amount of data. The size of storage depends on the length of the tape. Magnetic tape is more durable to Floppy or Magnetic disk.

CD & DVD: Compact Disk (CD) and Digital Versatile/Video Disc (DVD) is an optical disc storage format, invented and developed by Philips, Sony, Toshiba, and Panasonic in 1995. DVDs offer higher storage capacity than Compact Discs while having the same dimensions. A CD may have 700 MB data where as a DVD may have 4.7 GB storage. CD-ROM and DVD-ROM are Pre-recorded CDs and DVDs use for mass-production of audio or video contents. These are called ROM because data can only be read and not written nor erased. Blank recordable CDs and DVDs discs (CD-R and DVD-R) can be recorded once using a Recorder/ Writer. Rewritable CDs and DVDs (CD-RW and DVD-RW) can be recorded and erased multiple times. The new technology which offers more data capacity is called Blue Ray Disks.

Magnetic Tape

Hard Disk

Structure of CD/DVD

CD/DVD

:: 10 ::

Page 11: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Flash Memory: Flash Memory is Chip based (Solid state) memory, which can store data permanently. Generally, it is integrated with USB connector, which requires low power to read or write data. It is cheaper, small and lightweight, removable, rewritable and portable storage media. Memory cards, Memory stick, Multimedia card (MMC) and Pen drives are example of Flash Memory. A USB flash drive is a data storage device that includes flash memory with an integrated Universal Serial Bus (USB) interface. These small plug-and-play drives are removable, re-writable, and great for storing personal and professional data, as many are hardware-encrypted devices for ultimate security. A memory card or flash card is an electronic flash memory data storage device used for storing digital information. They are commonly used in many electronic devices, including digital cameras, mobile phones, laptop computers, MP3 players and video game consoles. They are small, re-recordable, and able to retain data without power. There are a number of memory cards on the market, including the SD card (secure digital card), the CF card (Compact Flash card), the Smart Media card, the Memory Stick, and the Multimedia Card.

Measurement of Memory: The smallest unit of memory is called BIT which can hold 1 or 0. The other units are-

4 Bit =1 Nibble 1024 MB =1 Giga Byte (GB) 8 Bit =1 Byte 1024 GB =1 Tera Byte (TB) 1024 Byte =1 Kilo Byte (KB) 1024 TB =1 Peta Byte (PB) 1024 KB =1 Mega Byte (MB) 1024 PB =1 Exa Byte (EB)

Communication Bus:

Bus is a collection of wires, used to transfer data, instruction or address in the form of electrical signals from one unit to another. Three types of buses are :

1. Address Bus: This type of bus connects Processor to Memory and carry address of memory to be read/write. The size of bus specifies the number of memory locations that can be addressed i.e. 64-bit address bus can address 264 memory locations. 2. Data Bus: It is Bi-directional bus connects processor and other units/ devices (memory & I/O devices) to carry data. 3. Control Bus: It carries the signals to/from control-unit and all the devices attached. Its size represents the capacity of Micro processor. The 32-bit or 64-bit processors are commonly used.

Communication Ports:

Ports are connecting points or slot which are used to connect external devices to the computers. Commonly used Ports in Computer System are- Serial Port (COMmunication Port): It is 9-pin/25-pin sized connector transmits 8 bit data serially. It is commonly used to connect Mouse and

Flash Memory & Memory Cards

:: 11 ::

Page 12: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Modem etc. Mostly obsolete and replaced by USB port. Parallel Port (LPT): It is 25-pin connector which transmits data in parallel way. Generally used for Printer, Scanner, Tape drive etc. USB Port: It is 9-pin sized connector used to connect various devices like Printer, Mouse, Joystick, Camera, Pen drive etc.

Blue Tooth: It is telecommunication industry specification used to connect Mobile/PDAs and computers that makes wireless communication upto 10 mt. Network Port (RJ-45 Port): A Network Port is 8-wire port which used to connect Ethernet (LAN) devices like Network Switch or MODEM. Phone Port (RJ-11 Port): A phone port is a 6-wire port which allows to connect telephone line or equipments to facilitate voice calling.

E-Waste & its Disposal:

What is e-Waste? Electronic-waste may be defined as discarded or unusable electrical-electronic devices like computers, mobile phones, television sets, and other electronic home appliances. E-Waste includes used electronics devices which are destined for reuse, resale, salvage, recycling, or disposal. It is also termed as e-Scrap or Waste Electronic Equipment (WEE). Impact of e-Waste? The processes of dismantling and improper disposing of e-waste may cause environmental

impacts leading to serious health and pollution problems. Liquid and atmospheric releases (poisonous gases) mixed up in groundwater, soil, and air and

therefore affect land and sea animals (both domestic and wild), and humans through crop’s yields, drinking water and breathing.

Disposal of e-Waste: Donate your old PCs and peripherals, which are usable and in working condition, to a school,

Educational Institutes or needy people for learning. (visit www.donateyourpc.in) Non-repairable PCs/peripherals/TVs/Monitor/Printer/ Cables/ Mother Boards/phones/digital

cameras/radios and Batteries etc. may be given to Recycling Agencies for proper disposal or re-cycling to reduce pollution and harmful environment effects.

Donate non-functional devices to Service Centers, so that they can utilize some functional parts while repairing others.

Do not through unserviceable electronic product in open area or sell to street garbage collector (‘Kabadi wala’), because they have no proper disposal system.

Serial Port

Parallel Port

USB Port

Blue Tooth

Network & Phone Port

:: 12 ::

Page 13: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Chapter 2: SOFTWARE CONCEPTS What is Software? An ordered set of instructions given to the computer is known as a program and a set of such programs that governs the operation of a computer system is known as Software. Hardware and software: The physical (tangible) components of a computer like Monitor, Keyboard, CPU etc. are called

Hardware, whereas Software is a set of programs that governs the operation of a computer and make the hardware functional.

Hardware alone cannot work unless we have some instructions for its working. The relation between hardware and software is similar to body and soul i.e. a body (hardware) is nothing without soul (software).

Types of Software: Computer software can be divided into two categories depending upon their uses and role. System Software: The software that controls internal operation of computer is called System

Software. System software controls all devices of computers. Operating System, Compilers, Interpreters etc. are example of System software.

Application Software: Application software carry out operations for a specified application. It helps to perform only one specific job like Library Management, Railway Reservation or Word Processing etc. MS Word, MS Excel and other Utility Software are example of Application software.

System Software:

System Software controls all attached devices/components of computer system and internal activities inside a computer system. Some common examples of System Software as follows:

(1) BIOS (Basic Input-Output System): The BIOS is boot firmware, a small program that controls various electronic devices attached to the computer system. It is designed to be the first set of instructions run by a Computer when powered on and performs POST (Power On Self Test) function. The POST function of the BIOS is to check and initialize devices and components of computer such as the RAM, hard disk, CD/DVD drive, video display card etc.

(2) Device Drivers: A Device Driver is a system software that acts as an interface between the Device and the User or Operating System. Some devices like Printer, Scanner, Web Camera etc. come with their own driver software given in CDs. These Drivers to be installed in the PC for proper working of the device. Most of the small devices like Keyboard, Mouse, Pen Drive, CD Drive etc. are Plug & Play, because their Driver programs are already installed with Operating System.

:: 13 ::

Page 14: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

(3) Operating System: An Operating system (OS) is a set of system programs that controls and coordinates the operations of a computer system. It works as an interface between computer hardware and user or application software. Operating system provides a software platform, on top of which, other programs, called application programs are run. The Operating System (OS) also called Resource Manager because it controls the hardware and performs all basic tasks, such as managing input/output devices, accepting input from the input devices, sending results to the output devices, keeping track of files and directories on the disk, and controlling other peripheral devices such as disk drives and printers etc. Some example of OS are Microsoft Windows, Mac OS, UNIX, Linux, Solaris, Android, Linux, Ubuntu etc. The Microsoft Windows is very popular and commonly used.

Functions of an Operating System

The major functions of an operating system can be summarized as follows: It allocates memory to program or process and keeps record of free and allocated

memory. (Memory Management) It schedules the processes for execution and allocated CPU time. (Process

Management) It controls and communicate with hardware and the attached devices (Device

Management) It manages the files, folders and directory systems on a computer. (File Management) It may also provide security to the computer system through authorization (user

name) and authentications (password) (Security Management)

Types of Operating System

The following types of operating system are generally available and used depending upon the primary purpose and applications.

Single User OS It allows one user to work at a time. It is also Single-Program OS i.e. only one program can be loaded and executed at a time. Example- MS DOS.

Multi-User OS It allows two or more users to run programs at the same time. These are Multi-Program and Time-Sharing OS, since multiple program can be loaded and executed by sharing CPU time among multiple users at the same time. Unix, Linux and Windows are common example of Multi-User OS.

Real Time OS A Real-time OS responds instantly, when input is given. The response time is pre-determined. Each job is completed in a specified dead line. It is used in Robotics, Communication and Flight Control System. LYNX and Windows CE are example of Real-Time OS.

:: 14 ::

Page 15: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

(4) Language Processor A computer can understand only machine language (Low level) or Binary language (0 and 1). A program written in High Level Languages (HLL) must be converted into its equivalent Machine code, so that computer can understand and execute. This conversion is done by Language Processors. There are so many High-Level Programming Languages like BASIC, C, C++, Java, Python etc., where a program can be written and converted in equivalent Machine Level code using language translators like assembler or Interpreter or Compiler. The Language processors are divided into three types-

Assembler:

Assembler coverts program written in Assembly Level Language into Machine level. Assembly Language consists of mnemonic codes, which to be converted (assembled) into machine code by using Assembler program .

Compiler:

A compiler is a language processor which converts (or translates) the entire program written in high level language into machine language in one go. If it fails to convert the program because of error(s) present in the program, all errors are reported together along with the line numbers for debugging. After all the errors are removed, the program can be recompiled to obtain the object program. After the compilation process is completed, the object program can directly be executed. A compiler can translate the programs of only that language for which it is written. For example C++ compiler can translate only those programs, which are written in C++. Each machine requires a separate compiler for each high level language.

Interpreter:

This language processor converts a high level language program into machine language line by line as well as executes it. If there is any error in the program, translation and execution stops and the error is reported. The conversion and execution resumes only after that error is rectified. This is a slow process and consumes high memory as the interpreter is also loaded in to memory. Debugging is the process of removing all errors from a computer program.

Application Software:

Application software is a set of programs to carry out a specific task like word processor, spreadsheet, presentation tools, library management software, railway reservation, antivirus software, etc. Generally application software can perform only one specific job, for example, library management software cannot be used for railway reservation system. Application Software can be divided into different categories depending upon their uses as follows:

(1) Utility Software: The software which keep our computer trouble free by performing some House-keeping jobs, are called Utility Software. The following Utility software are commonly used –

Compression Tools:

Using this software, you can reduce (compress) the storage size of any computer program/file while not in use. This utility comes in handy when you want to transfer a big program or computer file from one computer to another either through Internet or using storage devices like Pen Drive or CD. Example of such software are- 7-Zip, IZArc, WinRAR, PeaZip etc.

:: 15 ::

Page 16: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Backup Utility Software:

It is always advisable to take regular back-up of important data and programs stored in the computer. In case of any damage to the system, the back-up files can be restored and the important data can be recovered from the back-up files. This utility software facilitates you to take regular back-up of important files and folders stored in a drive into another storage device like a Pen drive or CD or a DVD or another computer. This backup data can be restored in case of any unforeseen situation.

Disk Defragmenter:

When computer system finds a file too large to store in a single location, it splits the file and stores it in pieces (called fragments), which are logically linked. This simply means that different parts of the file are scattered across the hard drive in noncontiguous locations. This type of fragmented file requires some extra time to access and slows down the system. Disk de-fragmentation utility software speeds up the system by rearranging such fragmented files stored on a disk in contiguous locations in order to optimize the system performance.

Antivirus detection and protection software:

A computer virus is a computer program intended to hamper the performance of a computer system. These viruses are copied into the system through some other infected programs or downloaded from the internet. The Antivirus software is used to prevent, detect and remove malware such as: computer viruses, adware, spyware, Trojan horses and worms. This utility software provides the user with a virus free work environment by restricting the entry of any unwanted program into the system. Commonly used Antivirus are Norton, Kaspersky, Quick heal etc.

Text Editor:

This utility software helps one to create, store or edit a basic text file. A text file generally stores English type text and can also store numeric and special characters with little formatting. Popular examples of text editors are Notepad, Notepad2, Notepad++, Gedit and KWrite.

(2) General Purpose Application Software: Some of the application software are designed for general day to day applications and uses. Some of these popular general purpose application software are discussed below:

Word Processor:

Word Processor is general purpose application software that facilitates the creation of documents along with text, graphics in well formatted way. Popular examples of Word processing software are Microsoft Word and Writer (open office).

Presentation Tools:

Presentation Tool facilitates the creation of presentations on any particular topic using slides. It also allows use of various formatting features like adding different types of background, different fonts, animations, audio, video, clipart and other graphics. Popular examples of Presentation tools are Microsoft Power Point and Impress (open office).

Spreadsheet Tools:

Spreadsheet Tool facilitates creation of tabular forms where some text and numerical values can be stored. It also allows creation of different types of charts and graphs based upon the numerical data stored in a worksheet. Furthermore, all common mathematical and statistical formulae can be used on the stored numeric data. Popular examples of Spreadsheet tools are Microsoft Excel and Calc (open office).

Database Management System:

Database Management System facilitates the creation, maintenance, and the use of database for an organization. It allows the user to control the addition, deletion, management, and retrieval of data in a database and generation of reports. Popular examples of Database Management System are Base (Open Office) and Microsoft Access, MS SQL Server, MySQL and Oracle.

Graphics & Multimedia Software:

:: 16 ::

Page 17: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

These software facilitates editing of images and creation of multimedia presentations and animations. Example: Photoshop, Corel Draw, Director, 3D Max etc.

(3) Special Purpose Application Software: Some application software are made for performing specific tasks generally used by the institutions, corporate, business houses, etc. and such software come under the category of specific purpose application software. The usage of few specific purpose application software is explained below:

Inventory Management System & Purchasing System:

Inventory Management System is generally used in departmental stores or in an institution to keep the record of the stock of all the physical resources. For example, a school keeps record of the number of computers, printers, printing sheet, printer cartridge available in the school's computer department.

Payroll Management System:

Payroll Management System software is used by all modern organizations to encompass every employee of the organization who receives a regular wage or other compensation. All different payment methods are calculated by the payroll software and the appropriate paychecks are issued.

Hotel Management:

Hotel Management software refers to management techniques used in the hotel sector. These can include hotel administration, accounts, billing, marketing, housekeeping, front office or front desk management, food and beverage management, catering and maintenance.

Reservation System:

Commonly seen at Railway or Flight reservation offices, this software helps the concerned department to automatically check the availability of the seats or berths of any train for any particular date.

Evaluation and Report Card Generator:

This software is commonly used in schools, universities and other Examination departments to prepare and generate the report card of students. It performs all mathematical calculations and generates the report card in specified format. It can also be used to calculate the class wise ranking of a student and merit lists.

(4) Developer tools: The design and development of Computer Software is also a tedious job which includes Writing source codes, Editing in source codes, Compiling, finding errors (bug) and removing bugs (debugging). Software Development tools (Developer tools) facilitate Software Engineer or Programmer in design and development of a software. These tools are also called Integrated Development Environment (IDE), which consists of the following components- Source Code Editor Graphical User Interface (GUI) Builder Compiler/Interpreter Debugger Application Packager or Builder

Example: Visual Basic IDE, JAVA IDE (NetBeans), Turbo C++ IDE etc.

:: 17 ::

Page 18: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Chapter 3: Computer System Security Concepts What is System Security? System security commonly refers to techniques which prevent our computer resources and data from any unauthorized access. System security covers three major dimensions of the security which is called CIA ( Confidentiality, Integrity and Authentication).

Confidentiality- ensures protection of the computer system from any unauthorized access. Integrity- ensures that information stored in the computer is protected. Authentication- ensures the authenticity of the authorized user.

Computer Security Threats

Computer systems are vulnerable to many threats that can inflict various types of damage resulting in significant losses. This damage can range from errors harming database integrity to fires destroying entire computer centers. The effects of various threats vary considerably. Some affect the confidentiality or integrity of data while others affect the availability of a system. The following are common threats to the System security.

Virus: Viruses are computer programs developed to copy themselves (self-replicate) and infect other files stored on the computer. These are malicious programs that move from computer to computer by attaching themselves to files or boot records of hard disks. Virus can automatically be transferred from one computer to another when its host is taken to the target computer. For example an user can sent it through a network or the Internet, or carried it on a removable storage medium such as CD, DVD, USB pen drive or Memory Cards. These virus programs can create files, move files, erase files, consume your computer's memory, and cause your computer not to function correctly. Therefore, it is better to prevent an attack than to try and cure it. There are many antivirus programs available that scan incoming files for viruses before they can cause damage to your computer. Some of these programs include Norton Antivirus, McAfee Virus Scan, and Quick Heal. Worm: A computer worm is a standalone program made to replicate automatically. A worm replicates continuously until the entire hard disk space and memory are eaten up and it may do so without any user intervention. This kind of self replicating programs spread over the entire hard disk and memory consequently and slow down the system. Unlike a virus, a worm does not need to attach itself to an existing executable program or code. Worms harm to a computer or a computer network by consuming bandwidth and slow down the network speed whereas viruses almost always corrupt or modify files on a targeted computer. Trojan Horse: The term Trojan is derived from the Trojan Horse story in Greek mythology. Trojan horse looks like a harmless program but actually performs malicious activities. The effect of a Trojan could be more dangerous than virus and warms. In fact, these programs perform some malicious activities like upload (send) some security files and information from the computer and at the same time download some unwanted files onto the computer. This way not only it slows own the network speed but also uploads (sends) some non shareable information to other computers like our user name, password, emails, credit card details and other secured information over the network. Trojan horses are designed to allow a hacker to target a remote computer system. Once a Trojan horse has been installed on a target computer system, it is possible for a hacker to access it remotely and perform various operations and it may do so without any user intervention at the remote end. Spyware:

Spyware is a type of malicious program installed on computer that collects information about users without their knowledge. The presence of spyware is typically hidden from the user and can be difficult to detect. Spyware can capture information like Web browsing habits, e-mail messages, usernames and passwords, and credit card information. If left unchecked, the software can transmit this data to another person's computer over the Internet.

:: 18 ::

Page 19: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Adware:

Adware are the malware programs that deliver unwanted advertisement to your computer (in Pop-up form). They are also get installed as tool bar in web browser program. They consume network bandwidth. It can display pop-up ads or irritating message and can slow down Internet speed.

All these malicious programs are termed as “Malware" Malware refers to software programs designed to damage or do other unwanted actions on a computer system. In Spanish, "mal" is a prefix that means "bad," making the term "badware," . Common examples of Malware include viruses, worms, Trojan horses, and Spyware.

Techniques used for System and Information Security

The Techniques used to secure and authorized access of Computer and Information includes software authorization, authentication, firewalls, encrypted channels, anti-virus tools and user education. It is a mechanism through which we can stop entry of viruses and other threats into our computer system. Some commonly used techniques are-

Authorization (User Name/Login ID) Something do you Know? User Authorization is done by a valid User Name/Login Id etc. User Name is a code which authorizes user to get computer access after log-in.

Authentication (Password) User is Authenticated by a valid password etc. Password is a secret code that is used to authenticate or confirm user’s identity. Password should strong enough to avoid guessing. Generally, User name and Password in combination is used to provide better security.

Biometric Identification (Physical Authentication) Something do you have? To provide more strong security, a system may have Biometric devices to identify a person by unique biological properties like Finger print , Retina Scan, Voice or Face Recognition etc., which can not be transferred or stolen by others.

CAPTCHA CAPTCHA(Completely Automated Public Turing Test to tell Computers and Human Apart) is a program that displays distorted text/images as a challenge, which can read by human beings only. It ensures that website/program is being accessed by human being and not by malicious computer programs (bots).

File Access Permission:

In a computer network or even in the internet, some files or documents are made shareable and some are made public. The protected sharable files and documents are shared among few users or even by a group having the access rights. Access rights are generally decided and given by the owner of the file or the network administrator. Files and folders stored on the computers may have limited access permissions like Read, Modify, Create and Execute permission (rights) as per need of the other users in the network. Sometimes a file may also have password to open or modify the contents to provide additional security at file level.

:: 19 ::

Page 20: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Firewall: A firewall is a technique used in a secured computer system or network to block unauthorized access and allow only the authorized user. Firewalls can be implemented in either hardware or software, or a combination of both. It is a device or set of devices or software running on a computer, which is configured to permit or deny computer applications and set of other software based upon a set of rules and other criteria designed by the network administrator. It also inspects network traffic passing through it, and denies or permits passage

Digital Certificate:

A digital certificate (also known as a public key certificate or identity certificate) is an electronic document which uses a digital signature to bind together a public key or password required for decode and encoded document with an authentic identity such as the name of a person or an organization, their phone numbers or address, and so forth. The certificate can be used to verify that a public key belongs to an authorized individual or organization.

Digital Signature: Digital signature is a method for providing the authenticity of a message, document or attachment sent through e-mail. It is commonly used in Financial and Legal transactions where forgery and tempering of document is possible. It works like a valid signature of a person on a document which ensures recipient about authenticity of document.

Cookies: A cookie (also known as a web cookie, browser cookie, and HTTP cookie) is a small bit of text or a file that accompanies requests and pages as they go between the web server and browser. The cookie is sent by a web server to a web browser and then sent back by the browser each time it accesses that server. Cookies help web sites to store information about visitors. Some cookies thus may violate privacy concerns. For example, when a user visits your site, you can use cookies to store user preferences or other information like password, address, date of birth etc. When the user visits your web site another time, the application can retrieve the information it stored earlier. A cookie can also be used for authentication, session tracking (state maintenance), storing site preferences, shopping cart contents, the identifier for a server based session, or anything else that can be accomplished through storing textual data. As text, cookies are not executable. Since they are not executed, they cannot replicate themselves and not harm the computer directly.

Cyber Crime & Cyber Law

Cyber crime refers to any crime wherein the computer is either a tool or a target or both. Some forms of Cyber Crime are Creating and sending Spam mails, Posting offensive messages on Social Networking Portals, Hacking of Computer or Cracking Security systems, unethical financial transactions and Fraud through Internet, Cyber terrorism , Creation & Propagation of Virus, Worms or Trojans etc.

Like traditional crime such as theft, fraud, forgery, defamation and mischief, Cyber Crime are also treated as criminal activities and are subject of punishment.

:: 20 ::

Page 21: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT 1 : Questions & Answers 1. What are the differences between hardware, software and Firmware ? Ans. Hawdware are the physical tangible components of a computer system. Software are the computer

programs that govern the operation of a computer System Firmware are the prewritten programs permanently stored in read-only memory

2. What are various Biometric Devices? Ans. A Biometric device translates a personal characteristic into digital code that is compared with a

digital code stored in the computer to identify an individual. A Fingerprint scanner captures curves and indentations of a fingerprint. A face recognition system captures a live face image. A hand geometry system measures the shape and size of hand. A voice verification system compares live speech with a stored voice pattern. A signature verification system recognizes the shape of a signature.

3. What are the types of computers? How do they differ? Ans. There are three types of computers (i) Digital (ii) Analog (iii) Hybrid

Digital Computers deal with discrete quantities Analog computers deals with physical quantities Hybrid computers combine the characteristics of analog and digital Computers.

4. Recognize the four categories of Output Ans. Output is a data that has been processed into a useful form. Four categories of output are text,

graphics, audio and video 5. What are the major strength and weaknesses of a computer? Ans. Strength: 1. Speed 2. Accuracy 3. Reliability 4. High storage 5. Versatility

Weaknesses: 1. Lack of decision making 2. Zero IQ 6. What is MICR? Where it is mostly used? Ans. MICR stands for Magnetic Ink Character Reader. This device can read human readable characters

that are printed using a special magnetic ink. The MICS is mostly used in banks. 7. What is the difference between OCR and OMR ? Ans. An OCR (Optical Character Reader) is used to read characters that are printed on paper or it is a

scanned document which can be edited. On the other hand an OMR (Optical Mark Reader) is used to transcribe marks that are marked with a dark pencil or ink on a special preprinted form (answer sheet of multiple choice question paper where choice of the answer is reflected by shading the correct box)

8. What are the two categories of printers? Which type of printer is more speedy Ans. The printers can be classified in two categories

1. Impact Printers: In these type of printers, there is a physical connection between the paper and the print head. They are (i) Line Printer (ii) Dot Matrix Printer

2. Non Impact Printer: In these types, there is no physical connection between the paper and the print head. The printing takes place with some electromagnetic, thermal, laser techniques. They are (i) Inkjet Printer (ii) Laser Printer (iii) Thermal Printer

The Non Impact printers are speedier than Impact printers 9. What is the difference between RAM and ROM ? Ans. RAM stand for Random Access Memory where both read and write operation can take place, but

this is volatile memory; its contents are lost when power is turned off ROM stands for Read Only Memory where only read operation can take place. This is a non volatile memory Both RAM and ROM are the parts of primary memory

10. What does a Bus mean ? Ans. A Bus is a group of conducting lines that carries data, address and control signals between a CPU

and memory. 11. What is Port? Name some port types Ans. Port is a point on a computer having circuitry to allow connection of external devices with

computer. Ports are of various types Serial Port, Parallel Port, InfraRed Port, Phone Port, USB Port,

:: 21 ::

Page 22: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

AGP Port, Network Port etc. 12. Write the full forms of the following terms VDU, LCD, DMP, CRT, CD-RW, DVD

Ans. VDU – Visual Display Unit LCD – Liquid Crystal Display DMP – Dot Matrix Printer CRT – Cathode Ray Tube CD-RW – Compact Disk

DVD – Digital Video Disk

13. What do you mean by e-Waste? Suggest some disposal guidelines? Ans. Electronic-waste or e-Scrap may be defined as discarded or unusable electrical-electronic devices

like computers, mobile phones, television sets, and other electronic home appliances. E-Waste includes used electronics devices which are destined for reuse, resale, salvage, recycling, or disposal. e-Waste can be disposed by the following way-

Port is a point on a computer having circuitry to allow connection of external devices with computer. Donate your old PCs and peripherals, which are usable and in working condition, to a school, Educational Institutes or needy people for learning. (visit www.donateyourpc.in)

Non-repairable PCs/peripherals/TVs/Monitor/Printer/ Cables/ Mother Boards/phones/digital cameras/radios and Batteries etc. may be given to Recycling Agencies for proper disposal or re-cycling to reduce pollution and harmful environment effects.

Donate non-functional devices to Service Centers, so that they can utilize some functional parts while repairing others.

Do not through unserviceable electronic product in open area or sell to street garbage collector (‘Kabadi wala’), because they have no proper disposal system.

14. What are various categories of System software? Ans. System Software are used to control internal computer operations. The system software can be

following types- Operating System : An Operating system is a set of programs which act as a interface between a user and hardware. Language Processors : This program is responsible for converting a HLL code into machine understandable code. Device Drivers : This program is responsible to make a communication link between devices and OS or user. BIOS: It is a firmware which is stores in BIOS chip and responsible to check the status of the devices connected to the PC when started.

15. What are various types of Operating System ? Ans. The Operating system are mainly following types : Single User OS

It allows one user to work at a time. It is also Single-Program OS i.e. only one program can be loaded and executed at a time. Example- MS DOS.

Multi-User OS It allows two or more users to run programs at the same time. These are Multi-Program and Time-Sharing OS, since multiple program can be loaded and executed by sharing CPU time among multiple users at the same time. Unix, Linux and Windows are common example of Multi-User OS.

Real Time OS A Real-time OS responds instantly, when input is given. The response time is pre-determined. Each job is completed in a specified dead line. It is used in Robotics, Communication and Flight Control System. LYNX and Windows CE are example of Real-Time OS.

16. What is fragmentation? How does it affect computers performance? Ans. Fragmentation means files stored in fragmented storage blocks. That is when files are not stored

in contiguous storage areas rather their contents are scattered over the disk it is known as fragmentation. High fragmentation slows down a computer as the computer has to perform more read/ write operations.

:: 22 ::

Page 23: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

17. What is application software? Why are its types? Ans. Application Software: Application software is the set of programs necessary to carry out

operations for a specified application. These are the programs written by programmers to enable computer to perform a specific tasks such as processing word, inventory controls, handling calculation and figures, medical accounting, financial accounting, result preparation, railway reservation, billing etc. Application Software Types: Utilities: They are those applications programs that assist the computer by performing housekeeping functions like baking up disk or scanning / cleaning viruses or arranging information etc. General purpose Application: This type of software performs general applications like word processing, spreadsheet and database management etc.. Specific Purpose Application: The type of software is developed to meet all the requirements specified by the user. Developers Tools: These software are used by the programmers to write, debug and execute the program. These are also called IDE(Integrated Development Environment)

18. What do you understand by IDE ? Ans. IDE stands for Integrated Development Environment. It is an application program consisting of

different development tools needed for developing and application. 19. What is Desk Top Publishing (DTP) Software? Give an example of DTP Software.

Ans. DTP stands for Desk Top Publishing. It is software that handles page layouts by combining the functions of traditional typesetter and a layout artist. Example is Corel Draw, Page Maker etc.

20. What is Operating System? Write its function. Ans. An Operating system (OS) is a set of system programs that controls and coordinates the

operations of a computer system. It works as an interface between computer hardware and user or application software. Operating system provides a software platform, on top of which, other programs, called application programs are run. The Operating System (OS) also called Resource Manager because it controls the hardware and performs all basic tasks, such as managing input/output devices, accepting input from the input devices, sending results to the output devices, keeping track of files and directories on the disk, and controlling other peripheral devices such as disk drives and printers etc.

Some example of OS are Microsoft Windows, Mac OS, UNIX, Linux, Solaris, Android, Linux, Ubuntu etc. The Microsoft Windows is very popular and commonly used.

Functions of an Operating System

The major functions of an operating system can be summarized as follows: It allocates memory to program or process and keeps record of free and allocated

memory. (Memory Management) It schedules the processes for execution and allocated CPU time. (Process

Management) It controls and communicate with hardware and the attached devices (Device

Management) It manages the files, folders and directory systems on a computer. (File Management) It may also provide security to the computer system through authorization (user

name) and authentications (password) (Security Management) 21. What is Compiler? How it is different from Interpreter?

Ans: A compiler is a language processor which converts (or translates) the entire program written in high level language into machine language. A compiler can translate the programs of only that language for which it is written. For example C++ compiler can translate only those programs, which are written in C++. Each machine requires a separate compiler for each high level language.

Difference between Compiler and Interpreter- 1. Compiler translates entire program in one go, however Interpreter translates program

in line by line mode. 2. In case of any error in the program, compiler reports all error along with the line

numbers for debugging. After all the errors are removed, the program can be recompiled and executed. But Interpreter stops translation, in any error occurred. The conversion and execution resumes only after that error is rectified.

:: 23 ::

Page 24: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

22. Define the following. (a) Spam (b) Malware (c) Phishing (d) Firewall (e) Digital Signature (f) Digital Certificate

Ans. Spam : Email spam, also known as junk email or unsolicited bulk email (UBE), is a subset of electronic spam involving nearly identical messages sent to numerous recipients by email. Clicking on links in spam email may send users to phishing web sites or sites that are hosting malware. Spam email may also include malware as scripts or other executable file attachments. Definitions of spam usually include the aspects that email is unsolicited and sent in bulk. Malware: Malware, short for malicious software, is software used or created to disrupt computer operation, gather sensitive information, or gain access to private computer systems. It can appear in the form of code, scripts, active content, and other software Phishing: Phishing is attempting to acquire information (and sometimes, indirectly, money) such as usernames, passwords, and credit card details by masquerading as a trustworthy entity in an electronic communication Firewall: A firewall can either be software-based or hardware-based security system which is used to help keep a network secure. Its primary objective is to control the incoming and outgoing network traffic by analyzing the data packets and determining whether it should be allowed through or not, based on a predetermined rule set. Digital Signature: A digital signature or digital signature scheme is a scheme for demonstrating the authenticity of a digital message or document. A valid digital signature gives a recipient reason to believe that the message was created by a known sender, and that it was not altered in transit. Digital signatures are commonly used for software distribution, financial transactions, and in other cases where it is important to detect forgery or tampering. Digital Certificate: A digital certificate is an electronic "credit card" that establishes your credentials when doing business or other transactions on the Web. It is issued by a certification authority. It contains your name, a serial number, expiration dates, a copy of the certificate holder's public key (used for encrypting messages and digital signatures), and the digital signature of the certificate-issuing authority so that a recipient can verify that the certificate is real.

23. What do you mean by system security? Discuss some preventive measures? Ans: System or Information Security refers the protection of information and system resources with

respect to confidentiality and integrity. System Security covers three dimensions of security known as CIA, which are-

Confidentiality:- Ensure that information is not accessed by unauthorized persons i.e. protection against unauthorized access. Integrity:-Ensure that information is not changed by unauthorized persons i.e. protection against unauthorized modification. Authentication:-Ensure that users are the persons they claim to be i.e. Identification of Authorized user.

Some preventive measures are- Install a effective and reliable Anti-virus and Anti-Spyware program. Keep your Anti-virus program update. Be careful while downloading and opening e-mails. Use proper File access permissions when it is being shared among users. Use Filter utility to get off spam. Keep your e-mail address, passwords etc. private. Install Firewall to prevent unauthorized access to or from a private network. Disable cookies to avoid misuse of private data. Disconnect Internet when it is not in use.

24. What do you mean by Cyber crime? Ans: Cyber crime refers to any crime wherein the computer is either a tool or a target or both. Some forms of Cyber Crime are-Creating and sending Spam mails, Posting offensive messages on Social Networking Portals, Hacking of Computer or Cracking Security systems and Unethical Financial transactions and Fraud through Internet etc.

:: 24 ::

Page 25: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT -2 Introduction to Java Programming

Chapter 4: Getting started with Java IDE

What is Java? JAVA is an Object Oriented programming language as well a platform. By using JAVA, we can

write application programs, which can run on any type of OS and Hardware.

JAVA is designed to build Interactive, Dynamic and Secure applications on network computer system.

Java facilitates development of multilingual applications because JAVA uses 2-Byte UNICODE character set, which supports almost all characters in almost all major languages of the world.

JAVA was developed by James Gosling at Sun Microsystems to write applications for electronic devices like TV-Set Top Box etc. The language was initially called Oak and later renamed as Java.

Features of Java: Object Oriented Language-Java is Object Oriented Language (a real-world programming style)

Open Source Product-It is Open Source i.e. freely available to all with no cost.

Write Once Run Anywhere (WORA)-JAVA Program can be run on any type of H/W and OS platforms i.e. Java programs are platform independent.

Light Weight Code-Big applications can be developed with small code.

Security-JAVA Programs are safe and secure on Network.

Interpreter & Compiler based Language-JAVA uses both Compiler and Interpreter (JVM) to produce portable and platform-independent object code.

Built-in Graphics & Supports Multimedia-JAVA is equipped with Graphics feature. It is best for integration of Audio, Video and graphics & animation.

Byte code: A byte code is machine 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. This makes Java program platform independent.

Why Java is platform independent:

A program written in HLL must be converted into its equivalent Machine code, so that computer can understand and execute. This conversion is known as Compilation. Generally, the converted machine code depends on the structure of Hardware and OS platform. So that a Windows program will not work on UNIX, or LINUX or Mac platform etc. Since they are Platform dependent.

A program written in JAVA is platform-independent i.e. they are not affected with changing of OS. This magic is done by using Byte code. Byte code is independent of the computer system it has to run upon.

Java compiler produces Byte code instead of native executable code which is interpreted by Java Virtual Machine (JVM) at the time of execution.

:: 25 ::

Page 26: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

GUI Programming using JAVA: GUI is an acronym for Graphical User Interface which is an interface that allows us to interact with the various components through visual elements including pictures, graphical icons, symbols and visual indicators. Graphical User Interface (GUI) based application contains Windows, Buttons, Text boxes, Dialogue boxes and Menus etc. While using a GUI application, when user performs an action, an Event is generated. Each time an Event occurs, it causes a Message which sent to OS to take action. In JAVA, the GUI programming is done through Swing API (Application Programming Interface) which enables look-and feel (L&F) environment. A GUI application in JAVA contains three basic elements-

1. Graphical Component (Event Source):

It is an object that defines a screen element such as Button, Text field, Menus etc. They are source of the Events. In GUI terminology, they are also known as Widget (Window Gadget). It can be container control or child control.

2. Event:-

An Event (occurrence of an activity) is generated when user does something like mouse click, dragging, pressing a key on the keyboard etc.

3. Event Handler (Listener) Method:

It contains method/functions which is attached to a component and executed in response to an event. In Java, Listener Interface stores all Event-response-methods or Event-Handler methods.

Graphical Control in Java:

The Java offers various Swing controls to facilitate development of GUI applications. A typical GUI form may contain various controls for data handling.

Most commonly used controls are- jFrame: A Frame is a container control, in which all the controls can be placed. It works like a

window for user interface.

jPanel: It is container controls which contains or groups other controls in a frame.

:: 26 ::

Page 27: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

jLabel: JLable allows placing un-editable text or picture. jTextField: JTextField allows placing editable text on the Frame. User can enter text in a

textFiled during runtime. jButton: is used to initiate an action when it is clicked. jList: jList is a group of values or items from which one or more selections can be made. jComboBox: jComboBox is similar to jList but also allow to enter editable text during run time. It

is a combination of jTextFiled and jList. jRadioButton: Allow us to choose a single item from a group of jRadioButton options. jCheckBox: Allow us to choose one or more items from a group of jCheckBox options. jPasswordField: Allow us to enter a text during the run time but shows an encrypted text

instead of the original text jTextArea: JTextArea is a multi-line text component used to enter or edit text.

JFrame, jPanel, jDialog etc. are called Container control , because these controls holds other Component (child) controls.

Working with JAVA IDE –Netbeans:

Netbeans is a Java’s IDE, which used to design GUI (Graphical User Interface) applications using Swing controls (graphical components). GUI allows us to interact with the various components through visual elements including pictures, graphical icons, symbols and visual indicators. For example to add a button we simply have to drag the button icon from the Swing Controls tab in the Palette. Similarly as we are writing code, small visual indicators appear informing us about the errors in the code. The Netbeans GUI Builder's various windows include four main components as displayed in Figure.

These components are explained below:

1. Design Area: The GUI Builder's primary window for creating and editing Java GUI forms. The toolbar's Source and Design toggle buttons enable us to view the source code or a graphical view of its GUI components. The additional toolbar buttons provide convenient access to common commands, such as aligning components, setting component auto-resizing behaviour, and previewing forms.

:: 27 ::

Page 28: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

2. Inspector Window: Provides a graphic representation of all the components attached in our application as a tree hierarchy. The Inspector also provides visual feedback about what component in the tree is currently being edited in the GUI Builder.

3. Swing Palette Window: Contains a list of components containing tabs for Swing controls, and JavaBeans components.

4. Properties Window: Displays the properties of the component currently selected in the GUI Builder, Inspector window, Projects window, or Files Window. You can customize the properties of selected control.

5. Project Explorer Window: Displays the information about currently and recently opened Projects. You can explore various components of the project.

6. Output Window: Output Window displays the output as well as Error description while writing/compiling of the application.

Commonly used Swing Controls & Properties and Methods:

Netbeans offers various Swing controls which can be placed on the container frame. Most commonly used controls are TextField, Text Area, Button, RadioButton and ComboBox etc. These controls are having some appearance properties like background color, font, height, width etc. which can be set at design-time. The functionalities (behavior) of a control are governed by invoking its Methods at run-time. The commonly used Swing Controls and their concern methods and properties are given below-

Swing Controls Methods Properties jButton • getText()

• setText() • Enabled • Text • Label

jLabel • getText() • Enabled • Foreground • Text

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

• Editable • Enabled • Text

jRadioButton & jCheckBox

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

• Button Group • Enabled • Label

jComboBox • getSelectedItem() • getSelectedIndex()

• Editable • Enabled • SelectedIndex • SelectedItem • Text

jList • getSelectedValue() • Enabled • SelectedIndex • Text

JoptionPane • showMessageDialog() Foregraound, Background and Font properties are also common with these controls.

To use a method we should write –

<control name>.<method name> Example : jTextField1.getText()

jTextField1. setText(“hello”) etc.

:: 28 ::

Page 29: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Designing GUI Application in NetBeans:

After launching NetBeans IDE, you may follow the following steps to create a Java application.

Step 1: Create a new Project (choose File > New or New Project tool) and name the project.

Step 2: Add a form ( Right Click on Project in Project Explorer Window and choose Add >jFrame)

Step 3: Add the desired component from the Palette window using drag and drop feature

Step 4: Customize the appearance properties of attached controls like Background, Foreground, Font, height, width and Text etc. using Properties Window.

Step 5: Add the Event Handler Method (To Do code) by selecting desired Event. Mostly events are attached with Buttons as ActionPerformed event.

Step 6: Test the form by pressing Shift+F6 or Run>Run File.

Adding Swing Controls on the Frame: After creating a Project and adding new JFrame, you may attach various controls (Graphical Components) like jTextField, jLabel, jButtons etc. from the Swing Palette Window using Drag-Drop feature of Netbeans IDE. When you drag a component like jTextField from Swing Palette, Netbeans creates its instance with default name like jTextField1, jTextField2 etc. We can change object’s default name by double clicking on control name in Inspector Window and providing a new name or by choosing Rename option (select control and press Right Click) with suitable familiar name. The following naming rules/conventions should be followed while renaming a control.

Name must begin with a letter.

Name must contain only letters, numbers, and underscore. Punctuation (, ; .) and spaces are not allowed.

When user familiar name is given to a control, first letter is generally capitalized. For example, a control jTextField1 for employee name can be renamed as TxtEmpName for easy reference. A button jButton1 with OK caption can be given a familiar name such as BtnOK etc.

Attaching Event Methods with Controls: In GUI application, after designing application with required graphical controls like TextFields, Labels and Buttons etc., we require an event handler method to trap user generated event and perform some action accordingly. This event method comprises codes/statement in a logical order. The following step are required to create Event Handler method in Netbeans-

Right Click on desired control of the Form in Design view.

Choose desired Event from the Context Menu and its Sub Menu.

When you click on desired Event, it opens source Code editor with default Handler Name, where you can type TODO code for the Handler.

You will found a code window along with prototyped method to perform actions defined by you. You may write commands to be executed in //TODO section.

:: 29 ::

Page 30: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Displaying Text in GUI :

In GUI application often we require to display information as a message or value. The following two ways are used –

Using jTextFields or jLabel Controls-

jTextField1.setText(“Hello!!! Welcome in Java Programming”); jLabel1.setText(“Hello Java”);

Using Dialog Box-

JOptionPane.showMessageDialog(null, “Hello.. how are you?“);

Commonly used controls and their methods: Most of methods in Java are categorized as -

.set…( ) method : These methods are used to set the values on the component at run-time.

.get…( ) method : These methods are used to get or read the values from the component at run-time.

.is…( ) method : These methods returns true/false values and used to check the status of component at run-time.

Method Usage with example exit() application

To successfully terminate an application. System.exit(0);

showMessageDialog() To display a specified message in a dialog box. JOptionPane.showMessageDialog (null, “Hello Java”);

setText() To display text (label, text field or button) during run time. jLabel.setText(“Hello”); jTextField1.setText(“”); //clears text box//

getText() To retrieve the text of a component (label, text field or button) at run time. String str=jTextField1.getText();

concat() To concatenate (add) string2 at the end of the string1. “Hello”.concat(“Java”);

toString()

To convert an Integer value to String type. jTextField1.setText(Integer.toString(5);

Integer.parseInt()

To convert a st ring value to Integer type. Integer.parseInt(jTextField1.getText());

Double.parseDouble()

To convert a st ring value to Double type. Double.parseDouble(jTextField1.getText());

setVisible() To set the visibility of a component at run time. setVisible(true) implies that the component is visible and setVisible(false) implies that the component is hidden. jTextField1.setVisible();

setEditable() To set the editing property of a component at run time. The setEditable(true) implies that the contents of this component can be changed at run time and setEditable(false) implies that the contents of this component cannot be changed at run time. jTextField1.setEditable(false);

setEnabled() To set the enabled property of a component at run time. The setEnabled(true) implies that this component can trigger a reaction at run time and setEnabled (false) implies that this component cannot trigger a reaction at run time. jTextField1.setEnabled(false);

:: 30 ::

Page 31: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Chapter 5: Programming Fundamentals Token The smallest individual unit in a program is known as Token. Java has the following types of tokens: Keywords (Reserve words), Literals, Identifiers, variable, Punctuators (. ; , etc.) and operators are called Java Tokens. Keywords Keywords are words that have a specific predefined meaning in Java. They cannot be used as variable names. They are also known as reserve words. eg. void, private, if, while etc. Literals: Items having fixed data values are referred to as Literals. They are also known as Constants. Various types of literals available in Java are :

Integer literals – may be a positive or negative integer number (without decimal). Floating literals- may be a positive or negative decimal number. Boolean literals- true or false Character literals – a single character in single quotes. String literals- group of characters enclosed in double quotes. Null literals – special symbol indicating nothing.

Identifier: A user given name to any object, class, variable or constant. The naming rules for identifiers are-

• Identifiers may have alphabets, digits and dollar ($), underscore (_) sign. • They must not be Java keywords. • They must not begin with digit. • They can be of any length. • They are Case Sensitive ie. Age is different from age.

Example of Valid identifiers- MyFile, Date9_7_7, z2t09, A_2_Z, $1_to_100, _chk etc. Example of Invalid identifiers- Date-RAC, 29abc, My.File, break, for etc.

Data types in JAVA:

Data types are means to identify the type of data and associated operations of handling it. Java offers two types of data types.

Primitive: These are in-built data types offered by the compiler. Java supports 8 primitive data types e.g. byte, short, int, long, float, double, char, boolean etc. Reference: These are constructed by using primitive data types, as per user need. Reference data types store the memory address of an object. Class, Interface and Array are the example of Reference Data types.

Java also offers ‘String’ data type which belongs to Reference data type and may contains group of characters.

:: 31 ::

Page 32: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

The following primitive data types are used in Java.

Type Size Description Range

byte 1 Byte Byte integer -128 to +127

short 2 Byte Short integer -32768 to +32767

int 4 Byte integer -231

to 231

-1

long 8 Byte Long integer -263

to 263

-1

float 4 Byte Single precision floating point (up to 6 digit) -3.4x10-38

to +3.4x1038

double 8 Byte Double precision floating (up to 15 digit) -1.8x10-308

to +1.8x10308

char 2 Byte Single character 0 to 65536

Boolean 1 Byte Logical Boolean values True or False

Working with Variables:

A variable is named memory location, which holds a data value of a particular data type. Declaration and Initialization of variable- <data type> <variable Name>; Example: int age; double amount; double price=214.70, discount =0.12; String name=“Amitabh” ; float x= a+b;

• By default all Numeric variables initialized with 0, and character/String and reference variable with null, and boolean with false, if it is not initialized.

• The keyword final can be used with variable declaration to indicate constant. E.g. final double SERVICE_TAX=0.020; Naming Rules and Conventions for Variables- The rules and conventions for naming variables in Java are summarized below:

Variable names are case sensitive.

Keywords which have special meaning in java, should not be used as the variable names.

Variable names should be short and meaningful.

All variable names must begin with a letter, an underscore(_) or a dollar sign($). The convention is to always use a letter.

After the first initial letter, variable names may contain letters and digits (0 to 9) and (_,$), but no spaces or special characters are allowed.

Using the above conventions and rules following is an indicative list of acceptable and unacceptable variable names. Example:- Valid Variable Names - Grade, Test_Grade, TestGrade, EmpName, StAge $Rs etc. Invalid Variable Names - Grade(Test), 2ndTestGrade, Test Grade, GradeTest#2 etc. Operators in Java:

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Java offers the following types of Operators:-

:: 32 ::

Page 33: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Arithmetic Operators :

+ Unary plus Represents positive values. int a=+25;

- Unary minus Represents negative values. int a=-25;

+ Addition Adds two values int x= a+b;

- Subtraction Subtract second operands from first. int x=a-b;

* Multiplication Multiplies two values int x= a*b;

/ Division Divides first operand by second int x=a/b;

% Modulus (remainder) Finds remainder after division. int x= a%b;

+ Concatenate or String addition

Adds two strings “ab”+”cd” ”abcd” “25”+”12” ”2512” “”+5 ”5” “”+5+”xyz” ”5xyz”

Increment/Decrement Operator :

Java supports ++ and -- operator which adds or subtract 1 from its operand. i.e. a=a+1 equivalent to ++a or a++ a=a-1 equivalent to --a or a--

++ or -- operator may used in Pre or Post form. ++a or --a (increase/decrease before use) and a++ or a– (increase/decrease after use)

Example:- Find value of P? (initially n=8 and p=4) p=p* --n; 28 p=p* n--; 32 Relational Operators:

Relational operators used to compare two values and returns true or false as per the relation between operands. Java offers the following six relational operators. Operator Meaning Usage == equal to Tests whether two values are equal. != not equal to Tests whether two values are unequal. > greater than Tests if the value of the left expression is greater

than that of the right. < less than Tests if the value of the left expression is less than

that of the right. >= greater than or equal to Tests if the value of the left expression is greater

than or equal to that of the right. <= less than or equal to Tests if the value of the left expression is less than or

equal to that of the right. Example: 3>=3 true and 3!=3 false

Logical Operators :

Logical operators returns true or false as per the condition of operands. These are used to design more complex conditions.

Operator Name use Returns true if

&& And x&&y X and y both true

|| Or x||y Either x or y is true

! Not !x X is false

Example- 5>8 || 5<2 ( returns false) 6<9 && 4>2 (return true)

:: 33 ::

Page 34: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Assignment Operators:

In Java = operator is known as Assignment operator, it assigns right hand value to left hand variables. Example- int x=5; or z= x+y; Java offers some special shortened Assignment operators, which are used to assign values on a variable. These operators are-

Operator use Equivalent to

+= X+=Y X=X+Y

-= X-=Y X=X-Y

*= X*=Y X=X*Y

/= X/=Y X=X/Y

%= X%=Y X=X%Y Example : x-=10 is equivalent to x=x-10

Other Operators:

In Java various other operators like ?: (conditional operator), new , [], (type) etc. are used.

Java Expression:

An expression is a valid combination of operators, constants and variable and keywords i.e. combination of Java tokens. Java expression may Arithmetic, Compound and Logical depending on the operators and values. In java, three types of expressions are used. Arithmetic Expression

Arithmetic expression may contain one or more numeric variables, literals and operators. Two operands or operators should not occur in continuation. e.g. x+*y and q(a+b-z/4) are invalid expressions. Pure expression: when all operands are of same type. Mixed expressions: when operands are of different data types. Compound Expression

It is combination of two or more simple expressions. e.g. (a+b)/(c+d) (a>b)||(b<c) Logical Expression

Logical or Boolean expression may have two or more simple expressions joined with relational or logical operators. Example - x>y , (y+z)>=(x/z) , x||y && z Implicit & Explicit data type Conversion in Java:

An expression containing different data type like int, float, double etc. all operands are promoted (Coercion) up to the largest data type in the expression. For example if an expression contains int and float value/variable then int data type is promoted to float data type. This conversion is called Implicit Data type conversion and is performed by the compiler itself. An explicit conversion is user defined conversion that forces to convert an operand to a specific data type by (type) cast. Example- Suppose x is integer type then if we write – (float) (x/2) then result of x/2 is converted in float otherwise it will give integer result. Example- 100/11 will give 9 not 9.999 (since both are integer) Example - int a, mb=2, k=4 then evaluate a = mb*3/4+k/4+8-mb+5/8 = 2 * 3 / 4 + 4 / 4 + 8 – 2 + 5 / 8 = 6 / 4 + 1 + 8 – 2 + 5 / 8 = 1 + 1 + 8 – 2 + 0 (6/4 will give 1 ) = 8

:: 34 ::

Page 35: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Conversion of String into number - Parsing

Some time it is required to convert numbers stored in string form in to numeral form so that calculation can be carried. parse() methods helps to parse string into different numeric types.

Method Syntax Usage parseByte() Byte.parseByte(string) To convert a string value to byte type parseShort() Short.parseShort(string) To convert a string value to type short parseInt() Integer.parseInt(string) To convert a string value to Integer type

parseLong() Long.parseLong() To convert a string value to Long type parseFloat() Float.parseFloat() To convert a string value to Float type pareseDouble() Double.parseDouble() To convert a string value to Double type

Designing Application in Java NetBeans:

Consider the following ‘Simple Interest Calculator’ application. The aim of the application is to accept the principal amount, rate and time in three separate text fields and calculate the simple interest on the click of a button. Design the application Form as per screen shot with four jTextField and two jButton controls with proper labeling.

Now, to attach Event method with jButton1, double click on the jButton1 to open code editor and write the following code in TODO section.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

double Principal,Rate,SInterest; int Time; Principal = Double.parseDouble(jTextField1.getText()); Rate = Double.parseDouble(jTextField2.getText()); Time = Byte.parseByte(jTextField3.getText()); SInterest = (Principal*Rate*Time)/100; //Formula to calculate SI jTextField4.setText(Double.toString(SInterest));

} Attach Event method with jButton2 to close the application.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); }

At last run the application and test application with real data.

:: 35 ::

Page 36: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Chapter 6: Control Statements in Java

In general a program is executed from begin to end. But sometimes it required to execute the program selectively or repeatedly as per defined condition. Such constructs are called control statements. Control flow statements, however, breakup the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. The following two type of control statements are used in Java. Selection (conditional): Execution of statement depends on the condition, whether it is True or False. (Ex. if.., if…else, switch constructs) Iteration (Looping): Statement is executed multiple times (repetition) till the defined condition True or False. (Ex. for.. , while… , do..while loop constructs)

Selection (Conditional) statements:

A selection statement selects among a set of statements depending on the value of a controlling expression. if statements:

The if statement allows selection (decision making) depending upon the outcome of a condition. If the condition evaluates to true then the statement immediately following if will be executed and otherwise if the condition evaluates to false then the statements following the else clause will be executed.

Simple if: The syntax of if statement is as shown below:

Syntax: if (conditional expression) { Statement Block; }

if-else :The syntax of if-else statement is as shown below: Syntax:

if (conditional expression) { Statement Block; } else { Statement Block; }

Nested if- else : These control structures are used to test for multiple conditions as against the simple if statement which can be used to test a single condition. The syntax of nested if else is as follows:

Syntax: if (conditional expression1) { statements1; } else { if (conditional expression2)

{ statements2; ………………… }

else { statements3; ………………….. } }

Example- if (num>0) { jLable1.setText(“Number is positive”); }

Example- if ( age>=18) jLable1.setText(“Eligible to Vote”); else jLable1.setText(“Not eligible to Vote”);

Example- if ( num>0) { jLable1.setText(“Number is positive”); } else { if (num<0) jLable1.setText(“Number is negative”); else jLable1.setText(“Number is zero”); }

:: 36 ::

Page 37: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

switch:

This selection statement allows us to test the value of an expression with a series of character or integer values. On finding a matching value the control jumps to the statement pertaining to that value and the statement is executed, till the break statement is encountered or the end of switch is reached. The syntax of the switch statement is as follows:

switch (Variable/Expression) {

case <Value1> : statements1 ; break ;

case <Value2> : statements2 ; break ;

default: statements3 ; }

Switch v/s if..else statement:

The switch and if..else both are used to make a selection construct in Java, but there some differences. Switch can test only equality whereas if.. Can evaluate any type of relational or logical

expression. In switch a single value or constant can be tested but in if.. more versatile expression can be

tested. The switch statement can handle only byte, short, int or char variable but If.. can test more

data type like float, double or string etc. In switch we cannot use any relational operator like > ,<, <=, != etc. where as with if … we can

any relational expression including relational and logical operators.

Looping statements:

These statements are used to perform a set of instructions repeatedly while the condition is true. The ‘for’ and ‘while’ loop is called Entry-Controlled loop because condition is tested at entry point of loop i.e. loop is executed only if defined condition is true. The ‘do’ loop is Exit-Controlled since condition is tested at exit point i.e. loop is executed at least single time even defined condition is false. For loop:

The syntax of the for loop is: for( initialization; test expression; increment/decrement expression) { statements; }

In for loop all the parameter like initialization, text condition or increment/decrement is optional.

While loop : The while loop is an entry-controlled loop. It means that the loop condition is tested before executing the loop body. The syntax of the while loop is as follows:

while(test expression) { loop body }

Example- switch (day) { case 1 : jTextField1.setText(“One”); break; case 2 : jTextField1.setText(“two”); break; case 3 : jTextField1.setText(“three”); break; default : jTextField1.setText(“Other”); }

//loop to generate first 10 numbers // for (int i=1; i<=10 ; i++ ) { jTextArea1.append (“ ”+i); }

//loop to find even nos. up to 50 for (int i=0; i<=50 ; i=i+2){ jTextArea1.append (“ ”+i); }

//while loop to generate first 10 numbers // int i=1; while (i<=10 ) { jTextArea1.append (“ ”+i); i++; }

:: 37 ::

Page 38: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

do while : 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. The syntax of the loop is as follows:

do { loop body }while (test expression);

Break and Continue statement:

Java offers three jump statements (return, break and continue), which transfers the control else where unconditionally. The break is used with for.., while, do.. and switch statements which enables the program to

skip over some part of the code and places control just after the nearest closing of block. It is used to terminate the loop.

The continue statement is used within looping statement (not with switch) and works like break i.e. it also skips the statements. Unlike break, it forces the next iteration of loop by skipping the in between code and continues the loop.

The return statement can be used any where in the program. It transfers the control to calling module or Operating System. However Java provides System.exit() method to stop the execution of program.

Scope of variables:

In Java, a variable can be declared anywhere in the program but before using them. The area of program within which a variable is accessible is known as its scope. A variable can be accessed within the block where it is declared.

//do loop to generate first 10 numbers // int i=1; do { jTextArea1.append (“ ”+i); i++; while (i<=10 ); }

:: 38 ::

Page 39: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Chapter 7: PROGRAMMING GUIDELINES Writing a good Program is an art. You should follow the following points while designing an application-

Make sure that the user provides appropriate information with minimum efforts. Maximize use of radio button, checkbox, combo box, and list.

Radio Button should be used wherever one of the option out of limited number of known set of options are required to be taken from the user. For example, for accepting gender (Male or Female), marital status (Single or Married), for accepting membership type (Monthly, Annual or Lifetime) etc.

Checkbox should be used wherever multiple options are required to be selected from a limited number of known set of options. For example, for accepting multiple hobbies (Swimming, Singing, Dancing, Debating), for accepting food order in a restaurant (Pizza, Burger, Channa Kulcha, Pao Bhaji, Chowmein) etc.

Combo box should be used wherever only one of the options from a large number of known set of options is required to be taken from the user. For example, selecting state, selecting marital status, selecting schools and selecting city etc.

List should be used wherever multiple options are required to be selected from a large number of known set of options. For example, selecting multiple food items from a menu containing five or more number of items.

It is advisable to use appropriate labels for each input and output options to help the user to correctly interpret them.

While writing the code do not use variable names as A, B, C etc. Instead use meaningful names and follow naming conventions. They make the code easier to read, understand and maintain. For example a variable storing total marks should be named as Total_Mark.

The conditional construct if..else should be preferred when there are very few alternative execution paths and also when decisions are to be made based on ranges of values or conditions.

The switch construct should be used when there are too many alternative execution paths and decisions are based only on a single integer or enumerated value (countable value).

Use appropriate comments. Comments can be used to explain the various complicated steps of the program thereby making the program more understandable for the user. In Java single line comments begin with '//' and multiple lines of comments are enclosed between '/*' and '*/' (quotes are not to be included).

Stylistic Guidelines

Meaningful Names for Identifiers Variable, Class and Method names should be meaningful and unambiguous. It makes the clarity and readability of the program. Ensure clarity of expression

Expression in the program should be written clearly. Proper parenthesis may be used to enhance the clarity of the expression. Use of comment & Indentation

A Program should have proper comment to explain the various parts of the program. Proper Indentation makes the program more readable. Insert Blank Lines and spaces

Blank lines can inserted before the declaration of blocks, comment lines, method’s prototype etc. It increases readability. Space must be given before and after an operator to make it more readability. Statement Formatting

Program should be pretty typed i.e. All the statement must be written in separate lines. So that program may be readable and understandable.

:: 39 ::

Page 40: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Characteristic for a Good Program

A good Program not only efficiently solves the given problem but also it should be presentable. The following features are expected for its goodness- Effective & Efficient

It must produce correct result for what it is written. The program should be time and memory efficient. User Friendly

The Interface (form Design) should be pleasant, attractive and well labeled. So that user can handle it effectively. The output produced by the program should also understandable and presentable. Self- Documenting Code

The source code of the program should have meaningful names for Identifiers and Variables, and proper comment should be used to make it self-documenting. Reliable

The Program should be reliable i.e. able to handle errors and give accurate result. Portable

A Program should be portable i.e. It can run on different Hard ware and software platform.

Stages of Program Development Process

A program development process is a step by step process where each stag contributes to building of an effective and efficient program.

1. Analysis: This phase involves the following steps: You must recognize the need of program. Try to explore ‘WHAT’ component in the problem After determining the need, carefully analyze the problem to get an effective solution. Try to

explore the inputs to get required output.

2. Design: This phase involves planning of step-by-step procedures required to solve a given problem. At this stage a detailed design of the following components is to be completed: Inputs: involves defining the data type of data items to be entered by the user into the

application. In this stage we should also decide on the type of input components to minimize ambiguity and inconsistency.

Outputs: decide on the possible data to be displayed from (reports) the application and also how, where and when it is to be displayed.

User Interface (Forms): involves designing of the screen the user will see and use to enter data or display data. The placement of various input-output components on the form in an aesthetic and visually appealing manner is a major step in this phase.

Process design: involves breaking of complex steps into simple ones to attain the target. Depending on the user interface this step will involve deciding on the functionality required from each component placed on the form to obtain the desired output. The program is divided into smaller components called module. Each programming module handles a specific task.

Database Design: involves creating database and its table which to be used for storing user input in the form of records. Database plays very important role in the application, it should be designed carefully to avoid ambiguity and redundancy.

3. Coding: This phase involves actual writing of programs using appropriate programming languages. A good programmer will make an optimum code, which is readable, easy to understand and maintain with appropriate error handling, comments and indentation. For example, after designing the form, we wrote the actual code using java programming language.

4. Testing and Debugging: Virtually all applications may have some errors called 'bugs' and these need to be eliminated. Bugs

:: 40 ::

Page 41: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

can arise from errors in the logic of the program specification or errors in the programming code created by a programmer. Testing means the process of executing the application with possible set of input data in order to find probable errors (bugs). Debugging means correction of those errors in the application. In the testing and debugging stage, we should try out all possible inputs in order to make our application error free. There are various approaches for testing and application like functional, structural testing and integration testing.

5. Documentation: Documentation refers to written descriptions, design, code and comment, internal and external requirement to the program, which make a program more understandable, readable and more easily modifiable. A Documentation describe the who, what, when, how and where of the system or application. The documentation module (also called Manual) may be following types as per their contents. User Manual: Describes how to use the program and contains all the I/O screens and operating instruction for its user. Program Manual: It contains the Source code of the program for reference purpose. It is required during program Maintenance. System Manual: It contains overall specification, results of all the program development stages etc.

6. Maintenance: Program maintenance refers to the modification of a program, in order to meet changing requirements or to take care of undetected errors. The maintenance involves the rectification of previously undetected errors and changes that are to be made for the enhancement of the functionality of the application. An updated version of the software with the reported bugs corrected and enhancements is then sent as a replacement to the end user. The following types of Maintenance may occur in the application- Corrective Maintenance: It is required to correct the errors which were undetected during

the design of the program. Adaptive Maintenance: Change in user’s need or program environment may occur and

program must be changed to adapt such changes. This change in the program is called Adaptive Maintenance.

Preventive Maintenance: Sometimes you could anticipate the errors before they actually occur. Preventive Maintenance is carried out to avoid such errors.

Perfective Maintenance: To cope with changing world i.e. changes in the technology, you should tune your system to keep it up-to-date. Due to arrival of new technology and facilities, the program is updated to make it perfect in respect of new technological need.

Types of Errors

An error or bugs may occur while designing and testing of the application. These errors must be rectified before finalizing the application for the end-user. The following type of error may occur in the program- Compile Time Error: These types of errors occur during compile time. When a program compiles it sources code is checked for rules of programming language. These errors are easy to locate and rectify. Its types are:-

:: 41 ::

Page 42: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Syntax error: Formal set of rules defined for writing any statement in a language is known as syntax. Syntax errors occur when syntax rules of any programming language are violated. it occurs when a grammatical rule of Java is violated. Some of the common examples of syntax errors are spelling errors in keywords, missing semicolon, missing parenthesis and using incompatible data types.

Semantic error: Semantic occurs when statement are not meaningful and ambiguous for compiler. For example if you are writing an expression x+y=z instead of z=x+y , then Semantic error occurs. This error is also located by the compiler.

Run time errors: If an application is syntactically correct then it is compiled and is ready to be executed. Run time errors occur during the execution of an application. These errors will result in abnormal termination of the application. Some common examples of runtime errors are Division by zero, trying to convert to number (int or double) from an empty jTextField etc. Run time errors are also called exceptions, and handling such errors in the application is called exception handling. In java exception handling is done using try{ } and catch{ } blocks. Logical errors: In case the application is not giving any compilation or runtime error but still giving a incorrect output, it is due to logical errors. These Errors occur due to mistakes in the logic. They are the most difficult errors to find and debug. One such common example of logical error is using a wrong formula as Eng+Maths+GK/3 instead of (Eng+Maths+GK)/3 for calculating average of 3 subject marks.

:: 42 ::

Page 43: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT 2 : Questions & Answers 1. Which window is used to design the form in Netbeans IDE?. Ans: Design window 2. Which window contains the Swing Controls components. Ans: Palette window 3. What is the most suitable component to accept multiline text. Ans : Text Area 4. What will be the output of the following command? Learning.concat("Java") Ans : Error 5. What will be the output of the following command? "Learning".concat("Java") Ans: LearningJava 6. Name any two commonly used method of ListBox. Ans: getSelectedIndex() and getSelectedValue() 7. Describe the three common controls. Also give some of their properties. Ans:

(i) jButton text, icon (ii) jLabel text, border (iii) jTextField text, font

8. How would you make a combo box editable. Ans: By setting its editable property to false. 9. What is the name of event listener interface for action events? Ans: ActionPerformed 10. Which method is used to retrieve password string from jPassword control? Ans : .getPassword() 11. What is event driven programming? Ans: This programming style responds to the user events and is driven by the occurrence of user events. 12. What are containers? Give examples. Ans: Containers are those controls inside them other controls are placed. e.g., frame (JFrame), Panel (JPanel) etc. are containers. 13. Which keyword is used to make a variable as constant? Ans: final 14. What will be the output of the following code segment:

String firstName = "Johua "; String lastName = "Yacomo"; String fullName = firstName + lastName; jTextField1.setText("Full Name: " +fullName);

Ans: Full Name: JohuaYacomo 15. Which expression is used to print the value of a variable "x" of type int. Ans: jTextField1.setText("x = " + x); 16. The statement i++; is equivalent to Ans : i=i+1; 17. Name the primitives data types in java. Ans: byte, short, int, long, float, double, Boolean, char 18. Which events gets fired when a user click a JButton and JRadioButton. Ans: ActionPerformed 19. Which of the following is a selection construct ?

(1) do while Loop (2) for Loop (3) while Loop (4) None of these Ans: none of these 20. What will be used if there are two or more possible options.

:: 43 ::

Page 44: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Ans: is.. else.. if and switch 21. Which braces is used to enclose statements in a block statement. Ans: { } Curly braces 22. Which of the following is an exit controlled loop? a. for loop b. do while Loop c. while loop d. none of these Ans: do while loop 23. 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: List and combo box

Short answers type questions

1. Explain the following terms: (a) IDE (b) Form

Ans: a) IDE : IDE is an acronym for Integrated Development Environment which is a work environment that integrates all tools necessary for Application Development and makes them available as part of one environment. b) Forms: Forms are used to accept data (input) and submit data to an external agent for processing. 2. Explain the usage of the following methods:

(a) setText() (b) toString() (c) concat() Ans:

a)setText() : It is used to change the display text of a component (label, text field or button) during run time.

b)toString() : It is used to convert an Integer value to String type. c) concat() : The concat() method or the string concatenation symbol(+) may be used to add two

strings together. 3. Differentiate between:

A. Text field and Text area components : B. Text field and Password field components: C. parseInt() and parseDouble() methods:

Ans: A. The Text Field allows the user to enter a single line of text only. But Text Area component allows

multiline input from the user or displaying multiple lines of information. B. The Text Field displays the obtained text in unencrypted form whereas password field displays

the obtained text in encrypted form. C. parseInt() is used to convert a string value to Integer type whereas parseDouble() is used to

convert a string value to type Double. 4. What is a Variable? Ans: Variables are named temporary storage locations. 5. Why are data types? Ans: Data Types define the way the values are stored, the range of the values and the operations that can be performed on that type. 6. How are keywords different from variable names? Ans: Keywords have special meaning in java, should not be used as the variable names. Variables are named temporary storage locations. 7. 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. 8. What is casting? When do we need it? Ans: Casting is a type of data conversion, which uses the type 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. 9. What is the purpose of break statement in a loop?

:: 44 ::

Page 45: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Ans: In a loop, the break statement terminates the loop when it gets executed. 10. Is Java case sensitive? What is meant by case sensitive? Ans: Yes, java is case sensitive. Case sensitive means upper case letters and lower case letters are treated differently. 11. What is the main difference between a combo box and a list box? Ans: The List Box does not have a text field the user can use to edit the selected item, whereas a Combo Box is a combination of a text field and a list. 12. Explain the use of for statement along with its syntax. Ans: The for loop repeats a set of statements till a test condition is satisfied. The syntax of the for loop is:

for( initialization; test exp; increment/decrement exp) { statements; }

13. What is the purpose of if statement? Name the different forms of if statement. Ans: The if statement allows selection (decision making) depending upon the outcome of a condition.

a) simple if b) if else c) if - else if – else

14. What is the purpose of default clause in a switch statement? Ans: The default statement gets executed when no match is found in switch. 7. What is the main difference between a while loop and a do while loop? Ans: In while loop test expression is evaluated at the beginning of the loop whereas in do while loop the test expression is evaluated at the bottom of the loop. This means that do-while loop is executed at least once. 15. 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. Also switch statement does not allow to use of any operator. The if…else if combination allows any kind of condition after each if. 16. Differentiate between compile time and run time errors. Ans: Compile time errors refer to the errors that violate the grammatical rules and regulations of programming language. 17. Which error is harder to locate and why? Ans: Logical errors because in presence of logical error , the program executes without any problems but the output produced is not correct. Therefore every statement of the program need to be scanned. 18. Explain the following terms:

(a) Exception handling (b) Syntax (c) Portability (d) Pretty typing (e) Syntax error (a) Exception handling: Run time errors are also called exceptions, and handling such errors in the

application is called exception handling. (b) Syntax: Formal set of rules defined for writing any statement in a language is known as syntax. (c) Portability: The application should be portable. It should be able to run on different platforms. (d) Prettytyping: Pretty typing refers the formatting of a program to make it more readable. These

formatting conventions usually consist of changes in positioning, spacing, color, contrast, size and similar modifications intended to make the content easier to view, read and understand.

(e) Syntax error: Syntax errors occur when syntax rules of any programming language are violated. These errors occur during compilation of the application.

19. What are the characteristics of a good program? Ans: The characteristics of a good program are-

1. The program should be efficient in terms of execution speed and effective memory utilization. 2. The program should be accurate. It should produce correct result.

:: 45 ::

Page 46: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

3. The program should user friendly. It means meaningful names should be given to variable, proper messages should be given, use of comments and indentation.

4. The program must be reliable that is it should be able to handle the situation when the wrong inputs are given.

5. The program should be portable so that it can run on different platforms without doing any changes.

20. What is the use of comments and indentation? Ans: Comments are non executable statements and are used for internal documentation purpose. In Java comments are given either by // or /* ….*/ brackets. Example-

/* This method calculates sum of two numbers.*/ int Sum( int x, int y)// x,y are formal parameters { return (x+y); }

Indentation makes a program readable and understandable. When you are writing a program you must remember that-

• The opening braces should properly match with closing braces. • Spaces should be inserted between operator and operands in an expression.

Output Finding Questions

1. Write the output : (i) jTextField1.setText(“Hello”.charAt(3)); (ii) jTextField1.setText(“Good morning”.substring(4));

Ans: (i) l (ii) morning

2. Write the output of the following code : int x , y = 0;

for(x=1;x<=5;++x) y = x++;

Ans: 7 3. Find the output of the code:

int f=1,i=2; do { f*=i; }while(++i<5); jTextField1.setText (“”+f);

Ans: 24

4. What will be the value of j and k after execution of the following code: int j=10,k=12; if(k>=j) {k=j; J=k; }

Ans: 10 10 5. How many times, the following loop gets executed?

i=0; while (i> 20) {//Statements }

Ans: 0 times 6. How many times, the following loop gets executed?

:: 46 ::

Page 47: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

i=0; do { //Statements }while (i> 20);

Ans: 1 time 7. What will be the contents of jTextield after executing the following statement:

int num=4; num=num+1; if(num>5)

jTextField1.setText(Integer.toString(num)); else

jTextField1.setText(Integer.toString(num*4)); Ans : 20

8. Find the output of the following code: int First = 7; int Second = 73; First++;

if (First+Second> 90) jlabel1.setText("value is 90 "); else

jlabel1.setText("value is not 90 "); Ans : value is not 90

9. Find the output int Number1 = 7,Number2=8; int Second = 73; if (Number1>0 || Number2>5) if (Number1>7)

jTextField1.setText("Code Worked"); else

jTextField1.setText("Code MightWork"); else

jTextField1.setText("Code will not Work"); Ans : Code MightWork

10. How many times will the following loop get executed? int x = 5, y = 36; while ( x <= y) { x+=6; }

Ans: 6 11. What will be the content of the jTextArea1 after executing the following code?

int Num = 1; do { jTextArea1.setText(Integer.toString(++Num) + "\n"); Num = Num + 1; }while(Num<=10);

Ans: 10

12. What will be the contents of jTextfield1 and jTextfield2 after executing the following code: String s=”KENDRIYA VIDYALAYA SANGATHAN”

jtextfield1.setText(s.length()+” “); jtextfield2.setText(Math.round(2.34)+“”);

Ans : 28 2

13. Give the value of x after executing following Java code.

:: 47 ::

Page 48: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

int a=10, b=12, x=5, y=6; while (a<=b)

{ if (a%2= =0) x=x + y;

else x=x-y;

a=a+1; }

Ans:11 14. What will be the output produced by following code fragment?

flaot x=9, y=5; int z=(int)(x/y); switch(z)

{ case1: x=x+2; case2: x=x+3; default: x =x+1; } System.out.println(“value of x:”+x);

Ans: value of x: 15 15. What will be the contents of jTextField1 and jTextField2 after executing the following

code: String s = “Sun Micro Systems”; jTextField1.setText(s.length()+””); jTextField2.setText(s.toLowerCase());

Ans: jTextField1 : 17 jTextField2 : sun micro systems

16. What values will be assigned to the variable ua ,ub, uc and fail after execution of the

following program segment: int i=0,ua=0,ub=0,uc=0,fail=0; while(i<=5) { switch ( i++ ) { case 1 :++ua;

case 2 : ++ub; uc++; break;

case 3 : case 4 : ++uc; ua++;

ub++; break;

default : ++fail; }

Ans: ua=1 ub=1 uc=0 17. Give the output of the following code:

int m=100; while(m>0) { if (m<10) break; m=m-10; }

System.out.println(“m is “+m); Ans: m is 0

18. How many times the loop will be executed? for (;;) { statement }

Ans: Infinite time

:: 48 ::

Page 49: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Errors finding and conversion questions:

1. The following code has some errors. Rewrite the corrected code .

int i=2, j=5; while j>i { jTextField1.getText(“j is greater”); j--; ++i; } JOptionPane.ShowMessageDialog(“Hello”);

Ans: int i=2,j=5; while( j>i) { jTextField1.getText(“j is greater”); j--; ++i; } JOptionPane.showMessageDialog(“Hello”);

2. Rewrite the code after making correction.

int sum; value; inct; int i for(i==0;i<=10;i++) sum=sum+i; inct++;

Ans : int sum, value, inct; for(int i=0;i<=10;i++) sum=sum+i; inct++;

3. The following code has some error(s). Rewrite the correct code.

int y=3; switch(y); { case 1: System.out.print(“Yes its One”); case>2: System.out.println(“Yes its more than Two”);

break; case else: System.out.print(“Invalid Number): }

Ans: int y=3; switch(y) { case 1: System.out.print(“Yes its One”); break; case 2: System.out.println(“Yes its more than Two”); break; default: System.out.print(“Invalid Number); }

4. Find out errors and rewrite the code:

M=1; N=0; For(;m+n<19;++n) System.out.println(“hello”); M=m+10;

Ans: m=1; n=0; for(;m+n<19;++n) System.out.println(“hello”); m=m+10;

5. Rewrite the following program code using a for loop:

int i,sum=0;

:: 49 ::

Page 50: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

while(i<10) { sum +=i; i+=2; }

Ans:

int i, sum=0; for(i=0;i<10;i+=2) { sum +=i; }

6. Rewrite the following code using while loop :

int i,j;

for(i=1;i<=4;i++) { for(j=1;j<=i;++j)

{ System.out.print(j); } System.out.println(); }

Ans: int i=1, j=0;

while(i<=4)

{ j=1; while(j<=i)

{ System.out.print(j); ++j;

} i++; System.out.println(); }

7. Rewrite the following if-else segment using switch-case statement.

char ch='A'; if(ch=='A') System.out.println("Account");

if((ch=='C') || (ch=='G')) System.out.println("Admin");

if(ch=='F') System.out.println("Advisor"); Ans: char ch='A';

switch(ch) { case ‘A': System.out.println("Account"); break; case 'C': case 'G’: System.out.println("Admin"); break; case 'F': System.out.println("Advisor");

}

8. Rewrite the following code using while loop:

int i,j; for(i=1,j=2;i<=6;i++,j+=2) System.out.println(i++); System.out.println(“Finished!!!”);

:: 50 ::

Page 51: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Ans: inti=1,j=2; while(i<=6)

{System.out.println(i++); i++;

j+=2;} System.out.println(“Finished!!!”);

9. Rewrite the following code using for loop.

int i=0; while(++i<20) { if( i==8)

break; System.out.println(i++);

} Ans:

int i;

for (i=1;i<20;++i) { if( i==8) break;

System.out.println(i++); }

10. Write the equivalent switch case for the following code :

If (num1 = =1 ) jTextField1.setText(“Number is one”); else If (num1 = =2 ) jTextField1.setText(“Number is two”);

else If (num1 = =3 ) jTextField1.setText(“Number is three”); else

jTextField1.setText(“Number is more than three”); Ans:

Switch(num1) { Case 1 : jTextField1.setText(“Number is one”); break; case 2 : jTextField1.setText(“Number is two”); break; case 3 : jTextField1.setText(“Number is three”); break; default: jTextField1.setText(“Number is more than three”); }

11. Write an alternative code (Using if) of given code that saves on number of comparisons .

If(a==0) System.out.println(“zero”); If(a==1) System.out.println(“one”); If(a==2) System.out.println(“two”); If(a==3) System.out.println(“three”);

Ans: if(a==0) System.out.println(“zero”);

else if(a==1) System.out.println(“one”); else if(a==2) System.out.println(“two”);

else if(a==3) System.out.println(“three”);

:: 51 ::

Page 52: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Application Design Questions:

Q1: Design an application for Theatre Booking system. And answers the following questions?

A. When the user select different seat type, then its price should be displayed in the Label.

B. If the user enters an invalid no of seats i.e. less than 1, then an error message should be displayed in the dialog box.

C. When the user click at the Book Seats button , then total amount (calculated as no. of seats x price per seat) should be displayed along with payment method, next to the push button.

Price per seat depend upon the seat type : Stall 625/-

Circle 750/- Upper Circle 850/- Box 1000/-

Ans: (a) if(jRadioButton1.isSelected()==true)

jLabel2.setText(“625”); if(jRadioButton2.isSelected()==true) jLabel2.setText(“750”); if(jRadioButton3.isSelected()==true)

jLabel2.setText(“850”); if(jRadioButton4.isSelected()==true)

jLabel2.setText(“1000”);

(b) int s=Integer.parseInt(jTextField1.getText()); if(s<1) JOptionPAne.showMessageDialog(null,”Error”);

(c) int s=Integer.parseInt(jTextField1.getText()); int p=Integer.parseInt(jLabel2.getText()); int tp=s*p; if(jRadioButton5.isSelected()==true)

jLabel5.setText(“Cash Payment of “ +tp); if(jRadioButton6.isSelected()==true)

jLabel5.setText(“Visa Payment of “ +tp); if(jRadioButton7.isSelected()==true)

jLabel5.setText(“American Exress Payment of “ +tp); if(jRadioButton8.isSelected()==true)

jLabel5.setText(“Master Card Payment of “ +tp);

:: 52 ::

Page 53: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q2 : Design the following application and answer the questions that follow :

(a) Write the code for the Clear button to clear all the textfields and checkbox. Set the default choice in

the radio button as Fixed Deposit.

(b) Write the code for the calculate button to calculate compound interest and amount and display the values in the txtInterest and txtAmount depending on principal, rate and time.

Rate is calculated based on the time according to the following table:

Account Time Rate Fixed Deposit <= 1 10%

>1 and <=5 12% >5 15%

Recurring Deposit <= 2 11% >2 and <=7 12% >7 15%

An additional rate of 2% is given to the senior citizens i.e. if the Senior citizen (chkSR checkbox) is checked. Ans:

(a) jTextField1.setText(“”); jTextField2.setText(“”); jTextField3.setText(“”); jRadioButton1.setSelected(true); jCheckBox1.setSelected(false);

(b) int p= Integer.parseInt(jTextField1.getText()); int t= Integer.parseInt(jTextField2.getText()); int r=0; if(jRadioButton1.isSelected()) { if(t<=1)

r=10; else if(t>1 && t<=5) r=12;

else r=15; }

else { if(t<=2)

r=11; else if(t>2 && t<=7)

r=12; else

r=15; } float ci= p*Math.pow((1+(r/100)),t); float amt= p+ci; txtInterest.setText(“”+ci); txtAmount.setText(“”+amt);

:: 53 ::

Page 54: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q 3: Consider the following application and answers the following questions:

The grading criteria for the two streams are given below:

Stream Percentage Grade Medical >=80

60-80 <60

A BC

Non-Medical >=75

50-75 <50

A B C

A. Write code for Calculate Percentage button to calculate the Percentage after finding the total marks of I term and II term . Also ensure that NCC cadet gets an increment of 3% in their percentages.

B. Write code for Calculate grade button to calculate the grade depending upon on the stream selected according to the given criteria.

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

int s= Integer.parseInt(jTextField2.getText()); int tot = f+s; float p= tot/2; if(jCheckBox1.isSelected())

p=p+3; jLabelp.setText(“”+p); ( b) String g; if(jRadioButton1.isSelected())

{ if(p>=80) g=”A”; else if(p>=60 &p<80)

g=”B”; else

g=”C”; }

else { if(p>=75) g=”A”; else if(p>=50 &p<75)

g=”B”; else

g=”C”; } jLabelp.setText(“”+p); jLabelg.setText(“”+g);

:: 54 ::

Page 55: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q 4: Mr. Madhav works in a construction company. To calculate total wages he has developed the

following GUI in NetBeans.

Male and female workers are respectively paid Rs. 150/- per day and Rs. 170/- per day. Skilled workers are paid extra at the rate of Rs. 100/- day. Male and female workers from rural areas are paid 10% less per day.

a. When Calculate Wage button is clicked, the total wages is calculated as per the given criteria

and displayed in total wage text box. b. When Clear button is clicked, all the text boxes should be cleared and radio button, check box

should be deselected. c. Close the application when Quit button is pressed.

Ans:

(a) int w=0; int d =Integer.parseInt(jTextField2.setText()); if(jRadioButton1.isSelected()) w=150;

else w=170;

if(jCheckBox1.isSelected()) w=w+100; if(jRadioButton3.isSelected()) w=w-(w*10)/100;

int cw=d*w; jLabel6.setText(“”+cw);

(b) jTextField1.setText(“”);

jTextField2.setText(“”); jRadioButton1.setSelected(false); jRadioButton2.setSelected(false); jRadioButton3.setSelected(false); jRadioButton4.setSelected(false); jCheckBox.setSelected(flase);

(c) System.exit(0);

:: 55 ::

Page 56: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q 5: Mr. JigneshDesai an owner of Alpha Chemicals PVT ltd has asked his programmer Sweta to

develop the following GUI application in Netbeans:

Service Charges Rates are as follows:

Class of City Rate of Service Charges i 10% of sales price ii 15% of sales price iii 20% of sales price

Write java code for the following:

a. To calculate service charges depending on the selection of radio button. This code will execute after click on the calculate service charges?

b. To calculate net price when Calculate Net price button will be clicked. c. When exit button will be clicked application should be automatically closed.

Ans:

(a) float q=Float.parseFloat(jTextField2.getText());

float p=Float.parseFloat(jTextField3.getText());

float sp=q*p; jLabelsp.setText(“”+sp); float sc; if(jRadioButton1.isSelected())

sc=(10*sp)/100; else if(jRadioButton2.isSelected()) sc=(15*sp)/100; else

sc=(20*sp)/100; jLabelsc.setText(“”+sc);

(b) float sp=Float.parseFloat(jLabelsp.getText());

float sc=Float.parseFloat(jLabelsc.getText()); float np=sp+sc; jLabelnp.setText(“”+np);

(c) System.exit(0);

:: 56 ::

Page 57: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT -3 Relational Database Management System

Chapter 8: Introduction to RDBMS & MySQL

What is Data? Raw facts and figures about something which is not organized are called data. For example details of some students which is not organized.

What is Database? A well organized collection of inter related data that ensures safety, security and integrity of data. It works like a container which contains the various object like Tables, Queries, Reports, Procedures in organized way.

Database Management System (DBMS) Software that provides the essential services to create, storing, maintain and utilize the databases in efficient way. In short a DBMS provides the means to store the data in the database, to edit or delete the data stored, to search and analyze the data in the database. They also provide various safety and security mechanisms that ensures that in any case stored data will be safe and accessible. Example of DBMS software are Oracle, MS SQL Server, MS Access, Paradox, DB2 and MySQL etc.

Advantages of Data Base System: Databases reduces Redundancy

Database removes duplication of data because data are kept at one place and all the application refers to the centrally maintained database.

Database controls Inconsistency When two copies of the same data do not agree to each other, then it is called Inconsistency. By controlling redundancy, the inconsistency is also controlled.

Database facilitate Sharing of Data Data stored in the database can be shared among several users.

Database ensures Security Data are protected against accidental or intentional disclosure to unauthorized person or unauthorized modification.

Database maintains Integrity It enforces certain integrity rules to insure the validity or correctness of data. For example a date can’t be entered like 25/25/2000.

Basics of Relational Model:

Relation/Table : Relational Databases store data or information in tables. A table or Relation is similar to a spreadsheet where data is stored in rows and columns. A table refers to a two dimensional representation of data using rows and columns.

Atomicity : Each column assigned a unique name and must have atomic (indivisible) value i.e. a value that can not be further subdivided.

No duplicity: No two rows of relation will be identical i.e. in any two rows value in at least one column must be different.

All items in a column are homogeneous i.e. same data type.

Ordering of rows and column is immaterial. Tuple/Entity/Record :

A row in a relation is called a tuple or entity. Attribute/Field:

A column in a relation is called an attribute or field Domain : Domain of an attribute refers to the set of all the possible values for that attribute.

:: 57 ::

Page 58: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Degree : Number of attributes or columns in a relation is called degree of the relation.

Cardinality : Number of tuples or records in a relation is called cardinality of relation.

Concept of Keys:

Primary Key:

A primary key is a column in a table that is unique for each record. Every table in a database should have a column or a group of columns designated as the primary key. The value this key holds should be unique for each record in the table. Some more examples of Primary key are: Admission Number in student table of School, Accession Number of a Book in the Book table, Employee ID of an employee in the Employee Table, Item Code of an item in the Stock table etc.

Candidate Key:

Some time there may be more than one field that uniquely identifies a record in a table. All such fields are called candidate keys because they all are having candidature to work as key. A Candidate key is an attribute (or set of attributes) that also uniquely identifies a row. A Primary Key is one of the candidate keys. A table may have more than one candidate keys but definitely has one and only one primary key.

Alternate Key:

All candidate keys that not chosen as primary key are called alternate keys. Only one of the Candidate keys is selected as the primary key of a table. All other candidate keys are called Alternate keys.

Foreign Key:

A non-key attribute whose values are derived from the primary key of some other table is called Foreign key. Foreign Key is used to implement Referential Integrity in the Database. It establishes relationship among two tables. Example: Consider the following Student Table, RollNo and Admission_no both may be used to uniquely identify each row in the Table, so both are candidate keys.

Admission_No RollNo Name Class Marks 2301 1 Seema Chauhan 11 23 1501 2 Ajay Kumar 11 15 1678 3 Vansh Pratap 11 20 7003 4 Manohar Lal 11 15

So Candidate Keys are - RollNo and Admission_no Pramary Key - Admission_No and Alternate Key – RollNo or vice-versa.

INTRODUCTION TO MYSQL

The software required to manipulate relational databases is known as Relational Database Management System (RDBMS) . Popular RDBMSs include MySQL, Oracle, Sybase, DB2, MS SQL Server. MySQL is an Open Source RDBMS Software that uses Structured Query Language. It was developed by Michael Widenius and AKA Monty. Features of MySQL :

1. Open Source and available at free of cost. 2. Fast and Reliable. 3. Supports SQL (Structured Query Language), standardized by ANSI . 4. Portable and secure. 5. Can be used with various programming languages and platform.

:: 58 ::

Page 59: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Chapter 9: Working with MySQL The Structured Query Language (SQL) SQL (pronounced SEQUEL) is Non-procedural query language used to access and manipulate data stored in the database. SQL standards are defined by ANSI (American N a t i o n a l Standards Institute). MySQL is an Open Source RDBMS Software that uses Structured Query Language. SQL also works with other RDBMS like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc.

Types of SQL Commands

SQL commands can be classified into the following: Data Definition Language (DDL): They are used to create tables, databases, identify data items, and provide unique names to the data items. Example of DDL commands are –

CREATE – This command used to create a database and table. ALTER TABLE – This command is used to add/Delete/Modifying columns of a table. DROP TABLE- This command is used to delete whole table and database.

Data Manipulation Language (DML): The data manipulation language (DML) commands are used to manipulate stored data e.g. operations such as entering rows into a table, changing data, deleting rows, and extracting data from rows and tables. It contains commands like-

SELECT- This command is used to read/fetch records from the tables. INSERT- This command is used to insert record in a table. UPDATE- This command is used to modify the value of columns for given crieria. DELETE- This command is used to delete record as per given condition.

Transaction Control Language (TCL): A transaction is a one complete unit of work. To manage and control the transactions, the transaction control commands are used. e.g.

COMMIT- This command saves changes in the database. ROLLBACK- This command cancels (undo) modifications from the database. SAVEPOINT- This command is used to create a flag in a transaction, used for partial rollback.

Data Types in MySQL:

Every column in a table should belong to a unique domain (known as data type). These data types help to describe the kind of information a particular column holds. MySQL supports the ANSI SQL data types. Some of the commonly used data types along with their characteristics are as follows: Numeric Data Types:

INTEGER or INT – up to 11 digit number without decimal. SMALLINT – up to 5 digit number without decimal. DECIMAL(M,D) – Unpacked floating point up to M length and D decimal places.

Date & Time Data Types: DATE - A date in YYYY-MM-DD format. TIME - Stores time in HH:MM:SS format. DATETIME – A date and time format like YYYY-MM-DD HH:MM:SS

String or Text Data Type: CHAR(Size) - A fixed length string up to 255 characters.(default is 1) VARCHAR(Size) – A variable length string up to 255 characters.

WORKING WITH MySQL Commands

To work on MySQL , you need to open or create the database first:

Creating and Opening Database: CREATE DATABASE <name of database>; Example: mysql> create database School;

Now the database with the given name will be created. To open database give following command: mysql> use School;

:: 59 ::

Page 60: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Creating Tables Tables are defined with the CREATE TABLE command. When tables are created its columns are named, data types and sizes supplied for each column. At least one column must be specified.

Syntax: CREATE TABLE <TableName>(<ColumnName1> <Data Type1>, <ColumnName2> <Data Type2>,….. ….,<ColumnNameN> <Data Type N>); Example: mysql> CREATE TABLE Students(RollNo INTEGER(3), Name VARCHAR(25));

Once the table is created we can insert the record in it, edit or delete existing records, and also we can search for desired record in a very comprehensive way using the SQL Select statement.

Creating tables with Constraints : A Constraint is a condition or check applicable to a column or table which ensures the integrity or validity of data. Constraints are also called Integrity constraints. The following constraints are commonly used in MySQL.

Constraints name Description PRIMARY KEY Used to create a primary key UNIQUE to create a unique key NOT NULL to define that column will not accept null values. DEFAULT to define the columns default value. CHECK to define the custom rule or condition.

Not Null and Default constraints can be applied only at column level rest all constraints can be applied on both column level and table levels.

A table may have multiple UNIQUE constraints but only one PRIMARY KEY is allowed. Example:

CREATE TABLE Student (StCode char(3) NOT NULL PRIMARY KEY, Stname char(20) NOT NULL, StAdd varchar(40), AdmNo char(5) UNIQUE, StSex char(1) DEFAULT ‘M’, StAge integer CHECK (StAge>=10), Stream char(1) CHECK Stream IN (‘S’, ‘C’, ‘A’) );

Inserting the record in the table The INSERT INTO command appends a new record to an existing table and initializes it to desired values.

Syntax: INSERT INTO table_name (column_name [,column_name]) VALUES (value [,value]);

Example: INSERT INTO Student (RollNo,Name) VALUES (12333,’Anu’);

Inserting NULL Values: INSERT INTO Student (RollNo,Name, Class, Grade) VALUES (12333,’Anu’,11, NULL);

Inserting Dates: INSERT INTO Student (RollNo,Name, Class, DOB) VALUES (12333,’Anu’,11, ‘1998-02-24’)

Inserting Data from another Table: INSERT INTO Marks SELECT * FROM Student WHERE Class>10;

Deleting Existing records from the table : The DELETE command deletes one, many, or even all records in a table, depending on the conditions that you specify.

Syntax: DELETE FROM tablename WHERE search_conditions;

Example DELETE FROM Students WHERE RollNo>11255;

If DELETE command is executed without conditions, it will delete ALL records in a table.

:: 60 ::

Page 61: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

For instance, DELETE FROM Students; Will delete all records from Students table.

Modifying (Updating) the contents of records : The UPDATE command changes one, many, or even all records in a table, depending on the conditions that you specify

Syntax: UPDATE tablename SET column_name = expression [,column_name = expression..] [WHERE search_conditions];

Example: UPDATE customer SET f_name = ‘Thomas’ WHERE Code = ‘E123’; UPDATE loan SET rate = rate + 1.5; UPDATE Item SET Price = Price + (Price*10/100);

Selecting (Displaying) records from the table : MySQL SELECT statement is a comprehensive statement used to search/select records from one or more tables. All the analysis done on a database usually involves some form of select statement. Choosing all fields (columns) : Use a asterisk (*) to indicate all fields with the select statement:

SELECT * FROM table_name; SELECT * FROM customer;

Choosing a selected list of fields (columns) SELECT column_name [,column_name] FROM table_name; SELECT Name, City, date_of_birth FROM customer;

The order in which you list the columns affects their order in the resulting output. Temporarily renaming columns in query results

SELECT column_heading AS column_name FROM table_name; SELECT Sal*12 as “Annual Salary” FROM employee;

Including calculated columns in the results SELECT date_due, rate, principal, rate * principal FROM loan;

Eliminating duplicate query results with distinct If you use the keyword distinct after the keyword SELECT, you will only get unique rows. SELECT rate, FROM loan;

(above will display all rate values might be repeated) SELECT distinct rate FROM loan;

(above will display only unique rate values, no repetition) Selecting from all the rows:

SELECT ALL rate, FROM loan; ( query will display all rate values) Selecting rows (using conditions): WHERE clause is used to specify the condition for searching. Only those records will be retrieved that satisfy condition given with where clause.

SELECT Column_list FROM table_list WHERE search_conditions; SELECT * FROM customer WHERE City= ‘Dehradun’;

Possible Search Conditions may be- Comparison operators (=,<,>,!=.<>,<=,>=)

SELECT * FROM loan WHERE principal > 100000; Ranges (between and not between; inclusive)

SELECT * FROM Student WHERE age BETWEEN 15 AND 20; OR SELECT * FROM Student WHERE age NOT BETWEEN 15 AND 20; Lists (in and not in) SELECT * from Customer WHERE city IN (‘Delhi’,’Mumbai’,’Chennai’); SELECT * from Customer where city NOT IN (‘Delhi’,’Mumbai’,’Chennai’);

:: 61 ::

Page 62: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Null values SELECT * from Customer where city is Null; SELECT * from Customer where city is Not Null;

Character Pattern matchings (like and not like) SELECT Name FROM customer WHERE Name LIKE ‘A%’; SELECT Name FROM customer WHERE Name LIKE ‘%Kumar%’; SELECT City FROM customer WHERE City LIKE ‘_D%’;

“%” (matches any string of zero or more characters) and “_” (matches any one character). SELECT name, city FROM customer WHERE name LIKE ‘A%’ AND City NOT IN (‘Mumbai’,‘Delhi’)

Some more examples of patterns: ‘Am%’ matches any string starting with Am. ‘%Singh%’ matches any string containing ‘Singh’ ‘%a’ matches any string ending with ‘a’ ‘_ _ _’ matches any string that is exactly 3 characters long. ‘_ _ %’ matches any string that has at least 2 characters long. ‘_ _ _g’ matches any string that is 4 characters along with 3 characters in the beginning but ‘g’ as the

4th character.

Sorting records The output of a SELECT query can be sorted in ascending or descending order on one or more columns, the default is ascending. This is important to note that the data in table is not sorted, only the results that appear on the screen are sorted.

Syntax: SELECT <column name> [,<column name>, ….] FROM <table name> [WHERE <condition>] [ORDER BY <column name> [, <column name>…]];

Example: (Sorting on single column) SELECT * FROM EMPL ORDER BY ENAME;

Example : (Sorting on Multiple columns) SELECT * FROM EMPL ORDER BY ENAME, JOB;

Modifying Table Structure: The ALTER TABLE command is used to change definitions of existing tables. It can add columns, delete columns or change their size. Adding a column: Syntax:

ALTER TABLE <table name> ADD (<column name> <data type with size> <constraints>); Example:

ALTER TABLE Students ADD (Age INTEGER (2)); Modify a column:

Syntax : ALTER TABLE <table name> MODIFY ( column name newdatatype (newsize));

Example: ALTER TABLE Students MODIFY (City Char(40));

Deleting Column : ALTER TABLE Students DROP COLUMN age ;

Removing Primary Key Constraints ALTER TABLE Students DROP primary key;

Deleting a table from the database: DROP TABLE <table name> ; DROP TABLE Students;

Viewing a tables structures Describe/ Desc statement is used to see the structure of a table:

Describe Student;

:: 62 ::

Page 63: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Chapter 10: MySQL Functions A function is special types of command that performs some operation and returns a single value as a result. It is similar to method or function in JAVA, which can be called by giving some argument. MySQL offers following types of functions-

Numeric Functions – Functions which accepts/returns only numeric data type. String Functions- Functions which accepts/returns only Text/Char data type. Date & Time Function- Functions which accepts/returns only Date data type. Aggregate Functions - Functions which works on whole column.

Numeric Functions

POWER() : Returns the argument raised to the specified power. POW () works the same way. Example:

POW(2,4): Result:16 POW(2,-2): Result:0.25 POW(-2,3): Result: -8

ROUND() : Rounds the argument to the zero decimal place, Where as ROUND(X,d) rounds the argument to d decimal places.

Example : ROUND(-1.23); Result: -1 ROUND(-1.58); Result: -2 ROUND(1.58); Result: 2 ROUND(3.798, 1); Result: 3.8 ROUND(1.298, 0); Result: 1 ROUND(23.298, -1); Result: 20

TRUNCATE() : Truncates the argument to specified number of decimal places. Example: TRUNCATE (7.29,1) Result: 7.2 TRUNCATE(27.29,-1) Result: 20

SIGN() : Returns sign of a given number.

Example : SIGN (15) Result : 1 SIGN (-15) Result : -1 SIGN (0) Result : 0.

SQRT() : Returns the square root of given number.

Example : SQRT (25) Result : 5

Character/String Functions

LENGTH() : Returns the length of a string in bytes/no.of characters in string.

Example: LENGTH(‘INFORMATICS’); Result:11

CHAR() : Returns the corresponding ASCII character for each integer passed.

Example : CHAR(65) ; Result : A

CONCAT(): Returns concatenated string i.e. it adds two strings.

Example : CONCAT(‘Informatics’,‘Practices’); Result : ‘Informatics Practices’

INSTR(): Returns the index of the first occurrence of substring.

Example : INSTR(‘Informatics’,’ mat’); Result : 6(since ‘m’ of ‘mat’ is at 6th place)

LOWER()/ LCASE(): Returns the argument after converting it in lowercase.

Example: LOWER(‘INFORMATICS’); Result : informatics

UPPER()/ UCASE(): Returns the argument after converting it in uppercase.

Example: UCASE(‘informatics’); Result : INFORMATICS

LEFT() : Returns the given number of characters by extracting them from the left side of the string :: 63 ::

Page 64: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Example : LEFT(‘INFORMATICS PRACTICES’, 3); Result : INF

RIGHT(): Returns the given number of characters by extracting them from the right side of the string.

Example : RIGHT(‘INFORMATICS PRACTICES’,3); Result : CES

MID(): Returns a substring starting from the specified position in a given string.

Example: MID(‘INFORMATICS PRACTICES’,3,4); Result : FORM

SUBSTR() : Returns a substring from a given string.

Example: SUBSTR(‘INFORMATICS’ , 3 , 4 ) ; Result : FORM

LTRIM() : Removes leading spaces.

Example : LTRIM(' INFORMATICS'); Result: 'INFORMATICS’

RTRIM(): Removes trailing spaces.

Example : RTRIM('INFORMATICS '); Result: 'INFORMATICS’

TRIM() : Removes leading and trailing spaces.

Example: TRIM(' INFORMATICS '); Result: 'INFORMATICS’

Date/Time Functions

Name Purpose Example

CURDATE() / CURRENT_DATE()

Returns the current date in YYYY-MM-DD format.

Select CURDATE();

NOW() Returns the current date & Time as YYYY-MM-DD HH:MM:SS

Select NOW();

SYSDATE() Returns the current date & Time as YYYY-MM-DD HH:MM:SS

Select SYSDATE();

DATE() Returns the date part of a date- time expression.

Select DATE(SYSDATE());

MONTH() YEAR()

Returns the Month/Year from given date argument.

Select MONTH(‘2012-10-02’);

DAYNAME() Returns the name of the weekday Select DAYNAME(CURDATE());

DAYOFMONTH() Returns the day of month (1-31). Select DAYOFMONTH(CURDATE());

DAYOFWEEK() Returns the day of week (1-7). Select DAYOFWEEK(CURDATE());

DAYOFYEAR() Returns the day of year(1-366). Select DAYOFYEAR(CURDATE());

:: 64 ::

Page 65: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT 3 : Questions & Answers Q1. What do you mean by a Database Management System? Ans:- DBMS is a collection of programs and files that allows a user to define structure of database, store

data into it, modify the structure and manipulate data. Apart from this it also provide security, transaction management and concurrency control.

Q2. What are the advantages of using a DBMS? Ans: Advantages of DBMS are:

1. Reduce data redundancy (duplication of data) 2. Control data inconsistency to a large extent 3. Database facilitate sharing of data 4. Enforce standards 5. Centralized databases can ensure data security.

Q3. What do you mean by Relational Data Model? Ans In this model data is organized into tabular structures called relations. A database may contain

many relations providing a better classification of data based on its nature and use. Multiple relations are then linked/ associated together on some common key data values (foreign key).

Q4. What is the foreign key? Ans: A column or a combination of columns whose values are derived from primary key of some other

table is called the foreign key of the table in which it is contained. Q5. What is MySQL?

Ans:- MySQL is an Open Source, fast and reliable RDBMS Software. Q6.What is SQL? Ans . SQL is Non-procedural universal data access language used to access and manipulate data stored in nearly all the data bases available currently. SQL standards are defined by ANSI (American National Standards Institute). SQL statements are used to retrieve and update data in a database. SQL works with database programs like MySQL, MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc. Q7. Differentiate between DDL and DML? Ans. Data Definition Language (DDL): This is a category of SQL commands. All the commands which are used to create, destroy, or restructure databases and tables come under this category. Examples of DDL commands are - CREATE, DROP, ALTER. Data Manipulation Language (DML): This is a category of SQL commands. All the commands which are used to manipulate data within tables come under this category. Examples of DML commands are - INSERT, UPDATE, DELETE. Q.8 What is a constraint? Ans : A constraints is a condition or check application on a field or set of fields. Example: NOT NULL (ensure that column con not have null value), CHECK (make sure that all value satisfy certain criteria), UNIQUE (ensure that all values in a column are different) etc. Q. 9 Compare CHAR and VARCHAR data types.

Ans. The CHAR data-type stores fixed length strings such that strings having length smaller than the field size are padded on the right with spaces before being stored. The VARCHAR on the other hand supports variable length strings and therefore stores strings smaller than the field size without modification.

Q.10 What are the differences between DELETE and DROP commands of SQL? Ans: DELETE is DML command while DROP is a DDL command. Delete is used to delete rows from a table while DROP is used to remove the entire table from the database.

Q 11. A table "Animals" in a database has 3 columns and 10 records. What is the degree and cardinality of this table? Ans: Degree 3 and Cardinality=10 Q.12. What are MySQL functions? Ans: A MySQL function is special types of command that performs some operation and returns a single value as a result. It is similar to method or function in JAVA.

Query Based question & answers

:: 65 ::

Page 66: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q1. Answer the question based on the table VOTER given below: Table : VOTER

Column Name Description V_id Voter identification Vname Name of the voter Age Age should not less than equal to 17 Address Address of voter Phone Phone number of the voter

(a) Write the command to delete all the rows of particular voter from the table voter where voter ID between 10 and 20.

Ans: Delete from VOTER where V_id between 10 and 20; (b) Delete the table physically. Ans: Drop table VOTER; Q2. Write MySql command to create a furniture table including all constraint.

Table: Furniture ITEMNO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT INT VARCHAR VARCHAR DATE INT INT 5 20 20 6 2 PRIMARY KEY NOT NULL DEFAULT ‘19/03/2010’

Ans:

CREATE TABLE FURNITURE (ITEMNO INT(5) PRIMARY KEY NOT NULL, ITEMNAME VARCHAR(20) NOT NULL, TYPE VARCHAR(20), DATE_STOCK DATE DEFAULT '2012/03/19', PRICE INT(6), DISCOUNT INT(2) );

Q3. Consider a database LOANS with the following table: Table: LOANS

AccNo Cust_Name Loan_Amount Instalments Int_Rate Start_Date Interest 1 R.K. Gupta 300000 36 12.00 19-07-2009 1200 2 S.P. Sharma 500000 48 10.00 22-03-2008 1800 3 K.P. Jain 300000 36 NULL 08-03-2007 1600 4 M.P. Yadav 800000 60 10.00 06-12-2008 2250 5 S.P. Sinha 200000 36 12.50 03-01-2010 4500 6 P. Sharma 700000 60 12.50 05-06-2008 3500 7 K.S. Dhall 500000 48 NULL 05-03-2008 3800 Answer the following questions.

Create Database and use it- 1. Create the database LOANS.

Mysql> Create Database LOANS; 2. Use the database LOANS.

Mysql> Use LOANS;

Create Table and Insert a record- 3. Create the table Loans and insert tuples in it.

Mysql>Create Table Loans (AccNo int primary key, Cust_Name varchar(30), Loan_Amount int, Installment int, Int_Rate number(5,3), Start_Date date, Interest number(7,2)); Mysql> Insert into Loans values (1,'R.K. GUPTA',300000,36,12.0.'2009-07-19');

:: 66 ::

Page 67: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Simple Select 4. Display the details of all the loans.

Mysql> Select * from Loans;

5. Display the AccNo, Cust_Name, and Loan_Amount of all the loans. Mysql> Select AccNo,Cust_Name,Loan_Amount from Loan_Acc;

Conditional Select using Where Clause 6 Display the details of all the loans with less than 40 instalments.

Mysql> Select * from Loans where Instalment <40;

7. Display the AccNo and Loan_Amount of all the loans started before 01-04-2009. Mysql> Select AccNo, Loan_Amount from Loans where Start_Date <'2009-04-01';

8. Display the Int_Rate of all the loans started after 01-04-2009. Mysql> Select Int_Rate from Loans where Start_date>'2009-04-01';

Using NULL

9. Display the details of all the loans whose rate of interest is NULL. Mysql> Select * from Loans where Int_rate is NULL;

10. Display the details of all the loans whose rate of interest is not NULL. Mysql> Select * from LOANS where Int_rate is not NULL;

Using DISTINCT Clause

11. Display the amounts of various loans from the table LOANS. A loan amount should appear

only once. Mysql> Select DISTINCT Loan_Amount from LOANS;

12. Display the number of installments of various loans from the table LOANS. An instalment should

appear only once.. Mysql> Select DISTINCT Instalment from LOANS;

Using Logical Operators (NOT, AND, OR)

13. Display the details of all the loans started after 31-12-2008 for which the number of instalments

are more than 36. Mysql> Select * from LOANS where Start_Date>'2008-12-31' and Instalment>36;

14. Display the Cust_Name and Loan_Amount for all the loans which do not have number of

instalments 36. Mysql> Select Cust_Name, Loan_Amount from LOANS where Instalment <>36;

15. Display the Cust_Name and Loan_Amount for all the loans for which the loan amount is less than

500000 or int_rate is more than 12. Mysql> Select Cust_Name, Loan_Amount from LOANS

where Loan_Amount <500000 or Int_rate>12;

16. Display the details of all the loans which started in the year 2009. Mysql> Select * from LOANS where Year(Start_Date)=2009;

17. Display the details of all the loans whose Loan_Amount is in the range 400000 to 500000. Mysql> Select * from LOANS where Loan_Amount between 400000 and 50000;

:: 67 ::

Page 68: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

18. Display the details of all the loans whose rate of interest is in the range 11% to 12%. Mysql> Select * from LOANS where Int_Rate between 11 and 12;

Using IN Operator

19. Display the Cust_Name and Loan_Amount for all the loans for which the number of installments are 24, 36, or 48. (Using IN operator) Mysql> Select Cust_Name, Loan_Amount from LOANS where Instalment IN(24,36,48);

Using LIKE Operator

20. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the Cust_Name ends with 'Sharma'. Mysql> Select AccNo, Cust_name from LOANS where Cust_Name like '%Sharma';

21. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the Cust_Name ends with 'a'.

Mysql> Select AccNo, Cust_name,Loan_Amount from LOANS where Cust_Name like '%a';

22. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the Cust_Name contains 'a'.

Mysql> Select AccNo, Cust_name,Loan_Amount from LOANS where Cust_Name like '%a%';

23. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the Cust_Name does not contain 'P'.

Mysql> Select AccNo, Cust_name,Loan_Amount from LOANS where NOT (Cust_Name like '%P%');

24. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the Cust_Name contains 'a' as the second last character.

Mysql> Select AccNo, Cust_name,Loan_Amount from LOANS where Cust_Name like '%a_';

Using ORDER BY clause

25. Display the details of all the loans in the ascending order of their Loan_Amount. Mysql> Select * from LOANS ORDER BY Loan_Amount;

26. Display the details of all the loans in the descending order of their Start_Date. Mysql> Select * from LOANS ORDER BY Start_date DESC;

27. Display the details of all the loans in the ascending order of their Loan_Amount and within

Loan_Amount in the descending order of their Start_Date. Mysql> Select * from LOANS ORDER BY Loan_Amount, Start_Date DESC;

Using UPDATE, DELETE, ALTER TABLE

28. Put the interest rate 11.50% for all the loans for which interest rate is NULL. Mysql> Update LOANS SET Int_Rate =11.50 Where Int_Rate IS NULL:

29. Increase the interest rate by 0.5% for all the loans for which the loan amount is more than

400000. Mysql> Update LOANS SET Int_Rate= Int_Rate+0.5 Where Loan_Amount >400000;

30. For each loan replace Interest with (Loan_Amount*Int_Rate*Instalments) 12*100. Mysql> Update LOANS SET Interest=(Loan_Amount*Int_Rate*Instalments) /12*100;

31. Delete the records of all the loans whose start date is before 2007. Mysql> Delete From LOANS Where Year(Start_Date)<2007;

:: 68 ::

Page 69: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

32. Delete the records of all the loans of 'K.P. Jain' Mysql> Delete From LOANS Where Cust_Name='K.P.Jain';

33. Add another column Category of type CHAR(1) in the Loan table. Mysql> Alter Table LOANS ADD (Category CHAR(1) );

Find the Output of the following queries

34. SELECT cust_name, LENGTH(Cust_Name), LCASE(Cust_Name), UCASE(Cust_Name) FROM

LOANS WHERE Int_Rate < 11.00;

Cust_Name Length(Cust_Name) LCASE(Cust_Name) UCASE(Cust_Name) S.P. Sharma 11 s.p. sharma S.P. SHARMA M.P. Yadav 10 m.p. yadav M.P. YADAV

35. SELECT LEFT(Cust_Name, 3), Right(Cust_Name, 3), SUBSTR(Cust_Name, 1, 3)

FROM Loans WHERE Int_Rate > 10.00;

LEFT(Cust_Name, 3)

Right(Cust_Name, 3) SUBSTR(Cust_Name, 1, 3)

R.K pta R.K S.P nha S.P P. Rma P.

:: 69 ::

Page 70: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT -4 IT Applications

Chapter 11: IT Applications

The modern e-technology changed our lives and facilitated to all the area of applications like Banking, Education, Entertainment and Government etc. Now days, Information & Communication Technology (ICT) enabled services are essential requirement of every walk of life. Some application area of modern IT practices are described below-

E-GOVERNANCE:

E-Governance refers to the application of e-Technologies in governance to provide effective, efficient, faster and transparent services to citizens. Example of such applications are Birth/Death Registration, issuing Passport, making of Voter ID Card, Filing Income Tax returns, Railway Enquiry & Ticket booking, On-line delivery of Land records etc

Objective of E-Governance Applications To provide information and knowledge about political system and services to the citizens. To fulfill the requirement of citizens by providing services at minimal cost and at doorsteps. To facilitate faster, transparent, accountable, efficient and reliable system for various

administrative and social activities of the Government

Social impacts of E-Governance: Improved the efficiency of administration and service delivery Reduced waiting time Reduced Cost Increased public participation Increased transparency

Limitations of e-Governance: People in rural and remote area could not get benefit from these E-Governance projects due to

poor ICT infrastructure and lack of Awareness. Unavailability of computers, Internet and lack of knowledge of computer operation has also

prevented people to get benefit from E-Governance Applications. Not all the services can be computerized and offered by the E-Governance

Some E-Governance websites are:

Name of Website Purpose www.incometaxindia.gov.in It Provides all the services of Income Tax department www.indiancourts.nic.in It provides information related to Supreme Court and High Courts of

India. www.rti.gov.in Right to information Act 2005 mandates timely response to citizen

requests for government information www.india.gov.in This portal gives the information about Government of India and

allows the users to apply online for various Government services. www.drdo.nic.in Defense Research and Development organization.

E-Commerce:

E-Commerce or E-Business refers to any form of business or trade that uses e-Technologies to facilitate the selling or buying of products and services, transactions of money and goods etc.

Social impacts of E- Commerce: Reductions in transactions and production costs. Increase in the internet users. Improved customer service (24x7 services). Increased productivity/efficiency. Access to international (Global) markets.

:: 70 ::

Page 71: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Limitations of e-Commerce: Lack of knowledge and poor Telecommunication Infrastructure and unavailability of Internet

connectivity in Rural areas are major issues for limited use of e-Business. People are still unaware about legal remedies. There are high chances for fraud, theft of private

information due to lack of effective legal framework. Some E-Business websites are:

Name of Website Purpose www.irctc.co.in It provides online railway ticket reservation in India.

www.ebay.in Online shopping mall providing sales and online auctions. www.amazon.com Online store for Books, CD’s, DVD’s, MP3’s etc. www.yatra.com Online flight ticket booking service.

E-LEARNING:

E-Learning describe as a means of teaching and learning through e-technology like Internet and Multimedia enriched contents on CDROM or DVD.

Social impacts of E- Learning: Cost effective, Interactive and Multimedia enriched Material for effective and long-lasting

learning. No physical Interaction among Teacher and Learner is required i.e. most suited for working

people. Easily available and facilitates Any-time and Any-Where Learning.

Limitations of e-Learning: High dropout rate due to lack of interaction among Trainer and Trainee. Sometimes less effective due to inappropriate learning contents. It requires prior knowledge of Computer and other Technologies.

Some E-learning websites are:

Name of Website Purpose www.moodle.org It is Open source Course Management System (CMS) www.w3schools.com Online web tutorial. www.exelearning.org Open source application useful in publishing of web content. www.ncert.nic.in Interactive module for students to learn various topics.

:: 71 ::

Page 72: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

UNIT 4 : Questions & Answers Q1. What is e-Governance?

Ans: E-Governance is the use of a range of modern information and communication technologies such as internet, local area network, mobiles etc. by government to improve effectiveness of their services.

Q2. What is e-Learning?

Ans: E-Learning is a delivery of learning, training or education program by electronic means.

Q3. What do you mean by E-Business?

Ans: E-business is a term used to described business run on the computer.

Q4. What are objectives of E- Governance?

Ans: Objectives of E- Governance are:- • Improves Government processes. • Increases the efficiency and speed in a transparent manner. • Simplify administrative transactions. • Citizen can participate in decision making process.

Q5. List the advantages of E Governance.

Ans: Advantages are :- • Improved quality of information and information supply. • Reduction of process time. • Cost reduction. • Improved service level. • Increased efficiency.

Q6. How E-learning is useful to learner.

Ans: • It enables students to complete training conveniently at off-hours or from home. • Self pacing for slow and quick learners reduces stress and increased satisfaction. • Interactivity engage users, pushing them rather than pulling them through training etc.

Q7. Why E-learning is preferred?

Ans: E-learning is preferred because it provides faster learning at reduced cost, increased accessed to learning and clear accountability for all participants in the learning process.

Q8. What are the importance of E-business?

Ans: • Reductions in transactions and other cost. • Un-shortened supply chain. • Improved customer service. • Increased productivity/efficiency. • Access to international markets.

Q9. What do you think e-learning courses have high dropout rate?

Ans: the possible reasons for this are • Lack of interaction. • Lack of proper follow-up.

Q10. Write three web portals of (1) e-commerce (2) e-Governance (3) e-Learning?

Ans: e-Commerce e-Governance e-Learning www.irctc.co.in www.indiancourts.nic.in www.moodle.org

www.ebay.in www.rti.gov.in www.w3schools.com www.amazon.com www.india.gov.in www.exelearning.org

:: 72 ::

Page 73: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Sample Paper 1

KENDRIYA VIDYALAYA SANGTHAN SESSION ENDING EXAMINATION- Class XI

Informatics Practice Max. Marks: 70 TIME: 3:00 HRS

Answer the following questions. Q1. What is a Bluetooth? (2) Q2. What is the function of an OCR? (2) Q3. What are non-impact printers? (1) Q4. Write two characteristics of Random Access Memory. (2) Q5. What is an Assembler? (1) Q6. How Multi Processing Operating Systems is different from Multi Programming

Operating Systems? (2) Q7. Write a short note on Firewall. (2) Q8. Paradise Park uses the following interface to generate bill for its customers. (4)

The controls used in the above interface are as follows:

Control Type Control Name Functionality jTextField txtName Customer Name jTextField txtAge Customer Age jCheckBox chkJr1 Joy Ride 1 jcheckBox chjJr2 Joy Ride 2 jTextArea txtRes Bill Area jButon btnbill To generate Bill

When the bill button is clicked the bill is displayed as shown in the interface above. The functionality is as follows:

• Rate for joy ride 1 is 100 and that for Joy ride 2 is 200. • A customer can select one or both the joy rides. • The total is calculated as the sum of one or both joy rides cost. A discount of

Rs 50 is given on total if the child is below 12 years. Write code under the action event of the jButton to achieve the above functionality.

:: 73 ::

Page 74: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q9. Explain how java codes are compiled and run. (2) Q10. What will be the output of the following code segments: (2)

int a=5, b=10, c=9, d=8; System.out.println(“” + ((a++)+(++c)-(--b)+(d--)); System.out.println(“” + ((a>b)?(c>d)?(++d):35:(--b)));

Q11. Convert the following code segment using switch-case construct: (2)

int num = Integer.parseInt(txtNum.getText()); if(num>=2 && num<=5)

txtRes.setText(“Prime”); else if(num==6 || num==8 || num==10)

txtRes.setText(“Even”); else

txtRes.setText(“Not Valid”); Q12. Predict the output of the following java construct: (2)

int m=5; int prod=1; int i=1; while(i<=5) {

prod=prod+prod*(m%2); --m; ++i;}

System.out.println(“”+prod); Q13. Design an application having an interface like: (4)

Implement functionality by writing methods with passing the argument of three textboxes in calcSum(), calcAvg() & calcMax(). Q14. What are the actual and formal parameters? Give example to support your answer. (2) Q 15. Explain the use of Comments in Java with example. (2) Q 16. Explain two circumstances where run time errors may occur in a java program. (2) Q 17.Write two characteristics of a good program. (2)

:: 74 ::

Page 75: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q 18. Write short Notes on: (6) A. MySQL Features. B. Referential Integrity C. Database Constraints

Q19. What is NULL? What happens when you perform arithmetic calculations on NULL value. (2) Q 20. Enlist the various types queries available with DDL and DML (2) Q 21. Explain the difference between ROUND and TRUNCATE functions in MySQL with examples. (2)

Q 22. Given the following table Structure and sample data: (14)

Table Name: Saragam

Field Name Data Type Data Limit Constraint Albumid Numeric 4 PRIMARY KEY Album Text 20 NOT NULL Cost Numeric 3 DEFAULT 0 Quantity Numeric 3 Greater than 0 Singer Text 10

Sample Data:

Albumid Album Cost Quantity Singer 1001 SAHER 150 4 JAGIT 1002 MADHUSHALA 250 6 MANNA 1003 IBADAT 180 8 RAFI 1004 KISMAT 180 6 RAFI 1005 HALCHAL 200 4 KISHORE 1006 BLACK 210 10 MICHEL 1007 PASSION 200 5 SHAKIRA 1008 NAMESAKE 190 3 MADONA 1009 PLASURE 220 2 ASHA 1010 CATWALK 155 7 MADONA

Write the following queries:

A. Write SQL syntax to create the table. B. Add a column RATING in the above table containing numeric data and should accept

NULL values. C. Insert one Row in the table. D. Increase the cost of all the albums sung by RAFI by 50. E. Display cost of all those albums whose singer name ends with ‘A’. F. Display the album details for either RAFI, KISHORE or ASHA G. Display the Album details in the ascending order of their quantity.

Q 23. What will be the output of the following SQL statements: (4)

A. SELECT RIGHT(MID(‘MAHARAJA MAHAYOGI’, 2, 5), 4);

B. SELECT LEFT(SUBSTR(‘AARAHANAPAHARAN’,-10,5),2); Q24. How e-Governance has has benefited the Common man? (2) Q25. What benefits does e-business offer to a customer? (2) Q 26. Enlist 2 websites that provides e-learning platforms. (1)

:: 75 ::

Page 76: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

SAMPLE PAPER-1 (Solution)

Q.1 Bluetooth is telecommunication industry specification that describes how mobile phones , computers and PDA’s can be easily interconnected using a short range wireless connection.

2

Q.2 OCR is uased to read character of special type font printed on a conventional paper

with conventional ink.It is a input device.

2

Q.3 In these printers there is no mechanical contact between the print head and paper.

1 Q.4 The two characteristics of Random Access Memory are -

1. It is a volatile memory. Its contents are lost when power is turned off. 2. We can read as well as write in this memory.

2

Q.5 Multiprogramming OS- It supports multiprogramming i.e. more than one user can be

supported by it therefore more than one programs are loaded and active in main store at the same time. Multiprocessing OS- It is capable of handling more than one processor as the jobs have to be executed on more than on CPU. It is capable of load sharing.

2

Q.6 Firewall- A firewall is a technique used in a secured computer system or network to

block unauthorized access and allow only the authorized users.. Firewall can be implemented as a hardware as well as software , or combination of both.

2

Q.7 Assembler- Assembler is a language processor which translates a program written in

assembly language to machine language.

1

Q.8 String str= txtName.getText();

int age= Integer.parseInt(txtage.gettext()); int bill=0; if( chkJr1.isSelected()) bill+=100; if(chkJr2.isSelected()) bill+=200; if(age<12)

bill - =50; txtRes.append(“\n Name: “+str); txtRes.append(“\n Age: “+age); txtRes.append(“\n Bill: “+bill);

4

Q.9 Java complier produces bytecode, which is a machine instruction code for a java processor chip called Java Virtual machine. This bytecode is platform independent.

2

Q.10

System.out.println(“” + ((a++)+(++c)-(--b)+(d--)); Output: 14 System.out.println(“” + ((a>b)?35:(--b))); Output: 9

2

Q.11

int num = Integer.parseInt(txtNum.getText()); switch(num) { case 2:

case 3: case 4: case 5: txtRes.setText(“Prime”); break;

case 6: case 8: case 10: txtRes.setText(“Even”); break; default: txtRes.setText(“Not Valid”);

}

2

Q.12 Output:- 4

2

:: 76 ::

Page 77: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q.13

int calcSum( int N1, int N2, Int N3) 4 { return (N1+N2+N3);} float calcAvg( int N1, int N2, Int N3) { return (float)(N1+N2+N3)/3;}// Type casting int calcMax( int N1, int N2, Int N3) { return ((N1>N2?(N1>N3? N1:N3):( N2>N3?N2:N3);}

Q.14 Actual parameters are those parameters which appear in method call statement. 2 Formal parameters are that parameter which appear in method definition. int M1( int x, int y) // x & y are formal parameters { return (x+y);} int a=12,b=13; int C=M1( a,b); // a,b are actual parameters 1

Q.15 Comments provide internal documentation of a program. In Java comments are given 2 either by // or /* ….*/ brackts.

Example- /* This method calculates sum of two numbers.*/ int Sum( int x, int y)// x,y are formal parameters { return (x+y); }

Q.16 1. Divide by zero error- When we try to divide a number by 0. 2. When we try to calculate square root of a negative number.

2

Q.17 Characteristics of a good program.

1. The program should be user friendly.. The user should not concern about what is happening inside a program. 2. The program should be portable i.e. it should run on different platforms.

1

Q.18 A. MySql features- Open Source , SQL support, Portability, Speed, Ease of use,

Security etc. B. The property of a relational database which ensures that no entry in a

foreign key column of a table can be made unless it matches a primary key value in the corresponding column of the related table. It is enforced in the database with the help of foreign key constraint.

C. A Constraint is a condition or check applicable to a column or table which ensures the integrity or validity of data. Constraints are also called Integrity constraints.

6

Q.19 NULL is a specific value which indicates empty or nothing. If any column value involved in an arithmetic expression is NULL, the result of the arithmetic expression is also NULL.

2

Q.20 DDL: Create, Alter, Drop commands. DML: Select, insert, Update, Delete commands.

2

Q.21 Round( X,D):-> returns X rounded to D decimal places.

Truncate(X,D):-> The number is truncated to D digits after decimal point. Select round( 1.298,1); will return 1.3 Select truncate( 1.298,1); will return 1.2

2

:: 77 ::

Page 78: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q.22 A. Create Table-

Create table Sargam (Albumid int(4) primary key, Album varchar(20) not null, Cost int(3) default 0, Quantity int(3) check ( Quantity>0), Singer varchar(10));

B. Add a column RATING in the above table. Alter table Sargam ADD COLUMN (rating int);

C. Insert one Row in the table. Insert into Sargam values(111,’Miraz’, 200,2,’Jagjit’);

D. Increase the cost of all the albums sung by RAFI by 50.

Update Sargam SET cost=cost+50 where singer=’RAFI’;

E. Display cost of all those albums whose singer name ends with ‘A’. Select cost from Sargam where singer like ‘%A’;

F. Display the album details for either RAFI, KISHORE or ASHA

Select * from Sargam where singer IN( ‘RAFI’,’KISHORE’,’ASHA’);

G. Display the Album details in the ascending order of their quantity. Select * from Sargam ORDER BY Quantity;

Q.23

a) HARA b) AN

4

Q.24

• Keeping a tab on corruption. • Resulted in increased public participation. Or any two benefits to common men.

2

Q.25

Access to International markets, increased productivity, reduction in transaction and other cost or any other benefits to customer.

2 Q.26

www.moddle.org, www.w3schools.com, www.exelearning.org

1

:: 78 ::

Page 79: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Sample Paper 2

Session Ending Examination Class XI – Informatics Practices (065)

Time: 03 Hours Max. Marks: 70

Instructions: i) All questions are compulsory. ii) Answer the questions after carefully reading the text. iii) Do all the parts of same question together.

Q.1 (a) What are basic units of a computer system? Discuss the major function of each unit. [2]

(b) What do you mean by Biometric identification of a person? Suggest any two application areas where biometric devices can be used.

[2]

(c) Give one example of the following - (1)Web Browser (2) File Compression Utility (3)Developer Tools (4) Operating System

[2]

(d) Sumit is confused between the term ‘Compiler’ and ‘Interpreter’. Can you explain the difference between two.

[2]

(e) What do you mean by Phishing threat? How Phishing is different from PC Intrusion attack?

[2]

Q.2 (a) Ramesh wants to disable some of the jTextFields during runtime. Suggest him the suitable method to be used for this purpose.

[1]

(b) Name any two container controls in Java. [1]

(c) Write the java statement to declare a variable named ‘Status’ which may hold ‘true’ or ‘false’ value.

[1]

(d) Which method is used to get selected text from jComboBox1 control? [1]

(e) Write any four characteristics of Java? [2]

(f) Differentiate between Syntax error and Logical error with suitable example? [2]

(g) Discuss some naming rules and conventions of naming a variable in Java? [2]

Q.3 (a) Which MySQL command helps you to see existing databases? [1]

(b) Ramesh wants to delete a table ‘Customer’ from the database named MYBANK. Name the MySql command, should he use.

[1]

(c) Rakhi wants to see those students whose name ending with ‘Singh’ word from Student table. She wrote the following query, but she finds errors. SELECT name.* FROM student WHERE name=”Singh%”; Write the correct query after removing errors for her.

[1]

(d) Which keyword with select command is used to remove duplicate entities in resultant output?

[1]

(e) Discuss any four advantages of computerized database using DBMS? [2] (f)

Predict the output of the following query- 1. Select mid(‘Annual Examination’,8,4); 2. Select round(355.856,1); 3. Select concat(“abc”, concat(“pq”,”xy”)); 4. Select substr(‘ABCDEFG’, -5,3);

[2]

(g) Explain any four table constraints which are used in MYSQL. [2] :: 79 ::

Page 80: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q.4 (a) Give the expected output of the following statement.

jTextField1.setText(“”+3+2); [1]

(b) Name the size of the following data types in Java. (1) int (2) float

[1]

(c) Write one word answer for the following: 1. Which java keyword is used to skip the remaining portion of a loop and start a

new iteration? 2. Which property is set during design time to assign an access key to a jButton?

[2]

(d) Rewrite the following code using for loop without affecting the output. int i=0; while( i < 20) { if(i==8) break; System.out.println(i); i++; }

[2]

(e) What will be the output of the following code fragment if value of ch variable is: (1) a (2) c (3) d (4) h

switch(ch) { case ‘a’ : System.out.println(“I am a”); case ‘b’: System.out.println(“I am b”); case ‘c’: System.out.println(“I am c”); break; case ‘d’: System.out.println(“I am d”); break; default : System.out.println(“Not a,b,c,d”); }

[2]

(f) Locate the errors in the following code fragment and re-write the code with underlined corrections : integer num=20,i=1; long sum=0; do(i<num) { sum+=i ++i; } jTextField1.Settext(“”+sum);

[2]

(g) Vivek works in Aryan International School. He has developed the following interface in Netbeans with controls to calculate the total fee:

Controls Name Purpose jTextField txtName Student Name

txtTfee Tution Fee txtCfee Computer Fee txtTotal Total Fee

jRadioButton btnSe Secondary section btnPr Primary section

jButton btnFee Get Fees btnClr Clear

[5]

:: 80 ::

Page 81: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

The tuition fee is Rs. 1200/- and Computer fee 300/- for Secondary. The tuition fee is Rs.1000/- and Computer fee is 200 for Primary section. The total fee is calculated as the sum of Tuition Fee and Computer Fee.

1. Write the code for calculate and display Total fee, Tution Fee and Computer Fee should be displayed in corresponding text boxes, when Calculate Fee button is clicked. (3)

2. Write the code for Clear button to clear all the text boxes and Secondary Radio button should be selected. (2)

Q.5 (a) What is use of LIKE operator in MySql ? How is it different from = (equal) operator. Explain with an example.

[2]

(b) Write queries to create the following table:

EMP Column name Data type Size Constraint EMPNO Integer 4 digits Primary Key ENAME Varchar 25 characters Not Null GENDER Char 1 Default M DOB Date Not Null SAL Numeric 4 digits Null allowed

[2]

(c)

Predict the output based on the following table-

STUDENT Rollno Name Class Gender Hobby Fees

101 AMAR 10 M Painting 100 102 MANI 7 F Drama 200 103 RAMA 6 F Cooking 150 104 SHAMA 10 F Cooking 250 105 KAJOL 9 F Sports 100 106 BUNTY 5 M Drama 120 107 AKBAR 4 M Sports 150 108 TONY 8 M Sports 100 109 JEETU 9 M Painting 200

1) SELECT Hobby from Student WHERE Fees IN (120,150);

[6]

:: 81 ::

Page 82: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

2) SELECT COUNT(*) FROM Student WHERE Gender=’M’;

3) SELECT Name FROM Student WHERE class >7;

4) SELECT Name, Gender from Student WHERE Hobby=’Painting’;

5) SELECT COUNT(DINSTICT(Hobby)) FROM student;

6) SELECT Name, Fee+100 From Student where Hobby=”Sports” And Class < 8 ;

Q.6 Consider the following table and write the query. STAFF

EMPNO ENAME GENDER DOB DEPTNO SAL 1001 RAHIM M 2002-01-20 10 8500 1002 AMAR M 2001-03-20 11 8500 1003 SURYA F 2004-11-25 10 9000 ….. …… . ……………… … ……

a) Display ENAME, GENDER ,DOB for all the employees who are not working in the Deptno 10 and 13.

b) Display the ENAME, GENDER and SAL of employees who are born in the year 2005.

c) Write a query to display all names whose name starts with ‘A’ character. d) Write a query to display name and Date of Birth whose Salary lies in range of

9000 to 12000. e) Write a query to display name and Salary in descending order of salary. f) Write a query to display details of all male employees whose salary is more

than 10000. g) Write a query to add a new column FName of 30 characters. h) Write a query to insert a record in the table (assume values yourself). i) Write a query to increase the SAL of all the female employees by 5% of existing

Salary. j) Write a query to delete the record for Empno 1006.

[10]

Q.7 (a) Enlist two websites that provide e-Learning Solutions. [1]

(b) Write two importance of e-Commerce for the Society [2]

(c) What is e-Governance? How e-Governance is benefiting citizens. [2]

:: 82 ::

Page 83: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

SAMPLE PAPER-2 (Solution)

Q.1 (a) Basic unit of computer are- 1. Input Unit – Used to enter data and instruction into computer. 2. Output Unit- used to see result from computer. 3. Memory Unit- it stores data and instruction while processing. 4. Secondary Storage Unit- stores data permanently. 5. Control Unit- It controls operations of I/O devices and processing. 6. Arithmetic Unit – This unit performs calculations on data.

2

(b) Biometric identification verifies person’s identity using Biometric technologies like Signature verification, Retina scan; DNA identification, face recognition, voice recognition and finger print identification.

Application Area – Security and Identification area etc.

2

(c) (1) Internet Explorer/Fire fox/Google Chrome or any other. (2) Win Zip/ 7 Zip/ any other. (3) NetBeans/Delhi/Eclips/Turbo C++ / or any other IDE. (4) Unix/Windows/Linux / any other OS.

2

(d) 1. Compilers translate HLL program into Machine code in one go, whereas Interpreter translates line – by line mode.

2. A compiler displays all errors with line numbers but Interpreter stops translation in case error occurs.

2

(e) Phishing is process of attempting to acquire sensitive information such as user name, password, credit card number and bank account data. PC Intrusion is an Internet threat attempted by hackers or a malicious program. It may include Sweeper attack and DoS attack etc.

2

Q.2 (a) jTextField1.enabled (false); 1

(b) jTextFrame/ jPannel/ jDialog etc. (any two) 1

(c) boolean status; 1

(d) jComboBox1.getSelectedItem() 1

(e) WORA/Free/Open Source/ GUI enabled/Internet Application etc. 2

(f) Syntax error- This type of error occurs when rules of programming language are violated. Ex. Misspelled commands, missing semicolon etc. Logical errors- This type of error occurs when expected result is not obtained, even program is running properly. This is due to error in the logic of the solution. Example- if we are writing C=A+B+C/3 instead of C=(A+B+C)/3 for getting average of A,B and C, then Logical error occurs.

2

(g) The four rules for naming variables in Java are summarized below: Variable names are case sensitive. Keywords which have special meaning in java, should not be used as the

variable names. Variable names should be short and meaningful. All variable names must begin with a letter, an underscore(_) or a dollar

sign($). The convention is to always use a letter.

2

Q.3 (a) Show databases; 1

(b) Drop table Customer; 1

(c) SELECT * FROM student WHERE name LIKE ”%Singh”; 1

(d) Distinct keyword. 1

(e) Four advantages of computerized database are- 1. Databases reduces Redundancy 2. Database controls Inconsistency 3. Database facilitate Sharing of Data 4. Database ensures Security

2

:: 83 ::

Page 84: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

(f) 1. Exam 2. 355.9 3. abcpqxy 4. CDE 2

(g) Primary Key/Not Null/Unique/Default/Check/Foreign Key 2

Q.4 (a) 32 1

(b) (1) 2 Byte (2) 4 Byte 1

(c) 1. Continue (2) Mnemonic Property 2

(d) for(int i=0;i<20; i++) { if(i==8) break; System.out.println(i); }

2

(e) The output is (1) I am a (2) I am b (3) I am d (4) Not a,b,c,d

I am b I am c I am c

2

(f) int num=20,i=1; long sum=0; while(i<num) { sum +=i ; ++i; } jTextField1.setText(“”+sum);

2

(g) 1.//to do code for btnFee int tot, tf,cf; if (btnSe.isSelected()) {tf=1200; cf=300; } if(btnPr.isSelected()) {tf=1200; cf=200; } tot=tf+cf; jTextTotal.setText(” “”+tot); 2.//To do code for BtnClr txtName.setText(“”); txtTfee.setText(“”); txtCfee.setText(“”); txtTotal.setText(“”) btnSe.setSelected(true);

3 2

Q.5 LIKE operator is used to compare Pattern Strings where as = operator is used for exact comparing of the strings.

2

1) Cooking Drama Sports

2) 5 3) Amar

Shama Kajol Tony Jeetu

4) Amar M Jeetu M

5) 4 6) Akbar 250

:: 84 ::

Page 85: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q.6 (a) a) Select Ename,Gender, Dob from Staff Not IN(10,13); b) Select Ename,Gender,Sal from Staff where Year(DOB)=2005; c) Select Ename from Staff where ename like ‘A%’; d) Select Ename,DOB from Staff where Sal between 9000 and 12000; e) Select Ename,Sal from Staff Order by Sal DESC; f) Select * from Staff where where Sal>10000 And Gender=’M’; g) Alter Table Staff ADD (FName Char(30)); h) Insert Into Staff Values (1004,’abc’,’M’,’2005-11-10’,10,9500); i) Update Staff Set Sal=Sal+(Sal*5/100) Where Gender=’F’; j) Delete From Staff Where EmpNo=1006;

10

Q.7 (a) www.moddle.org, www.w3schools.com 1

(b) The social impact of e-commerce are- Reductions in transactions and production costs. Increase in the internet users. Improved customer service (24x7 services). Increased productivity/efficiency. Access to international (Global) markets

2

(c) E-Governance refers to the application of e-Technologies in governance to provide effective, efficient, faster and transparent services to citizens. Example of such applications are Birth/Death Registration, issuing Passport, making of Voter ID Card, Filing Income Tax returns, Railway Enquiry & Ticket booking, On-line delivery of Land records etc

Benefits of E-Governance: Improved the efficiency of administration and service delivery Reduced waiting time Reduced Cost Increased public participation Increased transparency

2

:: 85 ::

Page 86: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Model Paper (Unsolved) Session Ending Examination

Class XI – Informatics Practices (065)

Time: 03 Hours Max. Marks: 70 Instructions:

iv) All questions are compulsory. v) Answer the questions after carefully reading the text. vi) Do all the parts of same question together.

Q.1 (a) What do you mean by Application software? How is it different from System

software? [2]

(b) What do you mean by Compiler? How it is different from Interpreter. [2]

(c) Expand the following terms- (1) MICR (2) PDA (3) DVD (4) TFT

[2]

(d) What is Operating System? Discuss its role in operation of computer system. [2]

(e) What do you mean by Security threats? Discuss some preventive measures to protect our computer system from Internet threats?

[2]

Q.2 (a) Write any two features of the Java. [1]

(b) Vinay wants to display an image in a jLable control, but he don’t know which property to be customized. Help him about the property to be used.

[1]

(c) Raman is confused about Byte code? Can you explain him? [1]

(d) How syntax errors are different from logical errors? [1]

(e) What are Operators? How logical operators are different from Relational operators?

[2]

(f) How Properties, Methods and Events are interrelated? Explain with a suitable example?

[2]

(g) What do you mean looping constructs? Write a ‘for’ loop to print even numbers from 2 to 20.

[2]

Q.3 (a) Which MySQL command is used to open a database? [1]

(b) Ranjan wants to see the structure of Customer table. Name the MySql command should he use.

[1]

(c) Rohit wants to see those records whose value is NULL in Address column of EMP table. He wrote the following query. SELECT name and address FROM EMP WHERE Address=NULL; But MySql reported errors. Write the correct query after removing errors.

[1]

(d) Write difference between Char and Varchar data types in MySql. [1] (d) What do you mean by Data Models? Discuss any two properties of Relational

Model. [2]

(f) Predict the output of the following query- 5. Select Lower(Right(“DEHRADUN”,3)); 6. Select Instr(“Informatics Practices”, ”or”));

[2]

(g) What do you mean by Keys? How Primary key is different from Candidate key.

[2]

:: 86 ::

Page 87: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

Q.4 (a) Give the expected output of the following statement. jTextArea1.setText(“Learning\n Java \t is fun”);

[1]

(b) Write the Command to display “Hello Java” in a message Dialog. [1]

(c) Rewrite the following code using while loop without affecting the output. for(int x=0; x<=10; x++) { if(x%2==0) System.out.println(“Dehradun”); else System.out.println(“Lucknow”); }

[2]

(d) What will be the output of the following code segment: int i=3, n=0; while (i<=14) {n++; i =i+2; } System.out.println(“”+n);

[2]

(e) Locate the errors in the following code fragment and re-write the code with underlined corrections : int a=2,b==3,c,i=0; c=a+b; for(; i<=5, i++) { if c=6 break; } JtextField1.getText(“”+c);

[2]

(f) The Ramson Casting Company has developed an application to calculate the wage of its workers. The following functionalities are expected.

1. The Wage rate are Rs.150/- and Rs.130/- per day for male and females workers respectively.

2. An additional amount Rs.50/- per day is paid if worker is skilled.

The controls on the frame and their names are as follows:

Object Type Object Name Description JTextField txtName To enter the Name txtDays To enter the number of working days txtAmount To display the amount due JRadioButton optMale To select male optFemale To select female JCheckBox chkSkilled To select if worker is skilled JButton btnCalculate To calculate the Wage amount btnClear To clear all the entered data

[7]

:: 87 ::

Page 88: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

(a) Write the code for cmdClear Command Button to clear all the textboxes. (1) (b) Write the code for the ActionPerformed event of btnCalculate to calculate the

Wage Amount as per conditions given. (4) (c) Which property you will customize to display ‘Wage Calculator’ on title bar of

the frame. (1) (d) Which property, you will customize to display ‘Click me to get Result’ when

mouse pointer is placed over Calculate button. (1)

Q.5 (a) What is SQL? How SQL commands are classified? [2]

(b) Write queries to create the following table:

CUSTOMER Column name Data type Size Constraint CUSTID Integer 4 digits Primary Key CNAME Varchar 25 characters Not Null GENDER Char 1 character Default M ADDRESS Varchar 30 characters Null allowed

[2]

(c)

Write the command for the followings-

1) SQL command to increase the size of Address field of Customer table from 30 to 50 characters.

2) Delete the Age column from the Customer table.

[2]

(d) Predict the output based on the following table- STUDENT

Code StName Age Gender Course Fees 101 ANMOL 21 M JAVA 1250 102 AMAN 32 M DBMS 1200 103 SUNIDHI 26 F CPP 1150 104 KAMAL 18 M Networking 1250 105 KOMAL 29 F DBMS 1200 106 SAMEER 35 M JAVA 1100 107 ABHISHEK 24 M WEB PRG 1150 108 TANIYA 18 F DBMS 1200

7) SELECT Course from Student WHERE Fees >1200;

8) SELECT COUNT(*) FROM Student WHERE Gender=’F’ AND Age>28;

9) SELECT StName FROM Student WHERE left(StName,1)=’A’;

10) SELECT COUNT(DINSTICT(COURSE)) FROM student;

[4]

Q.6 Consider the following table and write the query.

[10]

:: 88 ::

Page 89: KENDRIYA VIDYALAYA SANGATHANUnit -3 : Relational Database Management Systems . Chapter 8: Introduction to DBMS and MySQL 57 Chapter 9: Working with MySQL 59 Chapter 10 : MySQL Functions

EMPLOYEE EMPNO NAME GENDER DOJ Dept AGE SAL E01 RAKESH M 2002-01-20 Computer 40 28500 E02 AMAR M 2001-03-20 Sales 31 18500 E03 SURYA F 2004-11-25 Production 44 19000 E04 RUDRA M 1998-11-23 Sales 34 19500 ….. …… . ……………… … …… k) Display NAME and GENDER of all the employees who are not working in

Sales department. l) Display the NAME of employees who are joined in the year 2004. m) Write a query to display all names whose name starts with ‘R’ character. n) Write a query to display name and Date of joining whose Name is ended with

‘A’ character. o) Write a query to display details of all male employees whose salary is more

than 19000. p) Write a query to display name and Salary in descending order of salary. q) Write a query to count persons who works in Computer Department. r) Write a query to increase the Salary of all the female employees by 15% of

existing Salary. s) Write a query to insert a record in the table (assume values yourself). t) Write a query to delete the record for Empno equal to E06.

Q.7 (a) Enlist two websites related to e-commerce application. [1]

(b) What do you mean by e-Learning? Write two limitations of e-Learning. [2]

(c) “e-Governance provides effective administration and can be used as a tool for minimizing corruptions”. Justify the statement?

[2]

_________________________________________________

:: 89 ::