Kendriya Vidyalaya Sangathan

KENDRIYA VIDYALAYA SANGATHAN GUWAHATI REGION ... Don’t stretch the answer unnecessarily. ... Grouping Records And …...

0 downloads 155 Views 9MB Size
केय व यालय संगठन

Kendriya Vidyalaya Sangathan

Guwahati Region STUDY MATERIAL

(Informatics Practices) Class – XII

2012-13

Chief Patron:

Shri K.J. Subba Deputy Commissioner, KVS RO, Guwahati Region

Patron: Shri. AVLJ Rao, Assistant Commissioner, KVS RO

Guwahati Region

Co-ordinator:

Shri. S. Lakshminarayanan Principal, KV AFS, Digaru, Assam

Subject Contributors: Mr. Manash Ranjan Sahoo, PGT (Computer Science), KV Noonmati Mr. Vikas Gupta, PGT (Computer Science), KV Khanapara Mr. Rishi Raman, PGT (Computer Science), KV AFS, Borjhar Mr. Rajesh Bist, PGT (Computer Science), KV Panbari Mr. Sachin Patel, PGT (Computer Science), KV Maligaon Mr. Amit Kumar, PGT (Computer Science), KV Digaro Mr. Suerendra Vishwakarma, PGT (Comp. Science), KV Maligaon

KENDRIYA VIDYALAYA SANGATHAN GUWAHATI REGION

TIPS FOR STUDENTS 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.

Prepare those questions first, which you feel easy for you. Important terms of a topic must be memorized. Practice the solutions in writing rather than just reading. Practice all similar type questions at a time. Read all the questions carefully, before answering. Attempt such questions first, for which you are confident that it will leave a good impression. Don’t stretch the answer unnecessarily. Try to write answer in points. Important point should be underlined but be careful, don’t waste your time. Try to illustrate your answer graphically, if possible. Don’t leave any question unanswered. Solve previous years question papers. Make precise and concise notes, point wise for exam time preparation/quick revision. Plan your study judiciously. A proper timetable for study should be followed strictly. Take healthy and timely diet during examinations. Also take sound sleep everyday. Take a break from time to time in each study period. Do not forget to revise all the topics one day prior, to the day of examination. Take good care of your health.

INDEX

1.

Chapter-1: Computer Networking

2.

Chapter-2: Open Source Concept

3.

Chapter-3: Java GUI Programming Revision Tour -I

4.

Chapter-4: Java GUI Programming Revision Tour -II

5.

Chapter-5: Java GUI Programming Revision Tour –III

6.

Chapter-6: More About Classes And Libraries

7.

Chapter-7: Concept of Inheritance

8.

Chapter-8: GUI Dialogs And Tables

9.

Chapter-9: Database Connectivity to MySQL

10.

Chapter-10: Web Application Development

11.

Chapter-11: HTML-I : Basic HTML Elements

12.

Chapter-12: HTML-II : Lists, Tables And Forms

13.

Chapter-13: XML - eXtensible Markup Language

14.

Chapter-14: MySQL Revision Tour

15.

Chapter-15: Database Transactions

16.

Chapter-16: More On SQL – Grouping Records And Table Joins

17.

Chapter-17: Tables And Integrity Constraints

18.

Chapter-18: IT Applications

19.

Sample Question Paper

20.

Marking Scheme of Sample Question Paper

21.

CBSE AISSCE – 2012(Outside Delhi) Question Paper

22.

Marking Scheme of AISSCE – 2012(Outside Delhi) Question Paper

CHAPTER 1 NETWORKING AND OPEN STANDARDS Brief Summary of the Chapter: In this chapter we are going to study about computer Networks, associated terminology and related concept along with network devices.

Key Points of the Chapter: • Network: A Computer Network is a number of computers (Usually called terminals interconnected by one or more transmission paths.

• Need of Networking: 1. 2. 3. 4. 5. 6. 7. 8.

Resource Sharing File and data sharing. Data security and centralized security High Reliability : Communication Media High Speed Flexible working environment Cost factor

• Application of Networks 1. 2. 3.

Sharing of data, services and resources Access to remote database Communication facilities

a. Elementary Terminology of Networks : 1. Nodes (Workstations):- The term nodes refer to the computers that are attached to a network and are seeking to share the resources. 2. Server:- A computer that facilitates the sharing of data, software and hardware resources on the network 3. Network Interface Unit (NIU) (MAC Address):- A network interface unit is interpreter that helps in establishing the communication between the server and the client. 4. IP Address:- Every machine on a TCP bar IP Network has a unique identifying no. called an IP Address. 5. Domain Name:-It is a way to identify and locate the computers connected to the internet. It must be unique. a. NETWORK TOPOLOGIES : The term Network Topologies refer to the way in which the nodes of a network are physically connected together. The important network topologies are

1) Bus Topology or Linear Topology : In this topology a single length of the transmission medium is used onto which the various nodes are attached. The transmission from any station travels the length of the bus, in both directions and can be received by all other stations. The bus has a terminator at either end which absorbs the signal, removing it from the bus. Characteristics: Short cable length and Simple wiring layout A single cable called trunk is used through which all data propagates and to which all nodes are connected Easy to extend There is no central point of failure on a bus because there is no hub. Entire network shuts down if there is break in the main cable. Terminators are required at both ends of the backbone cable. Difficult to identify the problem if the entire network shut down. Addition of nodes negatively affects the performance of the whole network. Only one computer can send messages at a time

2)

Ring Topology: In a ring topology each node is connected to two and only two neighboring nodes. Data is accepted from one of the neighboring nodes and is transmitted onwards to another. Thus data travels only one direction. Every computer serves as a repeater to boost signals Short cable length. Suitable for optical fiber Difficult to add computers More expensive If one computer fails, whole network fails Data clashes can also occur if two machines send messages at the same time.

3)

Star Topology: A start topology is designed with each node connected directly to the server

via hub or switch. This topology is used in most existing information network. Data on a star network passes through the hub or concentrator before continuing to its destination. Easy to install and wire No disruptions to the network when connecting or removing devices. Easy to add new station as each station has direct cable connection to hub or switch. Depending on the intelligence of hub, two or more computers may send message at the same time One malfunctioning node does not affect the rest of the network. Required more cable length than a linear topology. All signals transmission through the hub; if down, entire network down

NETWORK DEVICES 1.

MODEM( MODulator DEModulator) : Modem is a device that converts digital data originating from a terminal or computer to analog signals used by voice communication network such as the telephone system. At one end, modems convert the digital pulse to audible tones and convert audio tones back to digital pulses at the other

2.

RJ –45 Connector: The RJ-45 is a single line jack for digital transmission over ordinary phone wire. It is a 8 wire connector which is commonly used to connect computers on the LAN(especially Ethernets). RJ – short for Registered Jack – 45

3. 4.

5.

6.

7.

Ethernet Card or NIC or NIU:A NIC(Network Interface card) is a computer circuit board or card that is installed in computer so that it can connected to network. It is suitable for coaxial or twisted pair cables. Hub: Hub is a device used to connect several computers together. It is a multi-port card. Hubs forward any data packets including e-mail, word processing documents or print request – they receive over one port from one workstation to all of their remaining ports Switches : Switches are smart hubs that send data directly to the destination rather than everywhere within network. When the switch receive a packet, the switch examines the destination and source hardware address and compare them to a table of a network segments and addresses. If the segments are the same the packet is dropped and if the different then the packet is forwarded to the proper segments. Repeaters :A repeater is a device that amplifies a signal being transmitted on the network. Since a signal loses strength as it passes along a cable, it if often necessary to boost the signal with this device.. The repeater electrically amplifies the signal it receives and rebroadcasts it.

Router: A device that works like a bridge but can handle different protocols, is known as router. It is used to separate different segments in a network to improve performance and reliability.

Solved Questions: Q1. What is MAC Address? Ans : In computer networking, a Media Access Control address (MAC) is a unique identifier assigned to most network adapters or network interface cards (NICs) by the manufacturer for identification, and used in the Media Access Control protocol sub-layer. Q2. Write two advantages of networks. Ans: Advantages: i) Data or information can be shared among the users. ii) Fast communication can be achieved. Q3. Write two disadvantages of networks. Ans : Disadvantages of networks: i. Sophisticated Hardware and software technology is required. ii. Expensive to install network. Q4. What is communication channel? Name the basic types of communication channels available. Ans: What is communication channel? Name the basic types of communication channels available. Communication channels mean the connecting cables that link various workstations. There are 3 basic types of cables:  Twisted Pair cables  Coaxial cables  Fiber-optic cables Q5. Define a network. Ans: A computer network is a system in which computers are connected to share information and resources. Q6. What is IP address? Ans A unique number consisting of 4 parts separated by dots, e.g. 165.113.245.2 Every machine that is on the Internet has a unique IP number - if a machine does not have an IP number, it is not really on the Internet. Q7. What is domain name? How is it alternatively known? Ans The unique name that identifies an Internet site. Domain Names always have 2 or more parts, separated by dots. The part on the left is the most specific, and the part on the right is the most general. E.g.: matisse.net

Q8. What are the various types of networks? Ans : Network can be classified on the basis of their size, complexity and geographical spread. On the basis of geographical spread it can be classified as Local Area Network, Metropolitan Area Network and Wide Area Network. Q9. What is the difference between MAN and WAN? Ans : A metropolitan area network (MAN) is a large computer network that usually spans a city or a large campus. WAN is a network that covers an area larger than a single building or campus such as across the cities or countries. Q10. What is meant by Topology? Name some popular topologies. Ans: Network topology is defined as the interconnection of the various elements (links, nodes, etc.) of a computer network. In computer networking, topology refers to the layout of connected devices. • Bus topology • Star topology • Ring topology • Tree topology • Mesh topology

Q11. What are the similarities and differences between bus and tree topologies? Ans: In bus topology each machine is connected to a single cable. Each computer or server is connected to the single bus cable through some kind of connector. Tree topology is a network with the shape of an inverted tree in which a single link between two nodes. Q12. What are the limitations of star topology? Ans i) Central node dependency: In this topology central node is a controller of the network. If the central node fails, the entire network will be failed. ii) Difficult to expand: The addition of a new node to a network involves a connection all the way to the central node.

Unsolved Questions: 1. 2. 3. 4. 5.

6. 7. 8. 9. 10. 11.

What are the goals of network? Write the applications of network? What do you understand by domain name resolution? What are communication channels? Discuss various channels available for networks? Advantages and disadvantages of the followings : i. optic fiber ii. coaxial cables iii. twisted pair cables iv. radio waves v. microwaves vi. Satellites Discuss and compare various types of networks? Explain mostly used topologies. What are hubs? What are its types? What is the role of a switch in a network? Discuss repeater. What are common threats to network security?

12. 13. 14. 15. 16. 17. 18.

What are denial of services attacks? How can you prevent/ counter threats of network security? When do you think, ring topology becomes the best choice for a network? Write the two advantages and two disadvantages of star topology in network. Write the disadvantages if twisted pair cables. Define Hub. Define switch.

Chapter 2 FREE AND OPEN SOURCE SOFTWARE Brief Summary of the Chapter: In this chapter we are going to discuss about various open source software and how they are different from software which are not open source.

Key Points: Free Software: It means software is freely accessible, free to use, changed, improved, copied, and distributed without any payments. Four kinds of freedom: ► Freedom to run the program for any purpose ► Freedom to redistribute copies. ► Freedom to study how the program works ► Freedom to improve the program and release your improvements to the public Open Source Software: Definition: The categories of software / programs whose Licenses do not impose many conditions. Features: 1. Freedom to run and use the software 2. Modify the program 3. Redistribute copies of either original or modified program (without paying royalties to previous developers). It can be freely used for modifications, but it does not have to be free of charge. Its source code is available. Criteria for the distribution of open source software 1. Free distribution 2. Source code 3. Derived works 4. Integrity of the Author’s Source code 5. No discrimination against fields of endeavor. 6. Distribution of License 7. License must not be specific to a product 8. License must not restrict other software. FOSS (free and open software):Free software- no payments Open source software- for technical progress OSS and FLOSS ► OSS- Source code is available

(Open source modified and redistributed software) free of cost or with nominal charge. ► FLOSS- (free libre and open source software) FSF (free software foundation) • Founded by Richard Stallman in 1985 to support GNU project. • Non-profit organization created for the purpose of supporting free software movement GNU (free and open source) • Objective: To create a system compatible to UNIX but not identical with it. • Now it offers a wide range of software, including applications apart from operating system. Proprietary software (neither open nor freely available) • Definition- Its use is regulated and further distribution and modification is either forbidden or requires special permission by the supplier • Source code is not available. Freeware • Free of cost • Copying and further distribution but not modification. • Source code is not available Example Internet Explorer Shareware • Right to redistribute copies • After a certain period of time license fee should be paid. • Source code is not available. • Modifications are not possible. • Objective- to increase user’s will to pay for the software. Limits functionality after a trial period of 1-3 months. Important Software’s LINUX • Linux: - free and open source software. • It can be downloaded from www.linux.org • Linux is a part of popular web server program LAMP (Linux, apache, MySql, PHP). Mozilla • Freeware • No source code available • free internet software It can be downloaded from www.mozilla.org Apache Server • The most common web server (or HTTP server) software on the Internet. • Apache is designed as a set of modules, enabling administrators to choose which features they wish to use and making it easy to add features to meet specific needs including handling protocols other than the web-standard HTTP. • Apache HTTP server is an open source web server. • It is component of LAMP. Denial-of-services attacks: DOS are those attacks that prevent the legal users of System from accessing or using the resources, information or capabilities of the system. It may be of following types:

Denial of Access to Information: Such attacks cause deletion or changing of important information to non-readable format. • Denial of Access to Applications: Such attacks make the applications unusable or unavailable for legal user of the system. • Denial of Access to Communications: Such attacks includes cutting of communication wire, jamming radio communications, flooding a system with junk mail. Threats to network security: It may be of following types: • Snooping: It refers to unauthorized access to someone else’s data, email or computer activity. • Eavesdropping: It refers to unauthorized listening / intercepting someone else’s private communication / data/ information. •

Standards: Standards refers to an established set of rules or requirements which are approved by recognized body or widely used across various software platforms. For ex.: PDF (Portable documents format) is a technical standard widely used by the industry. They are of two types: Proprietary Standards and Open Standards. Proprietary standards are those for which users have to buy license to use them. For e.g. MS Office format .doc, .ppt, .xls etc Open Standards are internationally accepted technical standards that guarantee that data can be exchanged across platforms and for any applications. Open is feely open to all. Advantages of Open Standards:  Making the data accessible to all.  It ensures data is application and platform independence.  Diversity and Interoperability in the Industry i.e. it enables business and people to go for any technology of their choice as per their needs and budget. E.g.: ASCII Characters, HTML file, Joint Photographic Expert Group, Portable Network Graphic etc. Ogg Vorbis: • It is a new audio compression which is open format developed by Xiph.org. It is roughly comparable to mp3, mpeg-4 formats and is completely free, open and unpatented. Hence it imposes no restrictions on its usage, types of usage, distributions, redistribution etc. Indian Language Computing: • Indian Language computing refers to ability to interact in diverse Indian language on electronic system. How to represent character in Memory? • ASCII: American Standard Code for Information Interchange is widely used alphanumeric code in most microcomputers and minicomputers and in many mainframes. It is 7 bit code hence it can represent standard 27 =128 characters. ISCII: • Indian Standard Code for Information Interchange (ISCII) is an eight bit code capable of coding 256 characters. It retains all ASCII characters and also offers coding for Indian Scripts. Transliteration: • When we type Indian Language words phonetically in English script and tool will automatically convert them into corresponding language words called as transliteration. Unicode • Unicode provides a unique number for every character, no mater what the platforms, no matter what the program, no matter what the language. Unicode can represent 94140 characters. Unicode standard has incorporated Indian Scripts under the group named Asian scripts. Indian

scripts included as Devnagari, Bengali, Gurumukhi, Gujarati, Oriya, Tamil, Telgu, kannada, and Malayalam. Fonts: • A Font refers to a set of displayable text characters called glyphs, having specific style and size. There are two categories of font: True Type Font and Open Type Font. • True Type Font: It is developed by Apple and licensed to Microsoft. It is 8 bit font which is compatible with Microsoft Windows and MAC OS. • Open Type Font: It is the extension of the True Type Font Format which is 16 bits font and support 65536 characters (Unicode characters). Indian Language Text Entry: Many Tools / software have been developed to facilitate the typing of Indian Language text. There are two types text entries: • Phonetic Text Entry: Words typed as per their pronunciation in English script and later on converted to Corresponding (Hindi/Gujarati) language work is known as phonetic text entry. • Key map based text entry: When you type text from a keyboard having key mapping of Indian language characters, is known as key map based text entry.

Questions and Answer What is OSS? Open Source Software is a software available with source code and free to change/edit / redistribute and imposed no further restrictions on product or its usage. Q2. Expand the terms: OSI, FLOSS, FSF, GNU, W3C, and PHP. Ans: OSI: Open source Initiative FLOSS: Free Libre and Open Source Software. FSF: Free software Foundation created for the purpose of supporting free Movement. GNU : GNU’s Not Unix Project established with an objective to create a system Compatible to UNIX but not identical with it. W3C: World Wide WEB consortium is responsible for producing the software standards for World Wide Web. PHP: Hypertext Pre-processor is a widely used open source programming language primarily for server side applications and developing dynamic web content. Q3. What is free software? Ans : Free Software means the software is freely accessible and can be freely used, changed, improved, copies and distributed to others. Q4. Define freeware and shareware. Ans The freeware is the software available free of cost and allows copying and further distribution but does not allows modification as its source code is not available. Shareware is as software which is available for redistribution for stipulated time but after some time some license fee is required to be paid. Q5. What is openoffice.org? Ans It is Office an application suite which is free software and directly competes with Microsoft Office. It is compatible with MS Operating System, UNIX, MAC OS. Q1. Ans

Q6. What is font? What is OTF? Ans : A font is a set of displayable or printable text characters having specific style and size. Open Type Font: It is the extension of the True Type Font Format which is 16 bits font and support 65536 characters ( Unicode characters). Q7. What are different font categories?

Ans : There are two categories of font: True Type Font and Open Type Font. True Type Font: It is developed by Apple and licensed to Microsoft. It is 8 bit font which is compatible with Microsoft Windows and MAC OS. Open Type Font: It is the extension of the True Type Font Format which is 16 bits fon and support 65536 characters ( Unicode characters). Q8. Define ODF. Ans : ODF is an Open Document file Format used for exchanging office documents such as memos, reports, spreadsheets, database, charts and presentations. Open document is open, XML based file format used for exchanging office documents such as memos, reports, spreadsheets, database, charts and presentations. Q9. What is key map based text entry? Ans: When you type text from a keyboard having key mapping of Indian Languages characters is known as key map based text entry. Q10. What is Unicode? Ans10: Unicode provides a unique number for every character, no mater what the platforms, no matter what the program, no matter what the language. Unicode can represent 94140 characters. Q11. What is ISCII? Ans : Indian Standard Code for Information Interchange (ISCII) is a coding scheme for representing various writing systems of India. It encodes the main Indic scripts and a Roman transliteration. When we type Indian Language words phonetically in English script and tool will automatically convert them into corresponding language words called as transliteration. Q12. What is Indian Script key map known as? Ans : Key map based text entry: When you type text from a keyboard having key mapping of Indian language characters, is known as key map based text entry.

Unsolved Questions 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

What is open source software? Compare Free software and open source software. Compare OSS and floss. Compare Proprietary software and free software. Compare Free ware and shareware. Compare Freeware and free software Write Short notes on GNU. Write short notes on LINUX. Write Short notes on MOZILLA. Write short notes on APACHE. Write short notes on POSTGRE SQL. Write short notes on PHP. Write short notes on Open Office. What are technological standard and its various categories? Mention some advantages of open standards. What is the significance of Unicode in terms of Indian Language Computing? How phonetic text entry is different from key map based text entry? What is Ogg Vorbis? Why? How to represent character in Memory? What is font and its types?

Chapter 3 PROGRAMMING FUNDAMENTALS Brief Summary of the Chapter: In this chapter we well understand Basics of programming and programming environment tools.

Key Points:IDE- Integrated development Environment: • A programming environment, where all the tools required for programming are available under one roof is called IDE. RAD- Rapid Application Development: • A programming style which aims at building programs fastly through the use of tools and wizards is called RAD.

Token: • 1)

2)

3)

4)

5) •



The smallest individual unit in a program is known as Token. Java has the following types of tokens: keyword, Identifier, literal, punctuators and operators. 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. int, void, private, for, while etc. Literals: These having fixed data values are referred to as Literals. They are also known as Constants. Various types of literals available in Java are : o integer literals o Floating literals o Boolean literals o Character literals o String literals o Null literals Identifiers: These have various names given to the program segments. For example variable name, class name, function name. There are four rules to create Identifers: i) It is a combination of alphabets, numbers, underscore and dollar sign ii) First character must be alphabet or underscore or dollar sign iii) Blank space are not allowed. iv) Reserve words cannot be used as variable name. Operators: Operators are symbols or group of symbols, which represent a operation in java. Operators in java can be classified as Unary operator- operators that require only one operand like ++, -- etc; Binary operator – operator that require two operands like +, - *, > <, == etc.; ternary operator – which require three operands like?:. Other types of operator are : Airthmetic operator, Relational operator and Logical operator. Punctuator or Separator: There are nine separator in Java: () {} [] .; , Escape Sequence: When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. Escape sequences are normally used to control printed or displayed output. For example, \a, \b, \n, \t, etc. Primitive Data Types:The Java programming language is statically-typed, which means that all variables must first be declared before they can be used.A primitive type is predefined by the language and is named by a reserved keyword. The eight primitive data types supported by the Java programming language are: 1. byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum



value of -128 and a maximum value of 127 (inclusive). 2. short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). 3. int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). 4. long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). 5. float: The float data type is a single-precision 32-bit IEEE 754 floating point. 6. double: The double data type is a double-precision 64-bit IEEE 754 floating point. 7. boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. 8. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). Reference Data Types : These are constructed by using primitive data These are constructed by using primitive data types, as per user need. Reference data types types, as per user need. Reference data types store the memory address of an object. Class, store the memory address of an object. Class,Interface and Array are the example of Interface and Array are the example of Reference Data types.

Scope of a Variable: • The part of program where a variable is usable is called scope of a variable. Block: • A group of statement enclosed in pair of parenthesis {} is called block or a compound statement. If Statement: If statement helps to execute a block of statement based on the result of a condition. If the condition set evaluates to true on block of statement is executed otherwise another block is executed. Syntax: if (Expression or condition) { Statement1; Statement2; . . Statementn; } else { Statement1;

Statement2; . . Statementn; } ‘else’ part of ‘if statement’ is optional, if the user doesn’t provide an else part and the condition evaluates to false, then nothing would happen. Complier will not produce an error in this case. Switch Statement: A Switch statement is used execute a statement from a group of statement based on the result of a expression. The expression must result in either of byte, short, integer or character. Syntax: Switch(Expression) { case 1: statement(s); break; case 2: statement(s); break; …… …… case n: statement(s); break; default: statement(s); } The default statement is executed when none of the above mention case matches with the result of the switch expression. Default is optional. Loop/Iteration: • loop or iterations helps to repeat a group of statements number of times under a condition. Java supports three kinds of loop: while loop, for loop, do while loop Entry control loop / Pre-Tested loop/ Top-Tested loop: • An entry control loop first test the terminating condition and then executes the loop body. If the condition is found true the loop body is execute other wise the loop terminates. In case if the condition is false in first time only then the loop will not get execute even once. Exit control loop / Post-Tested loop/ Bottom-Tested loop: • An exit control loop first executes the loop body and then test the terminating condition. If the condition is found true the loop body executed again other wise the loop terminates. In case if the condition is false in first time only then the loop will still get execute at-least once. While loop: It is an entry control loop Syntax: Initialization; while (condition) { statement(s); increment; } for loop: It is a compact entry control loop, which all the tree parts of the loop (i.e. initialization, terminating condition, and increment/decrement of the counter variable) exists in a single line. Syntax: for(initialization ; terminating condition ; increment/decrement) { Statement(s); (Body of the loop) }

It is to be noted that all the parts of the loop in the above statement are optional. In case if a programmer wants to specify more than one initialization or increment/decrement then it has to be separated by (,). for(int i=1; i<= 10; i++) for(i=1, j = 10; i= 1 && j<= 30 ; i-- , j++) // more than one condition joined using && for(; i<= 10; i++) //initialization missing still using ; for(; i<= 10;) //initialization, inc./dec. missing still using ; do while loop: it is a exit control loop Syntax: Initialization; do { statement(s); } while (condition); Break Statement: • break is used to terminate the current switch statement or the loop. Continue Statement: • Continue statement skips the remaining part of the current loop and begins the next iteration of the loop.

Commonly available Swing Controls in Java: jFrame: jLabel: jTextField: jbutton: jList: jComboBox: jPanel: jRadioButton: jCheckBox: jPasswordField: jTextArea:

A Frame is a container control, in which all the controls can be place. JLable allows placing un-editable text on the Frame/Panel JTextFiled allows placing editable text on the Frame/Pane. User can enter text in a textFiled during runtime. is used to initiate an action when it is clicked. is a group of values or items from which one or more selections can be made. jComboBox is similar to jList but also allow to enter editable text during run time. It is a combination of jTextFiled and jList. Act like a frame, to group one or more controls. Allow us to choose a single item from a group of jRadioButton options. Allow us to choose one or more items from a group of jCheckBox options. Allow us to enter a text during the run time but shows an encrypted text instead of the original text JTextArea is a multi-line text component to enter or edit text.

Questions and Answers Q1. Ans. Q2. Ans

Q3. Ans.

Name any two Object Oriented Programming languages? C++ and Java Why is java called a platform independent language? Java program can be easily moved from one computer system to another, anywhere anytime. Changes and upgrade in operating system, processors and system resources will not force any change in the Java program. Hence it is called a platform independent language. Elaborate the java Compilation process. The source program is first converted into a byte code using a java compiler. This byte code is machine independent i.e. same for all the machines. Later the byte code is executed on the machine using an interpreter.

Q4. Ans.

Why do we write a comment in a program? What are the two ways of writing comment in a java Program? Comments are added to a program for the following purposes:1. Make the more readable and understandable 2. For future references we can add comments in a Java program in the following ways: i) Adding // before the line which is to be commented. This can be used only for single

line comments. Q5. Ans.

Q6. Ans.

Q7. Ans. Q8. Ans. Q9. Ans.

Q10. Ans. Q11. Ans.

Q12. Ans.

Q13.

ii) using a pair of /* and */ for multi-line comments. What is a syntax error in context of a program? Give an example. Error in the way of writing a statement in a program, results in a syntax error. For e.g. for ( i=0, i<=100. i++), will result in a syntax because the program has written comma instead of a semi comma in the for loop. What is RAD programming? Why is program development in java using Netbeans IDE is RAD? RAD stands for Rapid Application Development. A programming style which aims at building programs fastly through the use of tools and wizards is called RAD. Program development using Netbeans IDE is RAD as it • provides GUI • Provides online help and suggestions during typing of the program (using ctrl+ Spacebar key) • Error alerts while typing of the program. What is IDE? Name two IDE for Programming in java. A programming environment, where all the tools required for programming are available under one roof is called IDE. Two IDE for Java are Netbeans and BlueJ Name any two type of Tokens available in Java. Keyword, Identifier, Literal, Punctuators ad Operators. What are primitive data types? Name the various primitive data type available in Java. Data types that are directly available with java are called primitive data type. Various primitive data types available in java are byte, short, int, long, float, double, char and boolean. What are Reference data types? Data types created by the programmer using the primitive data type are called reference data type e.g. Classes, interfaces etc. What is type casting? Converting a value form one type to another is called type casting. For e.g. int a = 5 . here ‘a’ is a integer, which can be cased to float as follows float b = (float) a; Name and explain the usage of any two data types used in Java to store numbers with decimals. Two data types available in java for storing numbers with decimals are 1. float: for single precision floating point values for e.g. float num = 10.0F 2. double: for double precision floating point value. This is the default data type for decimal numbers. for e.g. double num = 10.0 What are Keywords? Give two examples of keywords available in Java.

Keywords are words that have a specific predefined meaning in Java. They cannot be used as variable names. Eg. void, private, if, while etc. Q14. Name and explain the usage of any one relational and one logical operator in Java. Ans. One relational operator in java is ==. This operator results in true if both its operands are equal otherwise false. One logical operator in java is &&. This operator is used to combine two logical values. The result of the && will be true if and only if both its operands are true otherwise false. Q15. What is the difference between = and == operator in java? Ans. Represent an assignment operator. It sets the value of the variable on its left side with the result of expression on its right side. == represent a conditional equal to operator. It checks for

Ans.

the equality of both its operands. If both the operands are equal, condition evaluates to true otherwise to false. Q16. Name the two type of selection statement available in Java. Ans. Two selection statement available in java are ‘if’ and ‘Switch’ Q17. Write the purpose of Switch Statement with the help of an example. Which Java Statement can be used in place of switch statement? In the switch statement, what happens if every case fails and there is no default option? Ans. A Switch statement is used execute a statement from a group of statement based on the result of a expression. The expression must result in either of byte, short, integer or character. An ‘if statement’ can be used in place of switch statement. In a switch statement if none of the statement satisfies and even there is no default case then nothing would happen. This would not result in any sort of error. Q18. What is the purpose of ‘break’ statement in java? Ans. Break is used to terminate the current switch statement or the loop. Q19. What is the purpose of ‘continue’ statement in java? Ans. Continue statement skips the remaining part of the current loop and begins the next iteration of the loop. Q20 Find the output of the following code snippet written in java public static void main(String [ ]args) { long a=78345,s1=0,s2=0,r; while(a>0) { r=a%10; if (r%4==0) s1+= r; else s2+=r; a/=10; } System.out.println("S1 ="+ s1); System.out.println("S2 ="+ s2); } Ans. Output: s1= 12 s2= 15 Q21. Correct the errors in the following program segment written in JAVA. You are just required to write the corrected code, underlying the corrections made. public Static Void Main (String [] args) { Integer Nos = 100; while (Nos => 45) { If (Nos % 5 = 0); Nos+=10; otherwise Nos + = 20; } } Ans: Corrected Code public static void main (String [] args) { int Nos = 100; while (Nos >= 45)

{ if (Nos % 5 == 0)_ Nos+=10; else Nos + = 20; } }

Unsolved Questions 1.

What will be output of the following code: byte b; double d= 417.35; b= (byte) d; system.out.println(b);

2. 3.

4.

5.

6.

7.

8.

Given the value of a variable, write a statement, without using if construct, which will produce the absolute value of a variable. What is wrong with the following code fragment? Switch (x) { case 1: n1= 10; n2= 20; case 2: n3=30; break; n4= 40; } What will be the output of the following program code? int m = 100; int n = 300; while(++m < --n); System.out.println(m+” “+ n); What does the following fragment display String s = “Six:” + 3+ 3; System.out.println(s); What is the output of the following code? String s = new string(); System.out.println(“s = “ + s); What will be the output of the following code snippet? int x= 10; int y = 20; if ((x 10) System.out.println(x); else System.out.println(y); State the output of the following program: public static void main(String args[ ]) { int x = 10; int y = 15;

System.ou.println((x>y)? 3.14: 3); } 9. State the output of the following program: public static void main(String args[ ]) { int x = 10; float y = 10.0; System.ou.println((x>y)? true: false); } Given a pacakage named EDU.student, how would you import a class named Test contained in this package? Write one line statement. Consider the following class definition: Class Student { abstract double result( ) } This code will not compile since a keyword is missing in the first line. What is the keyword? Can an abstract method be declared final? Yes or No.

10. 11.

12.

CHAPTER-4 JAVA GUI PROGRAMMING REVISION TOUR – II [Swing Controls]

Brief Summary of the Chapter: In this chapter we shall be revising the JAVA GUI programming concepts using Swing API through NetBeans IDE.Java GUI applications are created through RAD tools with Classes, Object and methods etc. Key Points: •

Swing API includes graphical components for building GUIs.



Swing components can be either container or non container component.



Swing provide seven different Layout manager.



Frame is a top level window with a title and a border, created through jFrame component of Swing.



Common properties of buttons are: background, border, font, foreground, enabled, Horizontal Alignment, Vertical Alignment.



Label control displays text, that the user can not changed directly.



Label is created through jLabel class component.



TextField is created through jTextField class component.



Password field takes input without showing it on the screen, created through jPasswordField class component.



TextArea is multiline component to display or enter text, created through jTextArea class component.



Checkbox is a rectangular area that can be chacked or unchecked created through jCheckBox class component. SOLVED QUESTIONS

1.What does getPassword() on a password field return? (a) a string (b) an integer (c) a character array. Ans: (c) a character array 2. Which of the following component is the best suited to accept the country of the user? A. List B. Combo box C. Radio button D. Check box Ans: B. Combo box 3. What command do you need to write in actionPerformed() event handler of a button, in order to make it exit button? a. System.out.println(); b. System.exit(0); c. System.out.print() Ans: b. System.exit(0); 4.What method would you use, in order to simulate a button’s(namely Okbtn) click event, without any mouse activity from user’s side? a. Okbtn.setText() b.Okbtn.getText() c. Okbtn.doClick() Ans: Okbtn.doClick() 5. What would be the name of the event handler method in the ListSelection listener interface for a list namely CheckList to handle its item selections? a. CheckListValueChanged() b. getSelectedValue() c. clearSelection() Ans: a. CheckListValueChanged() 6. Which control displays text that the user cannot directly change or edit? a.TextField b. Checkbox c. Combobox d. Label Ans: d.Label 7.Which control provides basic text editing facility? a.TextField b. Checkbox c. Combobox d. Label Ans: a. TexfField 8. Occurrence of an activity is called: a. Function b. Class c. Object d. Event Ans: d.Event. 9. Which property is used to set the text of the Label? a. font b.text c.name d. icon Ans: b.text 10. The object containing the data to be exhibited by the combo box by which property. a. editable b. model c.selectedIndex d.selectedItem Ans: b. model 11. What is GUI programming? Ans: A GUI(Graphical User Interface) is an interface that uses pictures and other graphic entities along with text, to interact with user. 12. How is swing related to GUI programming?

Ans: We can create a GUI application on Java platform using Swing API (Application Programming Interface), which is part of Java Foundation Classes(JFC). 13. What is an event? What is event handler? Ans: An event is occurrence of some activities either initiated by user or by the system. In order to react, you need to implement some Event handling system in your Application. Three things are important in Even HandlingEvent Source: It is the GUI component that generates the event, e.g. Button. Event Handler or Event Listener: It is implemented as in the form of code. It receives and handles events through Listener Interface. Event Object or Message: It is created when event occurs. It contains all the information about the event which includes Source of event and type of event etc. 14. What is the default name of action event handler of a button namely TestBtn? Ans: private void TestBtnActionPerfomed(java.awt.action.ActionEvent evt){ }. 15. What property would you set to assign access key to a button? Ans: mnemonic property is used to assign access key or shortcut (Alt + Key). 16. Which method can programmatically performs the click action of a push button? Ans: private void TestBtnActionPerfomed(java.awt.action.ActionEvent evt){ }. 17. Which property would you set the setting the password character as ‘$’? Ans:echoChar 18. Which method returns the password entered in a password field? Ans: char [] getPassword(). 19. Which list property do you set for specifying the items for the list. Ans: model 20. Which method would you use to determine the index of selected item in a list? Ans: int getSelectedIndex(). 21. Which method would you use to insert an item at specified index, in the list? Ans: void setSelectedIndex( int index). 22. How you can determine whether 5th item in a list is selected or not? Ans: isSelectedIndex(4). 23. Which method you would use to insert ‘Hello’ at 10th position in the Text Area control. Ans:void insert(“Hello”, 9). 24. Which method you would like to use to insert an Icon (picture) on a Push Button. Ans: void setIcon(Icon). 25. Which property would you like to set to make a Combo box editable? Ans: editable. 26. What is Layout Manager? Name the layout managers offered by NetBeans? Ans: Layout managers enable you to control the way in which visual components are arranged in GUI forms by determining the size and position of components within containers.

There are seven types of layout are available– • Flow Layout • Grid Layout • Card Layout • Spring Layout • Border Layout • GridBag Layout • Box Layout 27. Name three commonly used properties and methods of the following controls. (a) text field (b) text area (c) Check Box Ans: (a) Properties: text, font, editable. Methods: void setText(), String getText(), void setEditable(boolean). (b) Properties: enabled, editable, wrapStyleWord Methods: setText(), getText(), isEditable() (c) Properties:font, text, selected . Methods: getText(), isEnabled(), isSelected(). 28. What is dispose() used for ? Ans: dispose() is used for hide and dispose of the frame when the user closes it. This removes the frame from the screen and frees up any resources used by it. 29. What is the difference between(a) Text field & Text area (b) Text field & password field (c) Radio Button & Check Box Ans: (a) A text field’s text property can hold single line of text unless it is an HTML text. While a text area’s text can hold any number of lines of text depending upon its rows property. (b) Though a text field and a password field can obtain a single line of text from the user, yet these are different. A password field displays the obtained text in encrypted form on screen while text field displays the obtained text in unencrypted form. (c) Radio Button: A jRadioButton control belongs to JRadioButton class of Swing controls. It is used to get choices from the user. It is grouped control, so that only one can be selected at a time among them. Radio Button works in group, so that they must be kept in a ButtonGroup container control like so that only one can be selected at the same time. Some features of jRadioButton control are It can be used to input choices typed input to the application.  Only one Radio button can be selected at a time.  They must be kept in a Button Group container control to form a group. Check box: A jCheckBox control belongs to JCheckBox class of Swing controls. It indicates whether a particular condition is on or off. You can use Check boxes to give users true/false or yes/no options. Check Boxes may works independently to each other, so that any number of check boxes can be selected at the same time. Some features of jCheckBox control are It can be used to input True/False or Yes/No typed input to the application.  Multiple check boxes can be selected at the same time. 30. What is the significance of following properties of a text area ?

(a) lineWrap (b) wrapStyleword Ans: (a) Defines Wrapping featureenable/disable (b) Determines where line wrapping occurs. If true, the component attempts to wrap only at word boundaries. This property is ignored unless linewrap is set to true. 31. What is the significance of a button group? How do you create a button group? Ans: We must add a ButtonGroup control to the frame to group the check boxes by using Button Group property of the check box. By dragging buttongroup control from palette window. 32. What do you understand by focus? Ans: A Focus is the ability to receive user input/response through Mouse or Keyboard. When object or control has focus, it can receive input from user. An object or control can receive focus only if its enabled and visible property are set to true. Most of the controls provides FOCUS_GAINED() and FOCUS_LOST() method in FocusEvent by the FocusListener. FOCUS_LOST() is generally used for validation of data. You can give focus to an object at run time by invoking the requestFocus() method in the code. Ex. jTextBox2.requestFocus(); 33. What is meant by scope of a variable? Ans: In Java, a variable can be declared any where in the program but before using them. The area of program within which a variable is accessible, known as its scope. A variable can be accessed within the block where it is declared. { int x=10; if (a>b) { int y=5; ………… Scope of x and y } else { int z=3; ……. Scope of z } ………. } 34. Create a Java Desktop Application to find the incentive (%) of Sales for a Sales Person on the basis of following feedbacks: Feedback Incentive (%) Maximum Sales 10 Excellent Customer Feedback 8 Maximum Count Customer 5 Note: that the sales entry should not be space.Calculate the total incentive as :Sales amount* Incentive. The feedback will be implemented in JCheckBox controls.Using a JButton’s (Compute Incentive) click event handler,display the total incentives in a JTextField control. Assume the nomenclature of the swing components of your own. Note that the JFrame from IDE window will be shown as given:

Ans:- private void btnIncActionPerformed (java.awt.ActionEvent evt) { int sales = 0; if (! txtSales.getText( ).trim( ).equals( “”)){ sales-Integer.parseInt(txtSales.getText( ).trim ( )); } double incentive = 0.0; if (jCheckBox1.isSelected ( )) { incentive = incentive + 0.1; } if (jCheckBox2.isSelected ( )) { incentive = incentive + 0.8; } if (jCheckBox3.isSelected ( )) { incentive = incentive + 0.05; } txtInc.setText ( “ “ + Math.round(sales * incentive)); } 35. Assume the following interface built using Netbeans used for bill calculation of a ice-cream parlor. The parlor offers three verities of ice-cream – vanilla, strawberry, chocolate. Vanilla icecream costs Rs. 30, Strawberry Rs. 35 and Chocolate Rs. 50. A customer can chose one or more ice-creams, with quantities more than one for each of the variety chosen. To calculate the bill parlor manager selects the appropriate check boxes according to the verities of ice-cream chosen by the customer and enter their respective quantities. Write Java code for the following: a. On the click event of the button ‘Calculate’, the application finds and displays the total bill of the customer. It first displays the rate of various ice-creams in the respective text fields. If a user doesn’t select a check box, the respective ice-cream rate must become zero. The bill is calculated by multiplying the various quantities with their respective rate and later adding them all. b. On the Click event of the clear button all the text fields and the check boxes get cleared. c. On the click event of the close button the application gets closed.

Ans: (a) private void jBtncalculateActionPerformed(java.awt.event.ActionEvent evt) { if(jchkStrawberry.isSelected()==true) jTxtPriceStrawberry.setText("35"); else { jTxtPriceStrawberry.setText("0"); jTxtQtyStrawberry.setText("0"); } if(jChkChocolate.isSelected()==true) jTxtPriceChocolate.setText("50"); else { jTxtPriceChocolate.setText("0"); jTxtQtyChocolate.setText("0"); } if(jChkVinella.isSelected()==true) jtxtPriceVinella.setText("30"); else { jtxtPriceVinella.setText("0"); jTxtQtyVinella.setText("0"); } int r1,r2,r3,q1,q2,q3,a1,a2,a3,gt; r1=Integer.parseInt(jTxtPriceStrawberry.getText()); r2=Integer.parseInt(jTxtPriceChocolate.getText()); r3=Integer.parseInt(jtxtPriceVinella.getText()); q1=Integer.parseInt(jTxtQtyStrawberry.getText()); q2=Integer.parseInt(jTxtQtyChocolate.getText()); q3=Integer.parseInt(jTxtQtyVinella.getText()); a1=r1*q1; jTxtAmtStrawberry.setText(""+a1); a2=r2*q2; jTxtAmtChocolate.setText(""+a2); a3=r3*q3; jTxtAmtVinella.setText(""+a3); gt=a1+a2+a3; jTxtTotalAmt.setText(""+gt); }

Ans.(b) private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt) { jTxtPriceStrawberry.setText(""); jTxtPriceChocolate.setText(""); jtxtPriceVinella.setText(""); jTxtQtyStrawberry.setText(""); jTxtQtyChocolate.setText(""); jTxtQtyVinella.setText(""); jTxtAmtStrawberry.setText(""); jTxtAmtChocolate.setText(""); jTxtAmtVinella.setText(""); jchkStrawberry.setSelected(false); jChkChocolate.setSelected(false); jChkVinella.setSelected(false); } Ans: (c) private void jBtncloseActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } 36. Read the following case study and answer the questions that follow. TeachWell Public School wants to computerize the employee salary section. The School is having two categories of employees : Teaching and Non Teaching. The Teaching employees are further categorized into PGTs, TGTs and PRTs having different Basic salary. The School gives addition pay of 3000 for employees who are working for more than 10 years.

Employee Type

Basic

DA (% of Basic Sal)

HRA (% of Basic Sal)

Salary

Deductions (% of Basic sal)

Non Teaching

12500

31

30

12

PGT

14500

30

30

12

TGT

12500

21

30

12

PRT

11500

20

25

12

(a) Write the code to calculate the Basic salary, deductions, gross salary and net salary based on the given specification. Add 3000 to net salary if employee is working for more than 10 years.

Gross salary=Basic salary + DA + HRA Net salary = Gross salary – deductions (b)Write the code to exit the application. (c)Write the code to disable textfields for gross salary, deductions and netsalary. Ans: (a) double bs=0,da=0,net=0,ded=0,gross=0,hra=0; if (rdnon.isSelected()==true) { bs=12500; da=(31*bs)/100; hra=(30*bs)/100; ded=(12*bs)/100; } else if (rdpgt.isSelected()==true) { bs=14500; da=(30*bs)/100; hra=(30*bs)/100; ded=(12*bs)/100; } else if (rdtgt.isSelected()==true) { bs=12500; da=(21*bs)/100; hra=(30*bs)/100; ded=(12*bs)/100; } else if (rdprt.isSelected()==true) { bs=11500; da=(20*bs)/100; hra=(25*bs)/100; ded=(12*bs)/100; } gross=bs+da+hra; net = gross – ded; if(chk10.isSelected()==true) { net=net+3000; } tfded.setText(“ ”+ded); tfgross.setText(“ ”+gross); tfnet.setText(“ ”+net); tfbs.setText(“ ”+bs); Ans:(b) System.exit(0); Ans:(c) tfgross.setEditable(false); tfded.setEditable(false); tfnet.setEditable(false);

37. ABC School uses the following interface built in java to check the eligibility of a student for a particular stream from science, commerce and humanities. The user first enters the total percentage and selects the desired stream by selecting the appropriate option button. An additional 5% is marks is given to students of NCC. Write Java Code for the following a. On Action event of the button ‘Calc Percentage’ Net percentage of the student is calculated and displayed in the appropriate text filed. Net percentage is same as that of the actual percentage if the student doesn’t opts for NCC otherwise 5% is added to actual percentage. b. On Action event of the button ‘Result’, the application checks the eligibility of the students. And display result in the appropriate text field. Minimum percentage for science is 70, 60 for commerce and 40 for humanities. c. On the Click event of the clear button all the text fields and the check boxes get cleared. d. On the click event of the close button the application gets closed.

Ans: a. private void jBtnCalcPerActionPerformed(java.awt.event.ActionEvent evt) { int p; p=Integer.parseInt(jTextField2.getText()); if (jCheckBox1.isSelected()) p=p+5; jTextField3.setText(Integer.toString(p)); } b. private void jBtnResultActionPerformed(java.awt.event.ActionEvent evt) { int p; p=Integer.parseInt(jTextField3.getText()); if( jRadioButton1.isSelected()) { if ( p>=70) jTextField4.setText(“Eligible for all subject”); else jTextfield4.setText(“Not Eligible for science”); } else if( jRadioButton2.isSelected()) {

if ( p>=60 ) jTextField4.setText(“Eligible for Commerce and Humanities”); else jTextfield4.setText(“Not Eligible for Science and Commerce”); } else { if ( p>=40 ) jTextField4.setText(“Eligible for Humanities”); else jTextfield4.setText(“Not Eligible for any subject ”); } } c. private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt) { jTextField1.setText(“ “) OR jTextField1.setText(null) jTextField1.setText(“ “) OR jTextField1.setText(null) jTextField1.setText(“ “) OR jTextField1.setText(null) jTextField1.setText(“ “) OR jTextField1.setText(null) jCheckbox1.setSelected(false); } d. private void jBtnCloseActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } Unsolved Questions: 1. Describe the relationship between properties, methods and events. 2. What is container tag? 3. What does a getPassword() method of a password field returns? 4. What will be the contents of jTextArea1 after executing the following statement: 1 5. jTextArea1.setText("Object\nOriented\tProgramming"); 6. What is difference between jRadioButton and jCheckBox? 7. What does a JList fire when a user selects an item? 8. What is Layout Manager? Discuss briefly about layout managers offered by NetBeans? 9. Name three commonly used properties and methods of the following controls. 10. (a) text field (b) text area (c) label (d) Check Box (e) button. 11. What is dispose() used for ? 12. What is the difference between13. (a) Text field & Text area 14. (b) List & Combo 15. (c) Radio Button & Check Box 16. What is the significance of following properties of a text area ? 17. (a) lineWrap (b) wrapStyleword 18. What is the significance of a button group ? How do you create a button group ? 19. Discuss about some commonly used properties of lists and a combo boxes. 20. What methods obtains the current selection of a combo box ? Give a code example. 21. The FOR U SHOP has computerized its billing. A new bill is generated for each customer. The shop allows three different payment modes. The discount is given based on the payment mode.

Credit Card Type Shopping Amount Discount Cash

Cheque

Credit Card

< 10000

20 %

>= 10000

25 %

< 15000

10 %

>= 15000

15 %

< 10000

10 %

>= 10000

12%

a) Write the code for the CmdClear Button to clear all the Text Fields. b) Write the code for the CmdCalc Button to display the Discount Amount and Net Price in the TxtDisc and the TxtNet Text Fields respectively. CHAPTER-5 JAVA GUI PROGRAMMING REVISION TOUR – III [Methods etc.]

Brief Summary of the Chapter: In this chapter concept related with Class, Objects, Constructors and methods are discussed. In Java method or function is a sequence of some declaration and executable statements. In Java, which is strictly Object-oriented, any action can take place through methods and methods have to be exist as a part of the class. Key points: •

Methods is a sequence of statements that carry out specific tasks.



Methods returns a value through return statement.



Class is a blue print for creating objects of a certain charactersticks.



Class contains fields and methods.



Classes created through keyword class.



Object is instance of a class created through new operator.



Constructor is method with the same name as of that class it is used to initialized object of class.



Constructor can either be parameterized or non-parameterized.



The “this” keyword is used to refer to current object.

SOLVED QUESTIONS 1. In java, methods reside in __________. (a) Function (b) Library (c) Classes (d) Object Ans: (c) Classes 2. The number and type of arguments of a method are known as _____________. (a) Parameter list (b) Calling (c) Definition (d)None to these. Ans: (a) Parameter list 3. The first line of method definition that tells about the type of return value along with number and type of arguments is called_____________.

(a) Class (b) Object (c) Prototype (d) Datatype Ans: (c) Prototype 4. A member method having the same name as that of its class is called______method. (a) Destructor (b) Constructor (c) Object (d) Variable Ans: (b) Constructor 5. A constructor method has__________return type. (a) float (b) void (c) no (d) int Ans: (c) no 6. A_________constructor takes no arguments. (a) Copy constructor (b) Non-Parameterized constructor (c) Parameterized constructor Ans: (b) Non-Parameterized constructor 7. A_________constructor creates objects through values passed to it. (a) Copy constructor (b) Default constructor (c) Parameterized constructor Ans: (c) Parameterized constructor 8. The keyword_________refers to current object. (a) void (b) goto (c) this (d) null Ans: (c) this 9. Define a method. What is method prototype and signature? Ans:A message to an object is a call to the object’s method requesting that it performs some specified action. int absval(int a) { return(a<0?-a:a); } The first line of the method definition is the prototype of the method i.e. the prototypes of method defined above is: int absval(int a) 10. How are following passed in Java: (i) primitive types (ii) reference types? Ans: (i) By Value (ii) By reference 11. The String objects being reference types are passed by reference but changes, if any, are not reflected back to them. Why? Ans: The String objects are immutable in Java, which means once they are created, the cannot changed. That is why, even though Strings are passed by reference, they cannot be changed. 12.At what time is the constructor method automatically invoked? Ans: Every time an object is created, the constructor method is automatically invoked. 13. What are Composite and user defined data types? Ans: The data types that are based on fundamental or primitive data types, are known as Composite Datatypes. Since these data types are created by users, these are also known as User Defined Datatypes. 14. Can you refer to a class as a composite type/ user-defined type? Ans: Yes, class is referred to as a composite type/user defined type. 15.How is a constructor invoked? Ans: A constructor is automatically called with a new operator in order to create a new object. 16. Which method of a class is invoked just once for an object? When? Ans: The constructor method. It is invoked for initializing values of the object at the time of its creation. 17. Passing the address means call by value or call by reference? Ans: Call by reference. 18. What’s wrong with the following constructor definition for the class PlayInfo? public void PlayInfo( int sticks) {

nsticks = sticks; } Ans: A constructor cannot have a return type, not even void. 19. How many values can be returned from a method? Ans: Only one value can be returned from a method though a method can have multiple return statements but only one gets executed which is reached first and thus returns the value. 20. What do you understand by Class and Object? Ans: The basic unit of OOP is the Class. It can be described as a blue print of Objects. In other words, an Object is an instance of a class. A JAVA program may have various class definitions. An Object is an entity having a unique Identity, characteristics (Properties) and Behavior (Methods). 21. How to declare a class in Java? Ans: In Java a Class is declared/definedby using class keyword followed bya class name. For example: public class Student { String Name; int RollNo; String FName; String DOB; void getAdmission() {…………………… …………………… } oid getTransfer() {…………………… ………………….. } oid feeDeposit() { ……………….. ……………….. } } 22. What is the difference between instance and static variable? Ans: Instance Variable- These data member are created for every object of the class i.e. replicated with objects. Class variable (static)- These data members that is declared once for each class and all objects share these members. Only a single copy is maintained in the memory. These are declared with static keyword. 23. What do you understand by constructor in OOP? Ans: A Constructor is a member method of a class, used to initialize an Object, when it is created (instantiated). 24.What are the properties of Constructor? Ans: There are some properties of constructor: • A Constructor must have the same name as the class name and provides initial values to its data members. • A constructor have no return type not even void. • JAVA automatically creates a constructor method, if it is not defined with default values. 25.What do you understand by methods? What are the advantages of methods? Ans: Definition: A Method or function is sequence of statement which are written to perform a specific job in the application. In Object Oriented Programming, Method represents the behavior of the object. A message can be thought as a call to an object’s method. The following three advantages/reasons describes that why we use methods. To cope with complexity:

When programs become more complex and big in size, it is best technique to follow “Divide and conquer” i.e. a complex problem is broken in to smaller and easier task, so that we can make it manageable. Some times it is also called Modularization. Hiding Details: Once a method is defined, it works like a Black-box and can be used when required, without concerning that “How it Works?” Reusability of code: Once a method is implemented, it can be invoked or called from anywhere in the program when needed i.e. Method can be reused. Even a packaged method may be used in multiple applications. This saves our time and effort. Most of the method like Math.sqrt() is available as ready to use which can be used anywhere in the application. 26. How to define a method? Ans: A method must be defined before its use. The method always exist in a class. A Java Program must contain a main() method from where program execution starts. The general form of defining method is as[Access specifier] () {……………. ; body of the method i.e. statement (s); } Access Specifier: It specified the access type and may be public or protected or private. Return Type: Specifies the return data type like int, float etc. Void is used when nothing is to be returned. Method Name: Specified the name of method and must be a valid Java identifier. Parameters List: It is list of variable(s), also called Formal Parameter or Argument, which are used to catch the values when method is invoked. Also a method may have no parameters. 27.What are the way to pass values to methods in Java? Ans: You can pass arguments (Actual parameters) to method (Formal Parameters) using valid data types like int, float, byte, char, double, boolean etc. or Reference data type like Object and Arrays. A method can called in two ways – Call by Value: In this method, the values of Actual parameters are copied to Formal parameters, so any changes made with Formal parameters in Method’s body, will not reflected back in the calling function. The original value of Actual parameters is unchanged because the changes are made on copied value. Call by Reference: In Reference method, the changes made on the formal parameters are reflected back in the Actual parameters of calling function because instead of values, a Reference (Address of Memory location) is passed. In general, all primitive data types are passed by Value and all Reference types (Object, Array) are passed by Reference.. 28. Differentiate between constructor and method. Ans: Though Constructor are member method of the class like other methods, but they are different from other method membersConstructor creates (initializes) an Object where a method is a group of statements which are packaged to perform a specific job. Constructor has no return type, even void also. Whereas method may have any return type including void. The Constructor has the same name as Class, but method may have any name except Class name. It is called at the time of object creation, but a method can be called any time when required.

29. What is “this” keyword? Ans: As you are aware that static data and method members of a class is kept in the memory in a single copy only. All the object are created by their instance variables but shares the class variables (static) and member methods. public class test { int x, y; static int z; static method1() {………………} static method2() {………………} } Suppose method2() is changes X data member, then big question arises that which object’s x variable will be changed? This is resolved by using ‘this’ keyword. The keyword ‘this’ refers to currently calling object. Instead of using object name, you may use ‘this’ keyword to refer current object. Ex. this.method2() 30. How can we use a class as a composite data type? Ans: Since a class may have various data members of primitive data types like int, float, long etc. In general class may be assumed as a bundle of primitive data types to make a user-defined composite data type. // use of class as composite data type class date { byte dd, mm, yy; public date( byte d, byte m, byte y) { dd= d; mm= m; yy= y; }v oid display() {system.out.println(“”+dd+”/ ”+mm+”/ ”+yy); } }; date DOB = new date(13,2,1990); UNSOLVED QUESTIONS 1. How are parameterized constructors different from non-parameterized constructors? 2. List some of the special properties of the constructor methods. 3. Differentiate between Instance member and static members of a class. 4. What do you mean by actual and formal parameters of a method? Explain with an example. 5. Identify the errors in the method skeletons given below: (1) float average (a, b) { } (2) float mult (int x, y) { } (3) float doer (int, float = 3.14) { } 6. Given the method below write an ActionPerformed event method that includes everything necessary to call this method. int thrice (int x) { return (a * 3) ; }

CHAPTER-6 MORE ABOUT CLASSES AND LIBRARIES

Brief Summary of the Chapter: In this chapter the way access of members of a class i.e. about access specifier will be discuss. Java include predefined classes in the form of packages which are also called Java class Library. Some of the used packages are: java.lang. java.util, java.io, java.swing. java.awt, java.applet etc. Key points: •

The public member of object are accessed through .(dot) operator.



The private members are accessible only inside their own class.



The protected members are accessible inside their own class, sub class and packages.



The default members are accessible inside their own class as well to classes in the same package.



Related classes and interfaces are grouped together in the form of package.



Packages and class are imported through import command. SOLVED QUESTIONS

1. Which keyword can protect a class in a package from accessibility by the classes outside the package? (a)private (b)protected (c) final (d) None of these Ans: (d) None of these. 2. We would like to make a member of a class visible in all subclasses regardless of what package they are in. Which one of the following keywords would achieve this? (a)private (b)protected (c) final (d) public (e) None of these Ans: (b) protected. 3. Which of the following keywords are used to control access to a class member? (a) default (b) abstract (c)protected (d) interface (e) public. Ans: (c) and (e) public 4. The public members of objects are accessed through which operator. (a) arrow (b) dot (c) this (d) none of these Ans: (b) dot 5. The private members are accessible only inside their _______class. (a) own (b) sub (c) super (d) none of these Ans: (a) own 6. Which command is used to import packages and their classes? (a) include (b) import (c) public (d) inline Ans: (b) import 7.Which statement is used to create a package in Java? (a) Class (b) super (c) this (d) package

Ans:(d) package 8. In Java, all strings are objects? (a) True (b) False (c) don’t say Ans: (a) True 9. What do you understand by Package in Java? Ans: A group of classes is called package 10.Given a package named EDU. Student, how would you import a class named Test contained in this package? Write one line statement. Ans: import EDU.Student.Test; 11. What will be the output of the following code StringBuffer city = new StringBuffer(“Madras”); StringBuffer string = new StringBuffer(); string.append(new String(city)); string.insert(0,”Central”); string.out.println(string); Ans: CentralMadras. 12. Give the output of the following program: class MainString { public static void main( String agrs[]) { StringBuffer s = new StringBuffer(“String”); if(s.length() > 5) && (s.append(“Buffer”).equals(“x”); System.out.println(s); } } Ans: StringBuffer. 13. What is the output of the following code fragment if “abc” is passed as argument to the func()? Public static void func(string s1) { String s = s1 + “xyz”; System.out.println(“s1=” + s1); System.out.println(“s = “ +s); } Ans: s1= abc s =abcxyz 14.What are the access specifiers in Java? Expalin. Ans: The Access Specifiers control access to members of class from / within Java Program. Java supports various Access Specifiers to control the accessibility of class members. Private : A variable or method declared as private, may not be accessed outside of the class. Only class member can access them, since they are private to others. Protected: Protected members can be accessed by the class members and subclasses (derived classes) and current package, but they are not accessible from beyond package or outside. Public: Class members declared as public, are accessible to any other class i.e. everywhere , since they are public. Package (default): If no any specifier is mentioned, default or friendly access is assumed. Class member may be accessed by any other Class members available in the same package, but not accessible by the other classes outside the package, even subclasses. 15. What do you meant by private, public, protected, package(friendly) access specifiers? Ans: Private Access Specifier Members declared as private are accessible by the members of the same class, since they are private. A private key word is used to specify. //e.g to demonstrate private specifier.// class abc

{ private int p; private void method1() { p=10; system.out.print(“I am Private method”); } } class xyz {………. void method2() { abc x = new abc(); x.p =10; x.method1() ; } } Protected Access Specifier Protected members are accessible by all the classes in the same package and sub-classes (same of different packages). A protected key word is used to specify. Package mypackage; class abc { protected int p; protected void method1() { p=10; system.out.print(“Protected method”); } } class xyz {………. void method2() { abc x = new abc(); x.p =10; x.method1() ; } } Lets another Package… package yourpackage; import mypackage.*; class pqr extends abc { void method3() { abc x=new abc(); pqr y=new pqr(); x.p=10; x.method1(); y.p=10; y.method1(); } } Public Access Specifier Public Members can be access at anywhere i.e. same or different package. A public key word is used to specify. packagemypackage; class abc { public int p; public void method1()

{ p=10; system.out.print(“Public method”); } } package yourpackage; import mypackage.* ; class xyz {………. void method2() { abc x = new abc(); x.p =10; x.method1() ; } } Package (friendly) Access Specifier If no specifier is explicitly specified, Java assumes default (friendly) access i.e. all the members are accessible in all other classes of the same package only, since they are trusted or friends. This is called Package level access. No any key word is used to specify default access. package mypackage; class abc { int p; void method1() { p=10; system.out.print(“Package method”); } } class xyz {………. void method2() { abc x = new abc(); x.p =10; x.method1() ; } } 16. What do you understand by Library in Java? Ans: A library is readymade and reusable component/codes that can be used in a program to perform predefined task. Some commonly used Java libraries are Math Library, String Library, Utility Library and IO Library etc. You can use import statement at the top of the program to include the Java libraries. import java.io.*; The java.lang is the default imported library in your program without writing import statement. String Library & its commonly used methods 1 .boolen equals(str) - Compare this (current) string to given string and returns true if both are true otherwise false. e.g. boolean test=str1.equals(str2); 2. int compareTo(str1,str2) - Compare two strings in alphabetical order. boolean equalsIgnoreCase(str) - Compare this string to given string but ignores case difference. 3. int length() -Returns the length of this string. e.g. int x=str1.length(); Math Library & its commonly used methods Java provides math library, which available under java.lang package.

In order to use functions/methods of math library, you need to invoke function using math keywords before the function. e.g. x=math.abs(-7.5); 1. pow(num1,num2) - It computes num1 num2 , where num1 and num2 are numbers. e.g. syste.out.print(“”+math.pow(2,3); 2. round(num1) - It rounds off a given number to its nearest integer. It can take float/double as argument. e.g. system.out.print(“”+math.round(1.5)); 2 system.out.print(“”+math.round(-1.5)); -1 Using Dates & Times in JAVA Java offers two classes in java.util package to manipulate date and time. 1. java.util.Date 2. java.util.Calendar In order to use Date & calendar, you need to import java.util package. E.g. import java.util.*; Date d=new Date(); -It returns system date in the given format. Tue Jul 20 17:30:22 GMT+05:30 2010 1. 2. 3. 4. 5. 6.

UNSOLVED QUESTIONS What are the different types of access specifier supported by java? Which is the default package of java? What is friendly access of class member? How does a class enforce information hiding? Define an abstract class and abstract methods. What is an interface? What is the use of Interface.

CHAPTER 7 CONCEPT OF INHERITANCE IN JAVA Brief Summary of the Chapter: This chapter talks about Inheritance, the capability of one class to derive properties from another class. Here we can learn how the inheritance is implemented in Java.

KEY POINTS 

Inheritance: Inheritance is the capability of one class to inherit properties from an existing class. Inheritance supports reusability of code and is able to simulate the transitive nature of real life objects.



Derived/Sub and Base/Super classes A class from which another class is inheriting its properties is called base class and the class inheriting properties is known as a sub class and derived class. 1. Single ( 1:1)  when a class inherits from a single base class. 2. Hierarchical

(1:M)

when several classes inherit from the same class.

3. Multilevel (1:1:1) 

When a subclass is the base class of another class. Method Overriding: If Base class has a method with same signature as in sub class the method of subclass overshadows the method of base class , it is called Method overriding.



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



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

Solved Questions: 1. What is inheritance ? Ans: Inheritance is a form of software reusability in which new classes are created from existing classes by absorbing their attributes and behaviours. 2. What is the primary purpose of inheritance ? Ans: The primary purpose of inheritance is code reusability. 3. Name three basic concepts in Java which are used in Object oriented programming. Ans:The three basic concepts are Classes , Objects and inheritance. 4. Which constructor is called first: subclass or superclass ? Ans: A subclass constructor always calls the constructor for its superclass first explicitly or implicitly to create and initialize the subclass members. 5. What is abstract class? Ans:An Abstract class is the one that simply represents a concept and whose objects can’t be created. It is created through the use of keyword abstract. The superclass set up as an abstract class does not allow objects of its prototype to be created. In this case only objects of the subclass are used. 6. What is method overriding in Java? Ans:A method in a subclass hides or overshadows a method inherited from the superclass if both methods have same signature.(i.e. the same name, number and type of arguments and the same return type.) This property is known as Overriding the Inherited method. 7. What is an Interface in Java? Ans: An Interface defines a protocol of behaviour or it is a collection of constants and abstract methods. These are not classes, but they can be used in the definition of a class. 8. What is the significance of abstract class in Java program? Ans: When a class defines a method using the same namem return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private. 9. What types of inheritance does Java have? Ans: Java supports only these inheritance types: i. Single inheritance ii. Multilevel inheritance iii. Hierarchical 10. State True and False a. A subclass inherits both member variables and member methods of superclass. b. A class created with keyword abstract can have at the most one object. c. Overloading and Overriding are similar concepts in Java. d. Java supports single inheritance only at multiple levels of inheritance. e. Interfaces are used for multiple inheritance.

Ans: a. True b. False c. False d. True e. False 11. Declare and explain the basic syntax of inheritance. Ans:The basic syntax for specifying an inherited class is as: class child_class extends parent_class { // class contents } The syntax represents the definition of the class child_class. The child_class automatically inherits an initial set of methods and variables from the parent class. The inherited variables and method can be used by the child class as if they had been declared locally in the child_class. 12. How does inheritance support software reuse? Ans:Because a new class can be derived from an existing one, the characteristics of the parent class can be reused without the erroneous process of copying and modifying code. 13. Differentiate between method overloading and method overriding. Ans: Overloading: The methods with the same name but it differ by types of arguments and number of arguments. Overriding: The methods with the same name and same number of arguments and types but one is in base class and second as in derived class. Derived class overrides over base class. 14. Write a program to find the area of triangle and rectangle through abstract class and abstract class method. The following is the screen used to find the area of triangle and rectangle using abstract class and abstract class methods:

The list of controls for the above form is as follows: Control Type Control Name Property Name JFrame AbstractU1 title JTextField

JTextFIeld1 JTextFIeld2 JTextFIeld3 JTextFIeld4

JButton

JButton1

text Variable Name text Variable Name text Variable Name text Variable Name

Property Value Abstract class and method [None] txtL [None] txtH [None] txtAreaT [None] txtAreaR

text Variable Name text Variable Name

Calculate cmdCalc Exit cmdExit

a) Write the code to declare an abstract class Figure with an abstract method area( ). Notice that the class should declare the possible variables for area operation. b) Write the code to declare two classes called Rectangle and Triangle which will calculate the area for both rectangle and triangle using the abstract method area( ). Use suitable constructors for both classes. c) Write the code for Calculate button to access the abstract method for both triangle and rectangle. d) Write the code for cmdExit to exit the application. Ans: a) abstract class Figure { double L; double BH; Figure( double a, double b){ L= a; BH = b; } Abstract double area( ); } b) class Rectangle extends Figure { Rectangle ( double a, double b){ super( a, b ); } double area( ) { jLabel5.setText(“ Inside Area of Rectangle. “); return L* BH; } } Class Triangle extends Figure { Traingle ( double a, double b) { Super( a, b); } double area( ) { jLabel6.setText(“Inside Area for Triangle.”); return L * BH /2; } } c) int len, heigh; len = Integre.parseInt(txtL.getText()); heigh= Integre.parseInt(txtH.getText()); Rectangle r = new Rectangle ( len, heigh); Triangle t = new Triangle ( len, heigh); Figure F; F=r; txtAreaR.setText(String.valueOf(F.area( ))); F= t; txtAreaT.setText(String.valueOf(F.area( ))); d) System.exit(0);

15. Write a program to demonstrate constant in an interface to find the area of circle. Notice that the interface should declare the value of pie as a constant. That is: interface valuePie { double PIE= 3.14; } Using class, implement the interface constant and find the area of circle. The following is the screen used to find area of circle using interface constant.:

The list of controls for the above form is as follows: Control Type Control Name Property Name JFrame IntAreaUi Title JTextField JTextField1 text Variable JTextField2 Name text Variable Name JButton

JButton1

text Variable Name text Variable Name

Property Value Constant in an Interface [None] txtR [None] txtArea

Find Area cmdArea Exit cmdExit

a) Write the code to declare an interface for constant with implementation class method area(). b) Write the code for FindArea button to acecess the abstract method and display the area of circle in textbox. c) Write the code for cmdExit to exit to exist the application. Ans: a) interface valuePie { double PIE=3.14; } class cArea implements valuePie { public double area ( float r){ return ( PIE *r*r); } } b) float r = Float.parseFloat(txtR.getText( ) ); cArea C = new cArea ( ); txtArea.setText (String.valueOf (C.area( ))); c) System.exit(0);

Unsolved Questions: 1. What members of a class out of private, protected and public are inheritable? 2. When do we declare a method or class ‘final’? 3. What is an abstract class? 4. When do we declare a method or class abstract? 5. What is the difference between an abstract class and an interface?

CHAPTER 8 GUI DIALOGS AND TABLES Brief Summary of the Chapter: This chapter tells us about how we can create dialogs in Java Swing through NetBeans IDE.

KEY POINTS: 

A Dialog: It is a small separate window that appears to either provide or request to/from the user.



Java Swing provides four dialog types: a) JDialog(General purpose dialogs) b) JOptionPane (Pre-defined styles) c) JFileChooser (dialog for choosing files) and d) JColorChooser(dialog for choosing colour)



JOptionPane dialog Type: There are four built-in dialog styles: 1) Message dialog  JOption.ShowMessageDialog() displays the message dialog 2) Input dialog JOption.ShowInputDialog() displays the input dialog 3) Confirm dialog JOption.ShowConfirmDialog() displays the confirm dialog 4) Option dialog JOption.ShowOptionDialog() displays the option dialog

Solved Questions: 1. What is dialog in Java? Ans: A dialog is a small separate window that appears to either provide or request to / from the user. 2. Write the import statement required for using JOptionPane class. Ans:import javax.swing.JOptionPane; 3. What is showConfirmDialog ( ) method of JOptionPane class do ? Ans: This method displays a dialog with several buttons and returns as int option type corresponding to the button pressed ( mostly one from Yes, No or Cancel) 4. What is showInputDialog ( ) method of JOptionPane class do ? Ans: This method displays a dialog which is intended to receive user input, and returns a String if the input component is a text field. It displays two buttons : OK and Cancel. 5. What is the difference between a dialog created with JDialog and a dialog created with JOptionPane?

Ans: The dialog created with JDialog can be customised in any form the user wants. Also with JDialog, a window’s default cloasing behaviour is available with minimize, maximaize and close buttons. A dialog created with JOptionPane can be one of the four pre-defined styles. Also, it only offers a close button for window closing.

Unsolved Questions: 1. What are the various type of dialog options supported by JOptionPane? 2. Name four methods associated with JOption dialog. 3. Explain the various possible value for Option type property of JOptionPane dialog.

CHAPTER 9 JAVA DATABASE CONNECTIVITY TO MYSQL Brief Summary of the Chapter: In this chapter we shall know how to connect the front end NetBeans application with back-end databases through JDBC,ODBC for making GUI applications.

KEY POINTS: 

Classes used for Database Connectivity



 Driver Manager Class,  Connection Class,  Statement Class,  ResultSet Class Prerequisites for connecting to MySQL from Java

MySQL provides connectivity for client applications developed in the Java Programming language via a JDBC driver known as MySQL Connector/J  Connection: A connection is the session between the application program and the database. To do anything with database, one must have a connection object.  Connecting to MySQL from Java :



Steps for Creating Database Connectivity Application There are mainly six steps – Step-1 Import the Packages Required for Database Programming. Step-2 Register the JDBC Driver Step-3 Open a Connection Step-4 Execute a Query Step-5 Extract Data from Result set Step-6 Clean up the Environment Now to connect to a database, you need to know database’s complete URL, the user’s Id and passwordJdbc:mysql://localhost/?user=”username” & password=”password” ResultSet Methods

A result set (represented by a ResultSet object) refers to a logical set records that are fetched from the database by executing a query and made available to the application –program. There are various resultSet methods such as:• next( ) :moves the cursor forward on row. •

first( )

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



Last( )

:moves the cursor to the last row in the ResultSet object.



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



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



getRow( )

:Retrieves the current row number the cursor is pointing at.

That is if cursor is at first row the getRow( ) will return 1. SOLVED QUESTIONS: 1. What is the importance of java.sql.*; in java jdbc connection ? Ans: The java.sql.package has to be imported first before we can create a java jdbc connection to the database. 6. What is DriverManager ? Ans: DriverManager a class of java.sql package that controls a set of JDBC drivers. Each driver has to be registere with this class. 7. What is the purpose of connection.close() method? Ans: This method is used for disconnecting the connection. It frees all the resources occupied by the database. 8. Name the four components of JDBC. Ans:JDBC consisits of four components: The JDBC API, JDBC Driver Manager, The JDBC Test Suite and JDBC-ODBC Bridge. 9. What are the steps involved in establishing a connection? Ans:To establishing a connection we need to follow two steps: a) loading the driver and b) making a connection. 10. What is ResultSet ? Ans:A result set (represented by a ResultSet object) refers to a logical set of records that are fetched from the database by executing a query and made available to the application program. 11. What type of parameter that used in executeQuery( ) method? Ans: The executeQuery( ) method has a single String parameter. This parameter must be valid SQL command. 12. What is Connection? What is its role? Ans: A Connection (represented through Connection object) is the session between the application program and the database. To do anything with database, one must have a connection object. 13. What all JDBC classes/objects are used in a database connectivity application? Ans: a) DriverManager Class b) Connection Object c)Statement Object d) ResultSet Object 14. What is JDBC? What is its basic functionality? Ans: The JDBC(Java Database Connectivity ) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC we can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing us to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote database access.

15. What is the JDBC-ODBC Bridge? Ans: The JDBC-ODBC Bridge is a JDBC driver which implements JDBC operations by translating them into ODBC operations. To ODBC it appears as a normal application program. The Bridge implements JDBC for any database for which as ODBC driver is available. The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used to access ODBC. 16. Explain the purpose of DriverManager. Ans:The DriverManager looks after the managing the drivers for a JDBC application. When it is instantiated it makes an attempt to load the driver classes. When the method getConnection( ) is invoked, the driver manager attempts to locate the suitable driver. The DriverManager obtains the information about the drivers such as registering, locating, finding the drivers loaded, setting the time to wait when it tries to get the connection to a database. 17. Name the methods which are useful for executing SQL statements. Ans: There are two methods which are responsible for executing SQL statements. These are: • executeQuery( )- For SQL statements that produce a single result set (like simple SQL query). • executeUpdate( )- For executing INSERT,UPDATE OR DELETE statements and also SQL DDL(Data Definition Language) statements.

Unsolved Questions: 1. Differentiate between JDBC and ODBC ? 2. What are the main tasks of JDBC ? 3. What are the various steps involved in establishing a JDBC connection? 4. Name the method used to trigger an update query using JDBC.

CHAPTER 10 WEB APPLICATION DEVELOPMENT Brief Summary of the Chapter: World Wide Web is an example of an information protocol/service that can be used to send and receive information over the internet. It supports: • Multimedia Information (Text, Movies, Pictures, Sound, Programs etc…) • Hyper Text Information :( Information that contains links to other information resources) • Graphical User Interface :(So users can point and click to request information instead of typing in text commands) The World Wide Web is an example of an information protocol/service that works using a Client/Server software design. A service that uses Client/Server design requires two pieces of software to work: Client software (e.g. Web Browser) to request information, and Server software(Web server) to answer requests and provide their information. Most Web applications are designed this way.

Key Points of the Chapter: Uniform Resource Locator: The uniform resource locator (URL) is the unique identifier of a web page. The address or URL of the current page you are on appears in the "Address Bar" of the web browser. What is Web Server: Web server delivers (serves) content, such as web pages, using the Hypertext Transfer Protocol (HTTP), over the World Wide Web.

What is Web Browser: A web browser is a client that initiates communication by making a request for a specific resource. The server then responds with the content of that resource, or an error message if unable to do provide the contents due to any reason. Client Server Computing: It refers to a network set-up in which programs and information reside on the server and clients connect to the server for network access. Dynamic Web Page: A dynamic document is created by web server whenever a browser requests the documents. Static Web Page: A static document is a fixed content document that is created by web server whenever a browser requests the documents.

Solved Questions: 1. Identify the web browser software from the following options: (a) Apache Web Server (b) MS Word (c) HTML (d) Mozilla Firefox Ans. (d) Mozilla Firefox 2. A___________ document is created by web server whenever a browser requests the documents. (a) active (b) static (c) dynamic (d) none of the above Ans. (c) Dynamic 3. A___________ document is a fixed content document that is created by web server whenever a browser requests the documents. (a) active (b) static (c) dynamic (d) none of the above Ans. (b) Static 4. Identify the web server software from the following options: (a) Apache (b) MS Word (c) HTML (d) Mozilla Firefox Ans. (a) Apache 5.

The address of a resource on the net is known as: (a) ISP (b) HTTP (c ) URL (d) WWW

Ans. (c) URL 6. A program that serves requested HTML files and pages. (a) Web Address (b) Web Page (c ) Web Server (d) None of these Ans. (c) Web Server 7. What is Uniform Resource Locator? Ans: The uniform resource locator (URL) is the unique identifier of a web page. The address or URL of the current page you are on appears in the "Address Bar" of the web browser. You can go directly to a web page if you know its URL by simply typing the URL in the address bar. You can click in the address bar at any time and overwrite the current address with another URL to jump to a different web page.The most general form of a URL syntax is as follows: Protocol://domain name// For example: http://www.openoffice.org/dev_docs/features/3.2/rc2.html

8. What is Web Server? Ans: Web server delivers (serves) content, such as web pages, using the Hypertext Transfer Protocol (HTTP), over the World Wide Web. 9. What is Web Browser? Ans: A web browser is a client that initiates communication by making a request for a specific resource. The server then responds with the content of that resource, or an error message if unable to do provide the contents due to any reason.

Unsolved Questions: 1. In the URL, http://www.mycorp.com/pr/master.htm, what is the http component? 2. In the URL, http://www.mycorp.com/pr/master.htm, what is the www.mycorp.com component? 3. In the URL, http://www.mycorp.com/pr/master.htm, what is the /pr/master.htm component? 4. What do you mean by Web Browser, and Web Server? 5. Which protocol is used to upload/ transfer the file from host to server Internet? 6. What is WWW? How does it function? 7. A web browser & web server are an application of client/server computing concept. Comment on this statement? 8. What is URL ? What are its components? 9. What is CGI? How it works in Dynamic web Page service? 10. Differentiate between Static and Dynamic Web Service?

CHAPTER 11 HTML-I : BASIC HTML ELEMENTS Brief Summary of the Chapter: The World Wide Web (or simply the Web or WWW) is a system of sharing interlinked hypertext documents over the internet. These documents are stored on web-servers on the internet and contain text, images, videos and other multimedia. These documents also contain hyperlinks to navigate among them. HTML (Hyper Text Markup Language) is the basic language which is used to create Hypertext documents. In this lesson we are going to learn how to create hyper text documents using HTML.

Key Points of the Chapter: • • • • • •

HTML stands for Hyper Mark-up Language. HTML is the subset of SGML (Standard Generalised Markup Language) The head of the HTML document is where you enter the title of the page. Headings are typically displayed in larger and/or bolder fonts than normal body text. HTML has six levels of heading, numbered 1 to 6, with 1 being the largest. The BACKGROUND is the image attribute in tag where you can place graphic object to make more attractive Web page. The BGCOLOR attribute is used to set the background color of your Web page with tag.

Solved Questions: 1. HTML tags must be written within: (a) < > (b) { } (c) [ ] (d) ( ) Ans: (a) <> 2. Which of the following is the correct structure of HTML tags? (a) < HTML> (b) (c) (d) Ans: (d) 3. What is HTML? Ans: HTML stands for Hyper Text Markup Language. It is a markup language used to create HTML documents. An HTML document defines a web page.

4. Define tag Ans: The tag identifies the document. An HTML document begin with ends with . 5. Give two differences between HTML and XML. Ans: The three differences between HTML and XML are: 1. HTML is designed to display data and hence, focussed on the ‘look’ of the data, whereas XML is designed to describe and carry data and hence, focuses on ‘what data is’. 2. In HTML tags are predefined, while in XML, tags can be created as per needs. 3. HTML tags are not case sensitive, whereas XML tags are case sensitive

Unsolved Questions: 1. What do you need to do work with HTML?

2. Write as HTML code line to set the background image as CLOUDS.GIF. 3. Write an HTML code line to set the BGCOLOR as YELLOW. 4. Write the HTML codes to set the BGCOLOR as PURPLE and a text “I am in Class X-A” as BLUE. 5. Write the HTML codes to set the BGCOLOR as LIME, header 1

text “Text Example with size and color” as BLUE, text font size as 30 and color=”RED”. 6. Write the HTML codes to set the BGCOLOR as NAVY, header 1

text “Text Example with size color, and font face” as WHITE, text font size as 20, color ”RED” and font face “ARIAL”. 7. What is the method of using comment line in HTML code? 8. What is the use of tag in HTML code? Write any two options used with this tag. 9. Which tag is used to insert heading of third level on a web page? 10. How would you display in the title bar of browser? 11. How
tag is different from

tag? 12. What is the purpose of using the tag

? 13. How can the font size of a single line on a web page be changed?

14. What will be displayed on the web page for the following web page? /I> O 2
15. What is the use of tag in HTML code? Write any two attributes used with this tag. 16. Which tag do we use to change the size and style (face) of the text of an HTML file viewed on a web browser? Also explain any two attributes used with this tag. 17. Distinguish between and tags with example.

CHAPTER 12 HTML-II : LISTS, TABLES AND FORMS Brief Summary of the Chapter: Making information more accessible is the single most important quality of HTML. The language’s excellent collection of text style, formatting tools, and links tools help you organize your information into documents that readers quickly understand, scan, and extract. Beyond embellishing your text width specialized text a tag, HTML also provides a rich set of tools that help you organize content into formatted lists. Apart from lists, you can insert images into your documents to enhance its visual approach. Also many documents can be linked together using HTML’s sophisticated linking tools. Also, there are situations where you need to represent tabular data(data in rows and columns). For this, HML provides Table tags.

Key Points of the Chapter: The numbered/ordered list
    tag is used to indicate a list item as contained in an ordered or numbered form. • An ordered list is also a list of items. The list items are marked with numbers. • Bulleted/unordered list