+ All Categories
Home > Documents > 12 Ip Java Notes 1

12 Ip Java Notes 1

Date post: 27-Oct-2014
Category:
Upload: subhash-varghese
View: 522 times
Download: 0 times
Share this document with a friend
Description:
IP Java Notes for Class 11 and 12
Popular Tags:
64
Page 1 of 64 [email protected] JAVA NETBEANS A graphical user interface (GUI ) is a human-computer interface (i.e., a way for humans to interact with computers) that uses windows, icons and menus and which can be manipulated by a mouse (and often to a limited extent by a keyboard as well). GUIs stand in sharp contrast to command line interfaces (CLIs), which use only text and are accessed solely by a keyboard. The most familiar example of a CLI to many people is MS-DOS. Another example is Linux when it is used in console mode (i.e., the entire screen shows text only). RAD : It stands for Rapid Application Development. It is a programming system that enables programmers to quickly build working programs. In general RAD system provides a number of graphical tools to help build a GUI that would normally take a large development effort. IDE (Integrated Development Environment ) is a programming environment integrated into a software application that provides a GUI builder, a text or code editor, a compiler and/or interpreter and a debugger. Visual Studio, Delphi, JBuilder, FrontPage and DreamWeaver, Java‟s NetBEans are all examples of IDEs. NetBeans IDE offers many features of application development: Drag and drop GUI creation Advanced source code editor Web services Excellent degugging(finding out bugs or errors) Wizards, automatic code generation and management tools. Thus, NetBeans IDE is a free, open source, cross platform IDE with a built-in support for Java Progg Language. Platform word is often used as synonym for Operating System of the computer. It defines a standard around which a system can be developed. Cross -Platform refers to the capability of the s/w or h/w to run identically on different platforms. Features of NetBeans IDE: 1. Title Bar: to display title of the application/project. 2. Menu Bar and Pull Down Menu: to display a list of options for a particular category. 3. Toolbar: contains shortcut for commonly used commands in form of icons. 4. GUI Builder: It is also called as „Design Area‟. This is the area where a user visually constructs a GUI application. It has two View: a. Source View: opens the code editor to add/edit a java code. b. Design View: is the default view where you drag and drop various GUI tools to create an application. 5. The Palette: contains all the graphical components needed to create a GUI. It contains icons for various type of graphical controls available under Java Swing API‟s(Application Programming Interface) ex. textbox, buttons, checkboxes, radiobuttons etc. 6. Inspector Window: displays a tree hierarchy of all components contained in the currently opened form. 7. Properties Window: displays editable settings for the currently selected control. 8. Code Editor Window: to open these double click on the control for which you want to write code. Basics of GUI GUI refers to the windows, buttons, dialogs, menus and everything that is visual in a modern application: a. An event refers to the occurrence of an activity. Each time an event occurs, a „MESSAGE‟ is sent to the OS. The system processes the message and passes it to other windows. b. A „message‟ is the information/request sent to the application Types of Graphical Components 1. Container Controls: are those controls that can hols other controls within it. Ex. frame, panel and pane. 2. Child Controls: these are controls inside a container. Ex textboxes, buttons, checkboxes, textarea etc.
Transcript

Page 1 of 64 [email protected] JAVA – NETBEANS

A graphical user interface (GUI) is a human-computer interface (i.e., a way for humans to interact with

computers) that uses windows, icons and menus and which can be manipulated by a mouse (and often to a

limited extent by a keyboard as well).

GUIs stand in sharp contrast to command line interfaces (CLIs), which use only text and are accessed

solely by a keyboard. The most familiar example of a CLI to many people is MS-DOS. Another example is

Linux when it is used in console mode (i.e., the entire screen shows text only).

RAD: It stands for Rapid Application Development. It is a programming system that enables programmers to quickly build working programs. In general RAD system provides a number of graphical tools to help build a GUI that would normally take a large development effort. IDE (Integrated Development Environment) is a programming environment integrated into a software application that provides a GUI builder, a text or code editor, a compiler and/or interpreter and a debugger. Visual Studio, Delphi, JBuilder, FrontPage and DreamWeaver, Java‟s NetBEans are all examples of IDEs. NetBeans IDE offers many features of application development:

Drag and drop GUI creation Advanced source code editor Web services Excellent degugging(finding out bugs or errors) Wizards, automatic code generation and management tools.

Thus, NetBeans IDE is a free, open source, cross platform IDE with a built-in support for Java Progg Language. Platform word is often used as synonym for Operating System of the computer. It defines a standard around which a system can be developed. Cross-Platform refers to the capability of the s/w or h/w to run identically on different platforms. Features of NetBeans IDE:

1. Title Bar: to display title of the application/project. 2. Menu Bar and Pull Down Menu: to display a list of options for a particular category. 3. Toolbar: contains shortcut for commonly used commands in form of icons. 4. GUI Builder: It is also called as „Design Area‟. This is the area where a user visually constructs a

GUI application. It has two View: a. Source View: opens the code editor to add/edit a java code. b. Design View: is the default view where you drag and drop various GUI tools to create an

application. 5. The Palette: contains all the graphical components needed to create a GUI. It contains icons for

various type of graphical controls available under Java Swing API‟s(Application Programming Interface) ex. textbox, buttons, checkboxes, radiobuttons etc.

6. Inspector Window: displays a tree hierarchy of all components contained in the currently opened form.

7. Properties Window: displays editable settings for the currently selected control. 8. Code Editor Window: to open these double click on the control for which you want to write code.

Basics of GUI GUI refers to the windows, buttons, dialogs, menus and everything that is visual in a modern application:

a. An event refers to the occurrence of an activity. Each time an event occurs, a „MESSAGE‟ is sent to the OS. The system processes the message and passes it to other windows.

b. A „message‟ is the information/request sent to the application Types of Graphical Components 1. Container Controls: are those controls that can hols other controls within it. Ex. frame, panel and

pane. 2. Child Controls: these are controls inside a container. Ex textboxes, buttons, checkboxes, textarea

etc.

Page 2 of 64 [email protected] Basic GUI controls: The palette of graphical controls offered by Java Swing contains the tools that you can use to draw

controls on your frame/form. The area on the form where GUI components are placed is called „Content

Pane‟.

1. jFrame: it is a top level container control. It contains a title bar, with buttons to resize and close the

frame.

2. jLabel: allows un-editable text or icons to be displayed.

3. jTextField: allows user input, can also be used to display text. It can be edited and is also known

as edit field.

4. jButton: an actionEvent is generated when a button is pressed.

5. jCheckBox: these are used to allow a user select multiple choices ex. a user can select more than

one hobbies out of 5 choices in checkbox.

6. jRadioButtons: these are option buttons which belong to a group and only one option out of a

given group can be selected. Ex a user can select only one stream out of three options as science,

commerce and arts.

7. jList: is a list of items from which a selection can be made.

8. jComboBox: provides a drop down list from which a selection can be made or new items can be

added. It is a combination of a textfield and a list.

9. jPanel: is a supporting container that cannot be displayed on its own but must be added to another

container.

10. jTextArea: is a control that can display multiple lines of Text.

Page 3 of 64 [email protected] Java Programming Language

Java Keywords: are words that convey a a special meaning to the programming language compiler. These are reserved for special purposes and should not be used as a variable name. ex. if, new, try, else etc. (pg 91 XII)

Constants/Literals: These are values that remain fixed in a program and do not change automatically.

1. You can perform both arithmetic and logical operations on NUMERIC CONSTANTS. a. 2 + 2 will result in 4 b. 32 > 12 will result in TRUE

2. The values of STRING CONSTANTS are displayed/stored AS IT IS written inside Double

Quotes. No mathematical or Logical Operations can be performed on Numbers that are used as a STRING CONSTANT.

a. “Hello” will result in Hello b. “10 + 10 “ will result in 10+10 c. “1 X 2 = “ will result in 1 X 2 =

Adding two Strings will join or concatenate them i.e. “12” + “13” will result in “1213” Adding two Numbers will sum them i.e. 12 + 13 will result in 25 Any NUMBER added with STRING will

result in a STRING i.e. 21 + “13” will result in “2113” VARIABLES: These are easy to remember NAMES given by the programmer to a memory location and

are used ONLY to STORE any one of the following:

A CONSTANT or

An EXPRESSION or

Value of another Variable of same type

A VARIABLE can Store ONLY a single value at a time. The values of these variables can change at any

point of the program. These are so called because the values of these variables can vary by the

programmer anywhere in the program.

JAVA PROGRAM

CONSTANTS/ LITERALS VARIABLES

CONSTANTS

NUMERIC CONSTANTS STRING CONSTANTS

Can ONLY be Numbers. They can be REAL NUMBERS i.e. Numbers with decimal points like 10.25, 123.654 etc.. They can also be INTEGER NUMBERS i.e. Numbers without any decimal points like 10, 121,134 etc..

These are any characters i.e. alphabets, numbers or special characters enclosed in Double Quotes (“ “). Ex. “123”, “Hello”, “####”, “12 + 10 = “ Numbers inside

quotes are treated as a STRING and

NOT as a NUMBER

Page 4 of 64 [email protected]

In JAVA Programming Language, Numeric Variables/Constants can further be sub-divided into the following types:

o byte

o short

o int

o long

o float

o double

In Integer Types, you can ONLY store Integer values i.e. the values without any decimal point.

In Real types, you can store values with decimal points and also integer values. Though internally,

java will store those integer values with decimal point only.

In JAVA Programming language before using a variable (store a value/display its value), you need to

define it first. This means that you need to tell the Java Compiler what type of value you will be storing in

a variable.

1. To define a variable the syntax is: <data type> <variable name> ;

2. To STORE value in variable the syntax is: <variable name> = <constant> ;

The „constant‟ at RHS is stored in „variable‟ at LHS.

In Java we have 6 Numeric data types : byte, short, int, long, float and double.

There is also a String type (though it is not exactly a data type. We will discuss this later)

How to define:

byte b1;

short s1;

int n1;

long n2;

float n3;

double n4;

String s2;

VARIABLES

NUMERIC VARIABLES STRING VARIABLES

These are used to STORE A numeric constants

or An expression which

result in a numeric value or

Value of another numeric variable

These are used to STORE A String constant or A String expression

which result in a string value or

Value of another String variable

Integer Types

Real Types

These types differ in the capacity of numbers that they can store

Byte 1 byte Short 2 byte Int 4 byte Long 8 bytes Float 8 bytes Double 16 bytes

b1 s1 n1 n2

n3 n4

s2

MEMORY

Page 5 of 64 [email protected]

How to STORE:

b1 = 23 ;

s1 = 123;

n1 = 452 ;

n2 = 123456 ;

n3 = 12345.765 ;

n4 = 657.43876 ;

s2 = “St. Xaviers School, Jaipur” ;

YOU CAN DEFINE AND STORE SIMULTANEOUSLY ALSO :

byte b1 = 23 ;

short s1 = 123;

int n1 = 452 ;

long n2 = 123456 ;

float n3 = 12345.765 ;

double n4 = 657.43876 ;

String s2 = “St. Xaviers School, Jaipur” ;

Rules for naming variables:

1. They must ALWAYS start with an alphabet or underscore character(_) or a dollar sign($).

2. They can have an alphabets, digits, underscore and dollar($) sign.

3. They must not be a „Keyword‟.

4. They can be of any length.

5. They are case sensitive.

6. They should not contain any space.

Examples of valid variable names : _a1 $12 a12 n1 qtr_1 abc sales pr …..

Examples of invalid variables : 1a a b new long 12ab 4qtr ….

Assigning values to a variable, just store them in memory. Now if you want to display values of

variables, you will be using : „System.out.println(<values>) ; command.

You can print:

String constants that are enclosed in double quotes.

Variables. The values stored in these variables are displayed.

To display more than one value, you need to use a separator „+‟.

Every „System.out.println‟ will print on a new line.

Example:

double n1 = 12 ;

double n2 = 123.62 ;

double res= n1 * n2 ;

System.out.println(“First Number = “ + n1 );

System.out.println(“Second Number = “ + n2 );

System.out.println(“Result = “ + res );

b1 s1 n1 n2

n3 n4

s2

MEMORY

23 123 452 123456

12345.765 657.43876

St. Xaviers School, Jaipur

In this piece of code you are storing a constant value in these variables. If CONSTANT is numeric, then VARIABLE should also be a numeric. If CONSTANT is a string, then VARIABLE should also be a string. Also, you CANNOT store real numbers in integer type variables

Page 6 of 64 [email protected] Expressions

Expressions are the basic way to create values. Expressions are created by combining literals

(constants), variables, and method calls by using operators. Parentheses can be used to control the order

of evaluation. Expressions are evaluated and results a SINGLE value of a specific type.

Operators

Operators are used to combine literals, variables, methods calls, and other expressions. Operators can be

put into several conceptual groups.

1. Arithmetic operators (+, -, *, /, %, ++, --)

2. Comparison Operators (<, <=, ==, >=, >, !=)

3. Boolean operators (&&, ||, !, &, !, ^, |, &)

4. Bitwise operators (&, |, ^, ~, <<, >>, >>>)

5. String concatenation operator (+)

6. Other (instanceof, ?:)

7. Assignment operators (=, +=, -=, *=,/=)

How to STORE expressions in a variable:

byte b1 = 12 ;

short s1 = b1 * 10 ;

int n1 = b1 + s1 * 2 + 10 ;

long n2 = n1 / s1 + 10 * 3 ;

float n3 = n2 / 2 ;

double n4 = n1 + n2 + n3 /10 ;

String s2 = “10” + “dulkar” ;

Operator Precedence

Precedence determines order of evaluation

Mathematical tradition, which programming languages generally try to match, dictates that some

operations are done before others (for example, multiplication and division are done before addition

and subtraction). Ex. a+b*c is the same as a+(b*c), not (a+b)*c.

Ever operator has a precedence (a number) associated with it. The precedence determines which

operations will be performed first. Multiplication has higher precedence than addition, as illustrated in the

previous example..

Equal precedence operations generally performed left-to-right

In addition to the precedence of each operator, the compiler also knows whether equal-precedence

operators should be performed left-to-right (almost all) or right-to-left (basically only assignment).

Parentheses can be used to control the order of evaluation

If you have any doubt about the order of evaluation, or have a potentially confusing expression, use

parentheses. Remember that one of your goals should be to make your programs as readable as

possible. Use parentheses when it makes an expression easier to read, not must when they are

absolutely required. Few programmers know the precedence of all operators, so it's common for extra

parentheses to be used.

b1 s1 n1 n2

n3 n4

s2

MEMORY

12 120 262 32

16.0 295.6

“10dulkar”

Page 7 of 64 [email protected] Example - Parentheses

When you can work out the precedence, it's often useful to use parentheses to figure out the order

of evaluation. For example, let's say you're evaluating the following expression.

1 + 2 - 3 * 4 / 5

Addition and subtraction are equal in precedence and lower than multiplication and division, which

are equal. Form the parenthesized form and work out the values in steps.

1 + 2 - 3 * 4 / 5

= (1 + 2) - ((3 * 4) / 5)

= 3 - (12/5)

= 3 - 2 The result of the integer division, 12/5, is 2 .

= 1

Precedence table

This table gives the precedence of all operators. You may not be familiar with all operators, but take the

advice on the right side and only learn a few precedences.

Operator Precedence

. [] (args) post ++ --

! ~ unary + - pre ++ --

(type) new

* / %

+ -

<< >> >>>

< <= > >= instanceof

== !=

&

^

|

Remember only

unary operators

* / %

+ -

comparisons

&& ||

= assignments

Use () for all others

&&

||

?:

= += -= etc

1. Arithmetic Operators:

a. + -> 2 + 4 = 6

b. - -> 21 – 2 = 19

c. * -> 2 * 3 = 6

d. / -> 13 / 2 = 6 13.0 / 2 = 6.5

e. % -> 13 % 2 = 1

2. Increment/Decrement Operators:

a. Prefix Forms: This form will follow the concept of “CHANGE then USE”. This means that the

value of the variable is incremented or decremented first and then its value is used.

i. ++a;

ii. –a ;

b. Postfix Forms: This form will follow the concept of “USE then CHANGE”. This means that

the current value of the variable is used first and then the variable is incremented or

decremented.

i. a++ ;

ii. a-- ;

Page 8 of 64 [email protected] 3. Relational Operators compares two operands and results in „true‟ or „false‟.

i. > -> greater than -> 12 > 10 true

ii. < -> less than -> 4 < 3 false

iii. >= ->greater or equal -> 12>=12 true

iv. <= ->less or equal -> 4<=8 true

v. != ->not equal -> 6!=6 false

vi. == -> equal -> 10==10 true

4. Boolean or Conditional operators: These operators also results in either „true‟ or „false‟. These

are used to compare two different conditions.

i. && (AND) -> c1 && c2 -> „true‟ ONLY if both the conditions are „true‟

ii. || (OR) -> c1 || c2 -> „true‟ ONLY if any one condition is „true‟

iii. ! (NOT) -> !c1 -> „true‟ if condition is false and vice versa

iv. ^ -> c1 ^ c2 -> either c1 or c2 is „true‟ and NOT both.

AND(&&)

C1 C2 RESULT

T T T

T F F

F T F

F F F

OR(||)

C1 C2 RESULT

T T T

T F T

F T T

F F T

^

C1 C2 RESULT

T T F

T F T

F T T

F F F

5. Assignment Operators : these operators are used to assign a value to a variable.

a = 10 ;

Here, the constant value/expression/variable on the RHS (Right Hand Side) is assigned or

get stored in the variable specified on the LHS (Left Hand Side)

Normal Assignment Shorthand

Assignment

a = a + 10 (add 10 to „a‟ and store it back in „a‟) a +=10

a= a – 10 (subtract “”) a -=10

a = a * 10 (multiply “”) a *=10

a = a / 10 (divide “”) a /=10

a= a % 10 (remainder “”) a %=10

Now, we‟ll come back to the concept of expressions. We know that an expression is any valid

combination of operators, constants and variables that result in a single value.

The „Expression‟ in java can be:

Arithmetic expression: if an expression is formed using arithmetic operators, numeric constants

and/or numeric variables, it is an arithmetic expression. This type of expression ALWAYS results in a

number (integer or real). Ex. 2 + a * 3 / c where „a‟ and „c‟ are numeric variables.

Relational expression: if an expression has relational and/or boolean operators, it is a relational

expression. This type of expression ALWAYS results in a logical value i.e. true or false. Ex. 10 > a

where „a‟ is a numeric variable.

Compound expression: if an expression consists of both arithmetic and relational expression, it is

termed as compound expression. This type of expression ALWAYS results in a logical value i.e. true or

false. Ex. (10 + a * 3 > 12 / c + 10 ) && ( 15 * d + a != 12 * c )

Page 9 of 64 [email protected] Among these expressions, „arithmetic expressions‟ need some more explanation.

Arithmetic expressions: these expressions can either be :

Pure Integer expressions where all the operands are integer constants and/or integer

variables and it results in an integer value only.

Pure Real expressions where all the operands are real constants and/or real type

variables and it results in a real value only.

Mixed expressions where the operands can be real and/or integer constants and/or

real and/or integer variables and it results in value of the highest data type used in the

expression.

With arithmetic expressions, we will now study about concept called „Type Conversion‟. This is a process

of converting one predefined data type into another data type.

Implicit TC or COERCION: This is automatic type conversion where the compiler

automatically converts the expression into the data type of the largest operand and thus

also known as „type promotion‟. Here, the programmer‟s intervention is not required.

All the above examples were of IMPLICIT TYPE CONVERSION or COERCION.

int shortnt

byteint

long int + * / -

short

long

long

long

float double floatnt

double float + * / -

double

double

double

double

int long floatnt

double short + * / -

float

double

double

double

Page 10 of 64 [email protected]

Explicit TC or CASTING: This kind of type conversion is user defined that forces an

expression to be of specific data type. Syntax to perform CASTING is:

(data-type) expression ;

where data-type specifies the type in which the expression has to be

converted.

Ex. (int) 12 – 32.8 * 4 + 16 / 2.5 ;

In the above example, the expression will result ‘ -112.799’ but the final

answer will be converted to int and thus the value will be -112.

Note that, CASTING may result in possible loss of data.

You CAN always STORE a smaller data type into a larger data type.

Ex. int a = 12 ;

double n2 ;

n2 = a ;

But you CANNOT STORE a larger data type into a smaller data type.

Ex. int a ;

double n2= 121 ;

a = n2 ;

If you want to perform the above operation, then you can do this by „Type Casting‟ it.

Ex. int a ;

double n2= 121 ;

a = (int) n2 ;

CASTING can be performed ONLY on NUMERIC expressions.

JAVA language consists of many classes. A class may contain many methods to perform various

operations. To use a method of a class, the syntax is : classname.methodname(parameters) ;

„classname‟ is the name of the class ex „Math‟

to access a class‟s method, put a „.‟ operator.

after „.‟ operator type the name of the function/method which you want to use.

a „method‟ may or may not use a parameter which is/are given inside a bracket.

o Parameters are of specific type and number ( 1 or more). If parameters are

more than 1, then they should be separated by a comma(,). Ex

classname.methodname(parameter1,parameter2,…..,parameterN) ;

o In case no parameter is needed, you have to put a blank bracket.

Examples:

Math . sqrt ( double type constant or variable)

note that spaces are given just to explain, otherwise no space can be

given while using a method of a class.

To perform mathematical operations, Java consists of a class named ‘Math’ which contains many

functions. Most commonly used are :

Math.sqrt(double) > Math.sqrt(24);

> Math.sqrt(n1); // where n1 is a double type variable

In this example, you are storing an int value in double data type, which is possible and the „int‟ value will be stored as a „double‟ value in n2 variable.

This statement will result in an error as you are trying to store larger value into a smaller data type variable.

This statement will store the value of „n2‟ variable as an „int‟ because of the CASTING statement and no error.

class method parameter

Page 11 of 64 [email protected]

Math.pow(double,double) > Math.sqrt(24,4);

> Math.sqrt(n1,n2); // where n1 and n2 are double

type variable

There are many more classes and their associated methods which we will study as we proceed. The

concept of a ‘CLASS’ and its INSTANCES/OBJECTS and their METHODS/FUNCTIONS will be covered

in more detail in coming sections.

Know that there are many methods associated with a class, BUT there are some methods which

cannot be accessed by a class directly. In such case you need to create an

INSTANCE/OBJECT/VARIABLE of that class to access those methods. In this case the syntax of

calling a method will become: instancename.methodname(parameter/s…….) ;

How to create instance or object of a class will be a topic to cover in detail.

To perform mathematical expressions, you need to convert those expressions in computer

language form. Example:

x

Equivalent Java Expression for the above:

Math.sqrt ( ( 2 * a * b ) + ( a * Math.pow (b , 2 ) ) ) * Math.sqrt ( ( 2 * a * a ) + Math.pow ( b , a ) ) ;

Converting NUMBERS which are STRINGS into PURE NUMBERS:

As discussed earlier, you CANNOT perform mathematical or logical operations on numbers that are

enclosed in double quotes or say are STRINGS.

Ex. “12.2” + “12” will result in “12.2 12”

Here , you should also know that whatever value you type in JAVA‟s GUI controls like a

textbox, are always treated as a String and thus no mathematical operations can be

performed on those values.

To CONVERT numbers that are STRINGS into PURE NUMBERS, you use various parse……

methods.

To convert STRING number into BYTE :

o Byte.parseByte(<string constant/variable that contains a NUMBER ONLY>)

To convert STRING number into SHORT :

o Short.parseShort(<string constant/variable that contains a NUMBER ONLY>)

To convert STRING number into INT :

o Integer.parseInt(<string constant/variable that contains a NUMBER ONLY>)

To convert STRING number into LONG :

o Long.parseLong(<string constant/variable that contains a NUMBER ONLY>)

To convert STRING number into FLOAT :

o Float.parseFloat(<string constant/variable that contains a NUMBER ONLY>)

To convert STRING number into DOUBLE :

o Double.parseDouble(<string constant/variable that contains a NUMBER ONLY>)

2ab + ab2 2a

2 + b

a

Page 12 of 64 [email protected] Ex.

Integer.parseInt(“23”) ; // this will convert string 23 to pure int value;

Double.parseDouble(“123.65”) ; // will convert string 123.65 to pure double value;

Long.parseLong(“1234a”) ; // will result in an error because the string is not a number.

Note that while using these parse… methods, the STRING should contain ONLY NUMERIC

VALUES or they should be a NUMERIC EXPRESSION.

Example:

String n1 = “12” ;

String n2 = “123.62” ;

double a = Double.parseDouble(n1) ;

double b = Double.parseDouble(n2) ;

double res= n1 * n2 ;

System.out.println(“First Number = “ + a );

System.out.println(“Second Number = “ + b );

System.out.println(“Result = “ + res );

System.out.println command is used to print constants or values of a variable on the output

screen.

To print more than one values using this command, you need to use “+” as a separator.

The separator (+) should not be inside a string, otherwise it will be treated as a string and not a

separator.

Each „System.out.println” will print on a new line.

Ex System.out.println(“Hello “ + myname + “ ! How are you ?” );

GUI CONTROLS

Now to create first Java Project using NetBeans IDE, follow these steps:

1. Double click on NetBeans IDE icon on the desktop.

2. NetBeans will start loading.

3.

In the opening screen, click on File -> New Project. You will see the following screen.

STRING CONSTANT STRING CONSTANT

STRING VARIABLE

Page 13 of 64 [email protected]

4.

Here, in Categories box, select Java and in Projects Box select Java Application, and then click in

Next button. Now, you will see the following screen.

5.

Here, in „Project Name‟ box give a name to the project of your choice, and make sure to uncheck

the „Create Main Class‟ checkbox and click on „Finish‟ Button. Now you will

see the following screen.

6.

Page 14 of 64 [email protected]

7. Now select the project, right click on it and from the shortcut menu, select New -> JFrame Form as

shown here

8. In the next screen, give a name of the form of you choice as shown here and click Finish

button.

9. Now you will see a new Java Form. Remember that you can create any number of forms in the

same project.

This creates a new project and a form in that project. You can see the Palette on the right side of

the form. This palette contains various GUI controls. We will be using many of these controls to

quickly create a Java application.

GRAPHICAL USER PALETTE IT CONTAINS VARIOUS GUI CONTROLS LIKE LABEL, TEXTFIELD, BUTTON ETC. YOU NEED TO JUST SELECT THE CONTROL AND DRAG IT ONTO THE FORM

FORM

Page 15 of 64 [email protected]

The next step is to add GUI controls on the form. There are many GUI controls available on the „Palette‟ of

the IDE.

Just to start, we will work with limited GUI controls:

jTextField

jLabel

jButton

jTextField control is used to input and display any value by the user.

Here, you should note that whatever value you input in a Text Field is ALWAYS considered as

a STRING even if it is a NUMBER which you have typed.

To add a text field control on the form, click on the control in the palette, hold down the left mouse button

and drag and drop it on the form.

Now, place this control at your desired place, by selecting and dragging. When you select the control, it will

also display resize handles on that control to increase or decrease its size vertically and/or horizontally

. Increase its size so as to accommodate largest value that you will be typing inside that

control

There are many properties associated with text field control (and other controls too). Most commonly used

them are: “Text” and “Name” properties.

To change its text property:

1. Select the control

2. Right click on it to open shortcut menu and select „Edit Text‟ option.

3. Change the text displayed in the text box. If you don‟t want ant text to be displayed,

simply press „delete‟ key.

4.

5. Here press delete key and clear the displayed text in this

control.

Page 16 of 64 [email protected]

To change its variable name:

1. By default the name of the control will be “jTextField1”. But you should give some

meaningful variable name to it.

2. Select the control, right click, and select „Change Variable Name” option.

3. It will open a small dialog. Here type a new name and press OK button.

4.

5.

6.

There are some commonly used “prefixes” which you use while naming a GUI control:

1. The „text field‟ control should be named with „t‟ prefix.

2. The „label‟ control should be named with „lbl‟ prefix.

3. The „command button‟ control should be named with „btn‟ prefix.

4. The „radio button‟ control should be named with „rb‟ prefix.

5. The „check box‟ control should be named with „cb‟ prefix.

6. The „Panel‟ control should be named with „pan‟ prefix.

7. All the other rules of naming variable applies to these variable names as well.

The next step is to RUN a Project. For that press SHIFT + F6 key.

You can see that, text field is used to GET INPUT from the user at RUN time. In the above example,

the user has provided “St. Xavier‟s School” as an INPUT to the text Field named „txtN1”. You can

think that internally the assignment has taken place as : txtN1 = “St. Xavier‟s School” ;

Page 17 of 64 [email protected]

Now, we will talk about two most commonly used methods associated with a text field variable:

1. getText()

2. setText(<string constant/variable>);

There will be many methods associated with different GUI control variables. To use a method you should

use the following syntax:

guicontrolname.methodname();

getText() method belongs to a Text Field class. This method is used to GET the value from the

Text Field and store it in some memory variable of type String ONLY or print it on the output

screen. Remember, the value stored in a Text Field is ALWAYS a STRING and thus you need

to store it in a String Variable.

Ex. String s1= txtN1.getText() ;

In the above example, “txtN1” is the name of a Text Field. So, whatever value the user

types in txtN1 at run time, will be stored in a memory variable s1 of type String with the above

command. You can store the value of a Text Field in a String Variable ONLY.

setText(<string constant/string variable> ) method also belongs to a Text Field class. This

method is used to DISPLAY/SET a text which should be of String type (constant/variable) in a

Text Field.

Ex. String s1=” Welcome to my Program” ;

txtN1.setText(s1) ;

In the above example, the value of s1 variable which is of String type, will be displayed in a

text field with the name txtN1.

Thus you can see and note that getText() method of a text field does not take any value in its

brackets while in setText() method, you need to provide a single String type value in its

bracket.

Java uses a peculiar practice to name any method. A method may contain different words in it

without any space like setText contains two words set and text or another method named

getSelectedValue contains three words get, selected and value . So, the practice is

o First letter of first word is small case ALWAYS.

o First letter of second or third or fourth word is upper case

ALWAYS.

o Ex. getSelectedValue() ;

o Ex. getText ();

o Ex. isSelected() ;

We will discuss about classes and methods in more detail in coming sections. Till then, you must know

that every GUI control belongs to a particular class and a class has got many methods. To access

those methods, you need to create an object/variable of that class.

Page 18 of 64 [email protected]

Now, the question arise that when text fields take all values as strings, how can you perform mathematical

or logical operations on the values that a user enters in a text field.

Can you recall? Is there any way?????? Think …….

Fine then, the answer is parse…. methods. Remember now.

To perform mathematical operations on values you enter in a text field:

a. First, store the text field value into a string variable.

b. Then, store that string value by converting it in desired NUMBER TYPE using parse methods.

Ex. String s1 = txtN1.getText() ;

double n1=Double.parseDouble(s1) ;

OR

double n1 = Double.parseDouble(txtN1.getText()) ;

Make sure that the value you enter in the text field is a NUMBER (real or integer) ONLY

otherwise the parse…. method will result in an error.

So, now you know that:

Any numeric value you enter in a text field is always a string type,

Numeric value you enter in a text field need to be converted in PURE numeric form by using

parse…. methods and should be stored in numeric variables.

If three text fields are used to input some value, then you will require three memory variables

too to store the values of those three text fields.

Example:

Design a GUI form as shown above.

Add three “label” controls and change their “text” property to

First Number

Second Number

Result

And place them as shown above.

Add three “text field” controls and change their “variable name” property to

t1 - first text field

t2 - second text field

t3 - third text field

And position them as shown above,

Add four “button” controls and change their “text” property to

+

-

*

/

And position them as shown above

Page 19 of 64 [email protected]

Now, double click on the “+” button in the design view and add the following code in the source view:

double n1=Double.parseDouble(t1.getText()) ;

double n2=Double.parseDouble(t2.getText()) ;

double r = n1 + n2 ;

t3.setText(r + "") ;

Likewise, add the code behind other three buttons to perform subtraction, multiplication and division.

Other Data Types

Till now, you have learnt about 6 numeric java data types namely :

short

byte

int

long

float

double

Now, we will study about 2 more data types:

char - this data type is used to store a single value (number or

alphabets or special characters within single quote („).

Ex - „a‟ , „1‟ , „&‟ , „^‟

etc. Also note that they are NOT String.

char ch;

ch=‟A‟ ;

ch=ch + 1 ;

System.out.println (ch + “”) ; // guess the output…

You can perform some calculations on char type. The ASCII code of

the value is stored in char type variable and the code is an integer

value. Thus, you can type cast char type to int and vice versa. Ex.

char ch=‟A‟ ;

int a = (int) ch ;

System.out.println (ch + “ “ + a ) ;

// Guess the output……..

boolean this data type is used to store ONLY TWO values, true or false

without any quotes (single or double).

Ex.

boolean yn ;

yn = true ;

Thus, Java has 8 inbuilt data types also known as Primitive Data Types namely:

short byte int long float double

char

boolean

String (is NOT a data type. It‟s a Java Class)

Page 20 of 64 [email protected]

Programming Constructs

Every programming language provides statements/commands/constructs to support:

Sequence

Selection

Iteration ( Repetition )

1. Sequence : this means that the statements of the program are being executed sequentially from

top to bottom and from left to right.

2. Selection: this means that the execution of statement(s) depends on a condition test.

If a condition is “true” a set of statements are executed and if the condition is “false”

another set of statements are executed.

“Condition” is any expression which result in “true” or “false”.

In hindi you can say, vxj ,¢lk g¨ r¨ ;g dj¨ ugh r¨ og dj¨

CONDITION TRUE FALSE

START

Statement 1

Statement 2

Statement 3

STOP

In the Flow Chart, you can see that, Statement 1 Statement 2 Statement 7 and Statement 8 will be executed in the program. And if the condition is TRUE: Statement 3 and Statement 4 will be executed And if the condition is FALSE: Statement 5 and Statement 6 will be executed.

Condition ?

START

Statement 1

Statement 2

Statement 3

Statement 4

Statement 5

Statement 6

Statement 7

Statement 8

STOP

T

F

If – else block

Page 21 of 64 [email protected]

3. Iteration: means repetition of a set of statements depending upon a condition test.

Till a condition is true, a set of statements are repeated again and again. As soon as the

condition becomes false, the repetitions stop.

BLOCKS

A Block is a group of zero or more statements written between an opening curly bracket and closing curly

bracket.

{

int a=10;

b= a+ c ;

System.out.println(“The value of „a‟ = “ + a );

}

Any variable defined in a BLOCK is visible ONLY in THAT BLOCK and ALL its SUB BLOCKS.

Ex. {

int a=10;

{

int b = a + 20 ;

System.out.println ( a ) ; // no error

}

System.out.println ( b ) ; // error

}

Loop body

F

Condition ?

START

Statement 1

Statement 2

Statement 3

Statement 4

Statement 5

Statement 6

STOP

T

In the Flow Chart, you can see that, Statement 1 Statement 2 Statement 5 and Statement 6 will be executed in the program. And till condition is TRUE: Statement 3 and Statement 4 will be executed again and again. And when the condition becomes FALSE control comes out of the loop and : Statement 5 and Statement 6 will be executed in sequence.

These 3 statements are part of a block.

Block begins with opening curly bracket

Block ends with closing curly bracket

MAIN BLOCK

SUB BLOCK

Page 22 of 64 [email protected]

JAVA SELECTION STATEMENTS

We have already discussed about „selection‟ construct. Now we will study those commands in JAVA that

supports this construct.

1. if

2. if – else

3. if – else if – else

4. switch

1. if : In this you specify what has to be done if the condition is TRUE, but you don‟t

specify what has to be done if the condition is FALSE.

if ( condition ) {

statements to be executed

if the condition is TRUE ;

}

In this „if‟ statement, if the condition is TRUE, the block after „if‟ statement will be executed and if the condition is FALSE, the control is

transferred just after the if block

Condition ?

START

Statement 1

Statement 2

Statement 3

Statement 4

Statement 5

Statement 6

STOP

T

If - block

If the condition is TRUE, then the following statements will be executed: Statement 1; Statement 2 ; Statement 3 ; Statement 4 ; Statement 5 ; Statement 6 ; If the condition is FALSE, then the following statements will be executed: Statement 1; Statement 2 ; Statement 5 ; Statement 6 ;

Page 23 of 64 [email protected] 2. if - else : In this you specify what has to be done if the condition is TRUE, and also what

has to be done if the condition is FALSE.

vxj ,¢lk g¨

if ( condition ) {

statements to be executed

if the condition is TRUE ;

}

else {

statements to be executed

if the condition is FALSE ;

}

In this „if‟ statement, if the condition is TRUE, the block after „if‟ statement will be executed and if the condition is FALSE, the block after else statement will be executed

Condition ?

START

Statement 1

Statement 2

Statement 3

Statement 4

Statement 5

Statement 6

Statement 7

Statement 8

STOP

T

F

If – else block

In the Flow Chart, you can see that, Statement 1 Statement 2 Statement 7 and Statement 8 will be executed in the program. And if the condition is TRUE: Statement 3 and Statement 4 will be executed And if the condition is FALSE: Statement 5 and Statement 6 will be executed.

F

r¨ ;g dj¨

ugh r¨ ;g dj¨

Page 24 of 64 [email protected]

3. if - else if - else : This is used when you have to check for more than one condition and

you know that out of those many conditions ONLY one can be TRUE.

if ( condition 1 ) {

statements to be executed

if the condition is TRUE ;

}

else if ( condition 2 ){

statements to be executed

if the condition 2 is TRUE ;

}

else if ( condition 3 ){

statements to be executed

if the condition 3 is TRUE ;

}

else if ( condition n ){

statements to be executed

if the condition n is TRUE ;

}

else {

statements to be executed if

all the above conditions are FALSE ;

}

Note the following code. Both are same.:

Without Blocks With Blocks

If(condition1)

Statement 1;

else if(condition 2)

Statement 2;

else if(condition 3)

Statement 3;

else

Statement 4 ;

If(condition1) {

Statement 1;

} else if(condition 2) {

Statement 2;

} else if(condition 3) {

Statement 3;

} else

Statement 4 ;

If the number of statement to be executed on the condition being true or false is a SINGLE statement, then

you can avoid the opening and closing blocks. But in case of MULTIPLE statements, they need to be

enclosed between opening and closing blocks as shown in the following example,

If(condition1)

Statement 1;

Statement 2 ;

else if(condition2)

Statement 3;

Statement 4 ;

The code to the left will

result in an error as you are

executing 2 statements

without giving blocks.

The correct code is on the

right side.

If(condition1) {

Statement 1;

Statement 2 ;

}

else if(condition2) {

Statement 3;

Statement 4 ;

}

In this „if‟ statement, if the condition is TRUE, the block after „if‟ statement will be executed and if the condition is FALSE, following „else if‟ condition is checked and so on.. Note that, the following „else-if‟ statement is checked ONLY IF the above „if‟ or „else- if „ condition is FALSE.

Page 25 of 64 [email protected]

Suppose, you need to find „grade‟ of a student which is based on the following criteria:

Total Grade

> 90 A +

80 – 89 A

70 – 79 B

60 – 69 C

50 – 59 D

40 – 49 E

<40 FAIL

Without else if With else if

int tot = Integer.parseInt(t1.getText());

String gr= “”;

if ( tot >=90 ) {

gr = “A+” ;

}

if ( tot >=80 && tot < 90 ) {

gr = “A” ;

}

if ( tot >=70 && tot <80 ) {

gr = “B” ;

}

if ( tot >=60 && tot < 70 ) {

gr = “C” ;

}

if ( tot >=50 && tot < 60 ) {

gr = “D” ;

}

if ( tot >=40 && tot < 50 ) {

gr = “E” ;

}

if ( tot < 40 ) {

gr = “FAIL” ;

}

int tot = Integer.parseInt(t1.getText());

String gr= “”;

if ( tot >=90 ) {

gr = “A+” ;

}

else if ( tot >=80 ) {

gr = “A” ;

}

else if ( tot >=70 ) {

gr = “B” ;

}

else if ( tot >=60 ) {

gr = “C” ;

}

else if ( tot >=50 ) {

gr = “D” ;

}

else if ( tot >=40 ) {

gr = “E” ;

}

else {

gr = “FAIL” ;

}

Can you point out the difference between the above two piece of code ???

All the above were different variants of „if‟ statements. You must note the following point with this regard:

With „if‟, you have to specify the course of action if the condition is true.

With „if‟, statement, „else‟ is optional. i.e. You may avoid the course of action if the condition is false.

The number of “if‟s” can be more than the number of “else‟s” in a program. This situation is known

as „dangling else‟ problem where the problem of associating an „else‟ with which „if‟ may arise.

But in any case, number of “else” can‟t be more than the „if‟s”.

Page 26 of 64 [email protected]

4. switch : this is also another conditional statement. Following are its features :

a. switch check ONLY EQUALITY conditions i.e. no range checking possible.

b. It can check only Integer Constants and Character Constants.

c. It can check ONLY a single variable‟s value of integer type or character type.

switch(variable/expression) {

case <constant1> : statement1 ;

break;

case <constant2> : statement2;

break;

case <constant3> : statemet3 ;

break ;

case <constantN> : statement4;

break;

default : statemetDefault ;

}

Variable must be of integer or char type AND

expression should result an integer value or char

value..

No two case statements can be same.

“break “ statement is needed to avoid an error or say

a concept namely “FALL THROUGH” associated

with switch statement.

If NO case matches, the compiler will execute

„default‟ statement.

Whenever you want to check a single variable with

ONLY equality conditions, go for “switch” instead of “if – else”.

The fall of control to the following „cases‟ of the matching „case‟ statement is called “FALL THROUGH”. To

avoid this, we use „break‟ at the end of every „case‟ statement.

The „default‟ statement is optional and if it is missing, no action takes place if all matches fail.

Example : int a = Integer.parseInt(t1.getText()) ; String msg = “” ; switch ( a ) { case 1 : msg = “MON” ; break ; case 2 : msg = “TUE” ; break ; case 3 : msg = “WED” ; break ; case 4 : msg = “THU” ; break ; case 5 : msg = “FRI” ; break ; case 6 : msg = “SAT” ; break ; case 7 : msg = “SUN” ; break ; default : msg = “Wrong Number” ; }

Page 27 of 64 [email protected]

Fall Through may sometimes work for your benefit in some cases:

Example :

String s1 = t1.getText();

char v = s1.charAt(0) ;

String msg = “” ;

switch(v) {

case „A‟ :

case „a‟ :

case „E‟ :

case „e‟ :

case „I‟ :

case „i‟ :

case „O‟ :

case „o‟ :

case „U‟ :

case „u‟ : msg=”It‟s a Vowel” ;

break;

default : msg = “Not a Vowel “ ;

}

If the above program is written with „if‟ statement then the code will look like the following:

……

if(v==‟A‟ || v==‟a‟|| v==‟E‟ || v==‟e‟|| v==‟I‟ || v==‟i‟|| v==‟O‟ || v==‟o‟|| v==‟U‟ || v==‟u‟) {

msg= “it‟s a Vowel” ;

}

else {

msg = “Not a Vowel” ;

}

Now try to convert the following piece of „if‟ statement into its equivalent „switch‟ statement :

int n1=Integer.parseInt(t1.getText());

String msg=””;

if(n1==1 || n1==2 || n1==3 ) {

msg= “RED” ;

}

else if (n1==4) {

msg = “GREEN” ;

}

else if(n1==5 || n1==6) {

msg=”BLUE” ;

}

else {

msg = “Enter a value between 1 and 6”);

}

This piece of „switch; statement is actually performing OR ( || ) operation. If the case matches „A‟ then the control will fall through all other cases in the absence of „break‟ statement. The following equivalent „if‟ statement will explain this.

Page 28 of 64 [email protected]

Examples: Assuming that you have already created required GUI form and controls.

1. Find maximum of two numbers. Also Check for their equality.

String msg=””;

int n1=Integer.parseInt(t1.getText());

int n2=Integer.parseInt(t2.getText());

if (n1>n2)

msg=“First Number is greater”;

else if (n2>n1)

msg=”Second Number is greater”;

else

msg=”Both are equal” ;

t3.setText(msg);

2. Find minimum of two numbers. ( Do it yourself)

3. Find maximum of four numbers.

int max=0;

int n1=Integer.parseInt(t1.getText());

int n2=Integer.parseInt(t2.getText());

int n3=Integer.parseInt(t3.getText());

int n4=Integer.parseInt(t4.getText());

max=n1 ;

if (n2 > max ) max = n2 ;

if (n3 > max ) max = n3 ;

if (n4 > max ) max = n4 ;

t5.setText (“The maximum number is = “ + max );

4. Find minimum of five numbers. (Do it yourself)

5. Input age and print a message if he/she is eligible to vote or not.

String msg=””;

int age=Integer.parseInt(t1.getText());

if ( age >= 18)

msg= “Eligible to vote” ;

else

msg = “Not eligible to vote.” ;

t2.setText(msg) ;

6. Input a number and check if it is an even or an odd number.

String msg=””;

int n=Integer.parseInt(t1.getText());

if ( n % 2 == 0)

msg= “ An Even Number” ;

else

msg = “ An Odd Number.” ;

t2.setText(msg) ;

No BLOCKS given because, the number of statements to be executed is ONLY a

SINGLE statement.

Page 29 of 64 [email protected]

7. Input a number and check if it is a negative, positive or a zero.

String msg=””;

int n=Integer.parseInt(t1.getText());

if ( n > 0)

msg= “A Positive Number” ;

else if (n < 0)

msg = “A Negative Number.” ;

else

msg = “The Number is Zero” ;

t2.setText(msg) ;

8. Find maximum and second maximum out of 4 numbers.

int max=0;

int max2=0 ;

int n1=Integer.parseInt(t1.getText());

int n2=Integer.parseInt(t2.getText());

int n3=Integer.parseInt(t3.getText());

int n4=Integer.parseInt(t4.getText());

max=n1 ;

max2=0 ;

if (n2 > max ) {

max2= max ;

max= n2 ;

} else if ( n2 > max2 ) {

max2= n2 ;

}

if (n3 > max ) {

max2= max ;

max= n3 ;

} else if ( n3 > max2 ) {

max2= n3 ;

}

if (n4 > max ) {

max2= max ;

max= n4 ;

} else if ( n4 > max2 ) {

max2= n4 ;

}

t5.setText (“The maximum number is = “ + max );

t6.setText (“The second maximum number is = “ + max2 );

(Write an EXECUTION TRACE for program Number 8 )

Page 30 of 64 [email protected] ITERATION OR LOOP STATEMENTS

1. for ….. loop

2. while ….. loop

3. do – while …. Loop.

Loop statements allow a set of statements to be performed repeatedly until a condition is TRUE.

Every loop is controlled by a „Loop Control Variable‟ which will keep track of the number of times the loop has

been executed.

Every Loop has got 4 elements as shown in the following flowchart:

I. Initialise Loop Control Variable: Before entering a loop, its control variable must be initialized.

The initialization expression gives the loop control variable its first or starting value. The initialization

expression is executed ONLY ONCE at the start of the loop.

II. Test Condition: is a condition which if „true‟ enters into the loop and executes the loop body. And if

the condition is „false‟, the loop is terminated and control is transferred to the first statement just

after the loop.

III. Loop Body: these are the statements that are executed repeatedly as long as the Test Condition is

„true‟.

IV. Update Loop Control Variable: This expression will change the value of loop control variable. This

expression is executed after the loop body statements have been executed.

F

Condition ?

START

Statement 1

INTIALISE LOOP CONTROL VARIABLE

LOOP BODY

Statement 5

Statement 6

STOP

T

UPDATE LOOP CONTROL VARIABLE

I

II

III

IV

Loop back to check condition

Loop terminated if condition becomes false

Page 31 of 64 [email protected]

I. for …. Loop: in this type of loop, all its loop control elements are gathered in one place at the top of

the loop.

Syntax:

for( initialization ; test condition ; update ) {

….. loop body ;

}

1. Initialization of Loop Control Variable takes place

2. Condition is tested. IF TRUE goto STEP 3 and IF FALSE goto STEP 5

3. Execute LOOP BODY.

4. Update the Loop Control Variable and Again goto STEP 2

5. Move to the first statement just after the end of the loop block.

Example : Suppose you are asked to print “Hello” five times on the screen. You can do it by :

System.out.println(“Hello”) ; write this command 4 more times..

But now, if you are asked to do the same hundred times, the above code may be tedious. But

with a loop command, it will be easy.

So, now to print “Hello” five times using “for” loop:

int n ; // my loop control variable

for ( n=1 ; n<=5 ; n++ ) {

System.out.println(“Hello”) ;

}

System.out.println(“Bye”);

In the above example, various elements of loop are :

1. Initialization: n=1; this is a loop control variable

2. Test Condition: n<=5;

3. Loop Body: System.out.println(“Hello”);

4. Update Expression: n++;

Execution Trace of the above Loop:

Statements Variable n Output

n= 1 Store 1 in Variable n: 1

n<=5 True so enter the loop

System.out.println (“Hello”) Print “Hello” on the output Hello

n++ Add 1 to n : 2

n<=5 True so enter the loop

System.out.println (“Hello”) Print “Hello” on the output Hello

n++ Add 1 to n : 3

n<=5 True so enter the loop

System.out.println (“Hello”) Print “Hello” on the output Hello

n++ Add 1 to n : 4

n<=5 True so enter the loop

System.out.println (“Hello”) Print “Hello” on the output Hello

n++ Add 1 to n : 5

n<=5 True so enter the loop

System.out.println (“Hello”) Print “Hello” on the output Hello

n++ Add 1 to n : 6

n<=5 False so terminate the loop

System.out.println(“Bye”) Print “Bye” on the output Bye

If TRUE

If FALSE come out of the Loop

1 2

3

4

5

Page 32 of 64 [email protected]

JUMP Statements These statements un-conditionally transfer program control within a program. Java has 3 statements that perform an un-conditional branch:

break continue return

a. break : this statement skips the rest of the loop and jumps over to the statement following the loop.

A „break‟ statement terminates the smallest enclosing „for loop‟, „while loop‟, „do-while loop‟ or „switch‟ statement.

Ex: for (n = 1 ; n<=10 ; n ++ ) {

System.out.println (“Hello”); break;

} System.out.println( “Bye”);

The above loop will print “Hello” ONLY once. The reason is that the „break‟ statement will transfer the control directly to the statement just following the loop. In a way, this statement terminates the loop unconditionally.

b. continue : this statement skips the rest of the loop statements and transfer the control to the

LOOP HEAD and NOT out of the loop. for (n = 1 ; n<=10 ; n ++ ) {

continue ; System.out.println(“Hello”);

} System.out.println( “Bye”);

The above loop will NOT print HELLO EVEN ONCE. The reason is that the „continue‟ statement will transfer the control back to the loop head. In a way, this statement can result in „UN-ENDING LOOPS.

Note that „break‟ statement can come ONLY inside any LOOP command or switch statement AND not anywhere else in the program. Similarly, „continue‟ statement can come ONLY inside any LOOP command AND not anywhere else in the program. c. return : this statement terminates a program abruptly. Whenever this statement is encountered, the

control is transferred out of the program and all the following statements remain un-executed. This statement is mainly used inside a method/function( topic to be covered ), to return a particular value. This statement can appear anywhere in the program and NOT necessarily inside a loop as in case of „break‟ and „continue‟ statements. The only thing is that all the statements following „return‟ statement will not be executed.

Make sure that you DO NOT change the LOOP CONTROL variable inside the loop body because it could result in some kind of unusual loop behaviour. The things may not work as intended.

Page 33 of 64 [email protected] Examples:

1. Print First Ten natural numbers along with “Hello”.

int n ; for (n=1 ; n<=10 ; n++ ) { System.out.println( “Hello ” + n) ; }

2. Print First ten natural numbers in reverse.

int n ; for (n=10 ; n>=1 ; n-- ) { System.out.println( n ) ; }

3. Print first ten even numbers.

int n ; for (n=2 ; n<=20 ; n+=2 ) { System.out.println( n ) ; }

4. Print first ten even numbers in reverse.

int n ; for (n=20 ; n>=2 ; n-=2 ) { System.out.println( n ) ; }

5. Print first ten odd numbers.

int n ; for (n=1 ; n<=20 ; n+=2 ) { System.out.println( n ) ; }

6. Print first ten odd numbers in reverse.

int n ; for (n=19 ; n>=1 ; n-=2 ) { System.out.println( n ) ; }

7. Print Sum of first 10 numbers.

int n ; int sum=0; for (n=1 ; n<=10 ; n++ ) { sum=sum + n ; } System.out.println (“The Sum is = “ + sum ) ;

8. Print Sum of even and odd numbers out of first 20 natural numbers.

int n ; int sumeven=0; int sumodd=0; for (n=1 ; n<=20 ; n++ ) { if ( n%2==0) { sumeven=sumeven + n ; } else{ sumodd=sumodd + n ; } } System.out.println (“The Even Sum is = “ + sumeven ) ; System.out.println (“The Odd Sum is = “ + sumodd ) ;

Page 34 of 64 [email protected] 9. Print table of n number upto n x 10 .

int num = Integer.parseInt(t1.getText()); int n ; for (n=1 ; n<=10 ; n++ ) { System.out.println( num + “ x ” + n + “ = ” + num * n ) ; }

10. Print factorial of n number.

int num=Integer.parseInt(t1.getText()); int n ; int fact=1; for (n=1 ; n<=num ; n++ ) { fact=fact*n; } System.out.println( “Factorial = ” + fact ) ;

11. Check weather a given number is a Prime number or not.

int num=Integer.parseInt(t1.getText()); int n ; boolean prime=true ;; for (n=2 ; n<=num/2 ; n++ ) { if (num % 2 ==0) {

prime=false; break ;

} } if(prime==true)

System.out.println( “The Number is Prime” ) ; else System.out.println( “The Number is Not Prime” ) ;

12. Print sum and average of first n Numbers.

int num=Integer.parseInt(t1.getText()); int sum=0; int avg=0; for(int n=1 ; n<=num ; n++) sum=sum + n ; avg=sum/num; System.out.println(“Sum = “ + sum) ; System.out.println(“Average = “ + avg) ;

13. Print sum and average of first n Numbers which are divisible by 3. (Do it yourself) 14. Print the following series : 1 1 2 3 5 8 13 21 34….

(Such a series is known as a FIBONACCI SERIES where every new number is sum of previous two numbers. int num=Integer.parseInt(t1.getText()); int n1=1; int n2=1; System.out.print(n1 + “ “ + n2); for(int n=3 ; n<=num ; n++) { n3 = n1 + n2 ; System.out.print(“ “ + n3 ); n1 = n2 ; n2 = n3 ; }

Page 35 of 64 [email protected] 15. Print all the ARMSTRONG NUMBERS.

„Armstrong Numbers‟ are those numbers whose sum of cube of individual digits is the number itself: 153 ( 1 + 125 + 27 = 153 ) int n,newn,n1,n2,n3; int sumcube=0; for(n=100 ; n<=999 ; n++){ newn=n;

n1=newn%10; newn=newn/10; n2=newn%10; newn=newn/10; n3=newn%10; sumcube=(n1*n1*n1) + (n2*n2*n2) + (n3*n3*n3) ; if( n==sumcube) System.out.println(“It‟s an ARMSTRONG number.”); else System.out.println(“It‟s NOT an ARMSTRONG number.”);

}

II. while loop: this loop has also the same 4 elements as in case of „for‟ loop. The

ONLY difference is the syntax.

Initilization ;

while ( test – condition ) {

loop body ;

update expression ;

}

statement n ;

1. Initialize LOOP CONTROL variable.

2. Check the CONDITION. If TRUE enter the LOOP. If FALSE go to STEP 5.

3. Execute LOOP BODY.

4. UPDATE the LOOP CONTROL VARIABLE and JUMP back to STEP 2

5. Execute the statement JUST after the LOOP.

for loop while loop

Print First Ten natural numbers along with “Hello”.

int n ; for (n=1 ; n<=10 ; n++ ) { System.out.println( “Hello ” + n) ; }

System.out.println(“Bye”);

Print First Ten natural numbers along with “Hello”.

int n;

n = 1 ;

while (n<=10) {

System.out.println(“Hello ” + n ) ;

n++ ;

}

System.out.println(“Bye”);

We will STORE value of „n‟ to „newn‟ in order to NOT to change the value of „n‟ because „n‟ is acting like a LOOP CONTROL VARIABLE .

1

2

3

4

5

1 2

3

4

5

1

2

3

4

5

If TRUE enter the LOOP

If FALSE exit the LOOP

Move back to the TOP of the LOOP to check the

condition

Page 36 of 64 [email protected] Thus, we can see that in the while loop :

Initialization expression takes place before the start of the while loop

In while header ONLY the test expression appears.

The update expression has to appear inside the while loop.

AND in „for loop‟ all these 3 parts appears inside the for loop header.

ENTRY CONTROLLED LOOP : In such kind of loops, the condition is evaluated first and if that condition is

„true‟ the loop body gets executed. Thus, the condition is tested at the top and then only the loop body gets

executed. Such loops are also called as „TOP TESTED LOOPS‟.

It is possible that such loops may not execute even ONCE if the condition is „false‟ in the very beginning. The

two loops „for loop‟ and „while loop‟ which we had discussed were ENTRY CONTROLLED LOOPS

Examples:

1. Create a GUI to input a number and count the number of digits it contains.

int n=Integer.parseInt(t1.getText());

int c=0;

while (n>0) {

c++ ;

n=n/10 ;

}

t2.setText(“Total digits: “ + c );

2. Create a GUI to input a number and find the sum of its digits.

int n=Integer.parseInt(t1.getText());

int sum=0;

while (n>0) {

int digit= n % 10 ;

sum=sum + digit ;

n=n/10 ;

}

t2.setText(“Sum of digits: “ + sum );

3. Create a GUI to input a number and count how many of those digits are even and odd.

int n=Integer.parseInt(t1.getText());

int counteven=0, countodd=0;

while (n>0) {

int digit= n % 10 ;

if (digit % 2 ==0)

counteven++ ;

else

countodd++ ;

n=n/10 ;

}

t2.setText(“Count of Even Nos: “ + counteven );

t3.setText(“Count of Odd Nos:” + countodd ) ;

Page 37 of 64 [email protected]

4. Create a GUI to input a number and print sum of all the even and odd digits.

int n=Integer.parseInt(t1.getText());

int sumteven=0, sumodd=0;

while (n>0) {

int digit= n % 10 ;

if (digit % 2 ==0)

sumeven=sumeven + digit ;

else

sumodd=sumodd + digit ;

n=n/10 ;

}

t2.setText(“Sum of Even Nos: “ + sumeven );

t3.setText(“Sum of Odd Nos:” + sumodd ) ;

5. Create a GUI to input a number and print sum of square of its individual digits.

int n=Integer.parseInt(t1.getText());

int sum=0;

while (n>0) {

int digit= n % 10 ;

sum=sum + (digit * digit) ;

n=n/10 ;

}

t2.setText(“Sum of square of digits: “ + sum );

6. Create a GUI to input a number and reverse it.

int n=Integer.parseInt(t1.getText());

int newnum=0;

while (n>0) {

int digit= n % 10 ;

newnum=(newnum * 10) + digit ;

n=n/10 ;

}

t2.setText(“Reverse is: “ + newnum );

Do all the programs of „for loop‟ WITH „while loop‟.

Both „for‟ loop and „while‟ loop were „ENTRY CONTROLLED LOOPS‟ as the conditions were tested first

before actually executing the loop. Such loops may not run even ONCE if the condition is found to be „false‟

at the entry level only.

Page 38 of 64 [email protected] Now, if we want to run a loop at least ONCE even if the condition is „false‟ we‟ll opt for

„EXIT CONTROLLED LOOP‟. Following is an example of such loop:

III. do - while loop: this loop has also the same 4 elements as in case of „for‟ and „while‟ loop.

The

ONLY difference is the syntax.

Initilization ;

do {

loop body ;

update expression ;

} while (test – condition) ;

statement n ;

1. Initialize LOOP CONTROL variable.

2. Execute LOOP BODY.

3. UPDATE the LOOP CONTROL VARIABLE and JUMP back to STEP 2

4. Check the CONDITION. If TRUE enter the LOOP. If FALSE go to STEP 5.

5. Execute the statement JUST after the LOOP.

In the above loop, the control will enter the loop at least once because the condition is being tested at

the end of the loop. Such loop is also known as „Bottom Tested Loop‟.

METHODS/FUNCTIONS

It is a sequence of some declaration statements and executable statements. The reasons for creating methods

are:

To allow us to cope with complex problems: a complex and big task can be broken into

smaller and more manageable task by creating methods. This technique is known as “divide

and conquer”.

To hide low level details that otherwise can confuse users: at the user level we need not to

concern ourselves with how the method‟s task is performed. We just call it to get a specific

task done. Ex . Math.sqrt(56) ;

To reuse portions of code: once a task is packaged in a method, that method is available to

be accessed or called or invoked, from anywhere in a program. It can be called more than

once in a program. This concept is called as “Write Once, Use Many”

Method/Function Definition: in java, method (or function) must be defined before it is used anywhere in the

program. The syntax to define a method is:

(access-specifier) (modifier) (static) return_type method_name (parameter list) {

---- body of the method ----

}

We had earlier used JAVA‟s in built method of class „Math‟: Math.pow(x,y), Math.sqrt(x), Math.round(x).

Here, the methods are pow(x,y), sqrt(x), round(x) of class „Math‟. Thus, to use a method, the syntax is:

classname.methodname(list of parameters) ;

1

2

3

5

Move back to the TOP of the

LOOP if the condition is TRUE

4

Go to First statement after the LOOP

if the condition is FALSE

Note semi-colon ( ; ) here.

Page 39 of 64 [email protected]

access- specifier: can be either public or protected or private. These keywords are used to determine

the type of access to the method. Its optional.

modifier: can be final, native, synchronized, transient, volatile. It too is optional.

static: this keyword makes a method a „class method‟ and thus it can be called even by a class. In the

absence of this keyword, a class cannot directly call a method instead an object has to be created

which in turn calls a method.

return_type: specifies the type of value that a method will return to its calling program and the return

type can be: byte, short, int, long, float, double, char, String, array or an object. If a function is not

going to return any value than its return type should be “void” and that method should not

contain any „return‟ statement. It is necessary to provide a return type.

method_name: it should be a name that should follow the following rules:

should be meaningful and it should begin with a lowercase alphabet ONLY.

There shouldn‟t be any space or any other special character in the name.

Underscore character is allowed.

parameter list: this is a comma separated list of variables that a method will be receiving and these

parameters are referred as arguments or formal parameters.

Ex. long sqr (long a ) {

long res = a * a ;

return res ;

}

the return_type is long

the name of the method is sqr

the parameter list is a single variable of type long

the formal parameter is a

Ex. long sumsqr (long a, long b ) {

long res =( a * a ) + ( b * b ) ;

return res ;

}

the return_type is long

the name of the method is sumsqr

the parameter list are two variables of type long

the formal parameter are a and b

Ex. void threesymbols (String a ) {

System.out.println ( a + a + a );

}

the return_type is void

the name of the method is threesymbols

the parameter list is a single variable of type String

the formal parameter is a

it does not and should not have „return‟ statement as its return type is „void‟

Method Prototype is the first line of the method definition that tells the program about the type of value

returned by the method and the number and type of its parameters/arguments.

Method Signature refers to the number and type of arguments it will receive.

Method Definition

Method Definition

Method Definition

FORMAL PARAMETER

FORMAL PARAMETERS

Page 40 of 64 [email protected]

Now, in JAVA Methods always exist in a class. Thus a method had to be defined in a class in order to

access it. To create your first „CLASS‟ do the following:

You will see a dialog box and give the name of the class as “MyClass”. Now you will see coding window as shown below: public class MyClass { }

Note that a “class window” will not contain the GUI palette.

So, now we will write those methods that we have written earlier between these blocks of the class namely “MyClass” public class MyClass { static long sqr (long a ) {

long res = a * a ;

return res ; }

long sumsqr (long a, long b ) {

long res =( a * a ) + ( b * b ) ;

return res ; }

void threesymbols (String a ) {

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

} // class ends here Thus, the above class “MyClass” contains three “non-static methods” . The next step will be to call the method whenever they are required.

To create an object/instance of a class, „new‟ keyword is used. Now, to call the method in a GUI form:

For Methods that are non static, you have to first create an object of a class: o MyClass m1= new MyClass () ; The above statement will create an object ‘m1’ of class ‘MyClass’ with the help of the keyword ‘new’.

Now, the object can call the method as follows:

o m1.threesymbols(“ # ”) ; // Method call

o long r = m1.sumsqr( x , y) ; // since this method is returning a value of type long‟ we are storing the returned value in a variable of the same type i.e. „long‟.

But a „static method‟ can be called directly by a „class‟ and as such no need to create an „object‟ of a class. In the above class „sqr‟ method is a static method:

o long r = MyClass.sqr ( 12 ) ; The above statement will call „sqr‟ method with the class name rather than with the object.

All the methods should be defined between these blocks of this class named “MyClass

First Method

Second Method

Third Method

Page 41 of 64 [email protected]

long r = m1 . sumsqr ( x , y) ; // A METHOD CALL STATEMENT

The above statement will call the „sumsqr‟ method and will pass the value of „x‟ and „y‟ variables to it.

value of „x‟ will be copied to „a‟ and value of „y‟ will be copied to „b‟ and after that there is no connection between these variables whatsoever. This is „CALL BY VALUE‟

long sumsqr (long a, long b ) {

long res =( a * a ) + ( b * b ) ;

return res ; }

note that in : long sumsqr (long a, long b ) // „a‟ and „b‟ are termed as FORMAL PARAMETERS‟ The „return res‟ statement will copy the answer to calling statement and then it‟s up to the calling statement to how to use the returned value.

It can either print the value or

store the value in a compatible variable. o In our case the returned value gets stored in a variable named „r‟ of „long‟ data-type.

Thus, variables that appear in the method definition are termed as „FORMAL PARAMETERS‟ and variables that appear in the method call statement are termed as „ACTUAL PARAMETERS‟. Moreover, the technique in which actual parameters pass the value to the formal parameters of the method is termed as „CALL BY VALUE‟ and in this, changes made by formal parameters in the method is not reflected back in actual parameters. class MyMath {

static int fact(int n){ int f=1; for(int i=1;i<=n;i++) f=f*i; return f; } static int findmax(int a,int b, int c){ int max; max=a; if(b> max) max=b; if(c> max) max=c; return max; } static int countdigits(long n){ int c=0; while(n>0){ c=c+1; n=n/10; } return c; }

OBJECT NAME

METHOD NAME

ACTUAL PARAMETERS

Method Definition

x y

1 METHOD

CALLED

2 METHOD RETURNING

A VALUE

1. Method to find factorial of a number

2. Method to find maximum of three numbers

3. Method to find count of digits in a number

Page 42 of 64 [email protected] static long reversedigits(long n){ int c=0; long temp=0; while(n>0){ temp=(temp*10)+(n%10); n=n/10; } return temp; } static long adddigits(long n){ long sum=0; while(n>0){ sum=sum+(n%10); n=n/10; } return sum; } static long cubedigit(long n){ return n * n * n ; } static long sumofcube(long n){ long sum=0; while(n>0){ long i=n%10; sum=sum+cubedigit(i); n/=10; } return sum; } private static boolean isprime(long n){ boolean tf=true; for(long i=2;i<=n/2;i++){ if(n%i==0){ tf=false; break; } } return tf; } static boolean iseven(int n){ if(n%2==0) return true; else return false; } static String sign(long n){ if(n<0) return "Negative"; else if (n>0) return "Positive"; else return "Zero"; } static int findmin(int a,int b, int c){ int min; min=a; if(b< min) min=b; if(c> min) min=c; return min; }

4. Method to reverse a number

5. Method to find sum of individual digits of a number

6. Method to find cube of a number

7. Method to find sum of cube of individual digits of a number

8. Method to check whether a given number is a prime number or not

9. Method to check whether a given number is an even number or odd

10. Method to check whether a given number is +ive, -ive or zero

11. Method to find minimum of three numbers

Page 43 of 64 [email protected] static int secondMax(int n1, int n2, int n3, int n4) { int max1=n1; int max2=0; // coding for max and second max if(n2>max1) { max2=max1; max1=n2; } else if(n2>max2) { max2=n2; } if(n3>max1) { max2=max1; max1=n3; } else if(n3>max2) { max2=n3; } if(n4>max1) { max2=max1; max1=n4; } else if(n4>max2) { max2=n4; } return max2 ; } private static int sumPrime(long n){ long sum=0; boolean p=true; for( long k=1 ; k<=n ; k++) { p=true ; for(long i=2 ; i<=k/2 ; i++) { if( k % i == 0){ p=false; break; } // end if } // end inner for if(p==true) sum=sum + k ; } // end outer for return sum; } private static long totalEvens( long n) {

long n=Long.parseLong(t1.getText()); long counteven=0; long temp=n; while(temp>0){ long dig=temp%10; if(dig%2==0)counteven++; // 15. just change the condition to find „total odd digits‟ temp=temp/10; } return counteven ; } private static int maxDigit (long n) { long n=Long.parseLong(t1.getText()); long max=0; while(n>0){ long dig=n%10; if(dig>max) max=dig; // 17. Just change the condition to find min digit n=n/10; } return max ; } } // end MyMath class

NOW CREATE A JFRAME FORM AND CALL THE ABOVE CREATED METHODS. AN EXAMPLE IS GIVEN HERE:

String s=t1.getText(); long n=Long.parseLong(s); n=MyMath.reversedigits(n); // METHOD CALL t2.setText("Reverse is : " + n);

PRIMITIVE DATA TYPES ARE ALWAYS „CALLED BY VALUE‟ (byte, int, long, float, double, char, boolean, String )

USER DEFINED DATA TYPES ARE ALWAYS „CALLED BY REFERENCE‟ (objects of user defined class)

12. Method to find 2nd maximum of four numbers

13. Method to find sum of first „n‟ prime numbers

14. Method to find total even digits in a number

16. Method to find max digit in a number

Page 44 of 64 [email protected]

CLASSES AND OBJECTS

Class : this is a template from which you can create objects. The definition of class includes the formal specifications for the class and any data and method in it. Object: this is an instance of a class much as a variable is an instance of a data type. We can think of a class as the type of an object. Every object has got (a) state/characteristics (Data Members) and (b) behaviour (methods/functions)

Data members: those variables that are part of a class. We use them to store the data the object uses. Objects supports both „instance variables‟ whose values are specific to the object and „class/static variables‟ whose values are shared among the objects of a specified class.

Methods/Functions: this is a function built into a class or object. We have instance and class methods. We can use instance methods with objects and class /static methods just by referring to the class name, no object is required.

Class declaration and definition syntax: [access] class class_name [extends …] [implements…] { // class definition [access] [static] type variable1; [access] [static] type variable2; . [access] [static] type variableN; [access] [static] return-type method1([parameter-list]) { (method definition) ….. }

[access] [static] return-type method2([parameter-list]) { (method definition) ….. } [access] [static] return-type methodN([parameter-list] { (method definition) ….. } } // end class definition The keyword „static‟ turns variable into a class variable and a method into a class method. The „access‟ term specifies the accessibility of the class or a class method or a class variable to the rest of the program and it can be public, private or protected. Instance and Class variables: instance variables are specific to the objects. If you have 2 objects(i.e. two instances of a class), the instance variables in each object are independent of the instance variables in other object On the other hand, class variables of both the objects will refer to the same data and therefore will hold the same value. Ex. Create a class named „A‟ public class A { int x,y; // instance variables static int z; // static variable void add1(){ x++; y++; z++; } static void add10(){ z+=10; // not allowed x+=10; // not allowed y+=10; } void print1(){ System.out.println("x= "+ x + " y = " + y + " z= " + z); } static void print2(){ System.out.println(" z= " + z); } } // end class A

Page 45 of 64 [email protected] Now create a jFrame form and add a button in the form. Add the following code behind the button. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { A n1=new A(); A n2=new A(); n1.x=10; n1.y=20 ; n1.z=30 ; System.out.println("After initialising n1 object :"); System.out.print("n1.print1() : "); n1.print1(); System.out.print("n2.print1() : "); n2.print1(); n2.x=100; n2.y=200 ; n2.z=300 ; System.out.println("After initialising n2 object :"); System.out.print("n1.print1() : "); n1.print1(); System.out.print("n2.print1() : "); n2.print1(); System.out.println("After calling instance method add1() by object n1"); n1.add1(); System.out.print("Values of object n1 : " ); n1.print1(); System.out.print("Values of object n2 : " ); n2.print1(); System.out.println("After calling instance method add1() by object n2"); n2.add1(); System.out.print("Values of object n1 : " ); n1.print1(); System.out.print("Values of object n2 : " ); n2.print1(); System.out.println("After calling static method add10() by class A"); A.add10(); System.out.print("Values of object n1 : " ); n1.print1(); System.out.print("Values of object n2 : " ); n2.print1(); } Internally what happens is that : Object n1 Object n2 Static Values

In the above example, instance variables „x and y ‟ are different for both the objects. Thus changes made to „x and y ‟ by the object n1 is not reflected in object n2.

In the above example, the class /static variable „z‟ is same for both the objects or say both the objects share the same class variable „z‟. thus changes made to „z‟ by object n1 is reflected in object n2.

In the above example, there are 2 instance methods „add1() and print1()‟. These methods can ONLY be called by the instance/objects of a class. Such methods CANNOT be called by a class directly. Moreover, instance methods CAN ALSO work with static variables of a class. Ex. n1.add1(); //valid as object can access instance method

A.add1() ; // invalid as a class cannot directly access instance method

In the above example, there are 2 static methods: „add10() and print2()‟. These methods can be called by the instance/objects of a class AND CAN ALSO be called by a class directly. Moreover, static methods CAN ONLY work with static variables of a class and NOT instance variables. Ex. A.add10() ; // valid as class accessing class method

n1.add10() ; //valid as object can access class method

z

x y

add1()

print1()

add10()

print2()

x y

add1()

print1()

Page 46 of 64 [email protected] CONSTRUCTORS

These are special methods which have the same name as that of a class and its basic use is to initialize or provide a starting value to the objects of a class. Thus, a constructor:

1. It is a METHOD with the same name as that of a class. 2. It does NOT have a return type, not even void. 3. Is called automatically when an object is created. 4. It can be parameterized or non-parameterized. 5. There can be any number of constructors but with different signatures. 6. No need to call it explicitly as other methods.

class Student { int roll; String name;

float marks; public Student() { roll=1; name=”Ajay”; marks=45; } public Student(int r); roll=r; } public Student(int r, String n) { roll=r; name=n; } public Student(int r, String n, float m){ roll=r; name=n; marks=m; } public void printdata(){ System.out.println(“Roll No.= ” + roll); System.out.println(“Name = ” + name); System.out.println(“Marks = ” + marks); } } Now creating objects of the class: Student s1=new Student(); // calling no parameter constructor Student s2=new Student(2); // calling 1-parameter constructor Student s3=new Student(3,"Amit"); // calling 2-parameter constructor Student s4=new Student(4,"Bishnu",50); //calling 3-parameter constructor System.out.println("Object s1:") ; s1.printdata(); System.out.println("\nObject s2:") ; s2.printdata(); System.out.println("\nObject s3:") ; s3.printdata(); System.out.println("\nObject s4:") ; s4.printdata(); Internally the following happened:

A constructor with zero parameters. This

will initialize an objects all the three variables with the default value provided here.

A constructor with one parameter. This will

only initialize the „roll‟ variable of the class with the user supplied value. The other two variable will have „null‟ and 0.0

A constructor with two parameters. This

will initialize the „roll‟ and „name‟ variables of the class with the user supplied value. The other variable „marks‟ will have 0.0

A constructor with three parameters. This

will initialize the „roll‟ , „name „ and „marks‟ variables of the class with the user supplied value.

roll

name

marks

1

“Ajay”

45.0

Object: s1

roll

name

marks

2

null

0.0

Object: s2

roll

name

marks

3

“Amit”

0.0

Object: s3

roll

name

marks

4

“Bishnu”

50.0

Object: s4

Three instance variables of the class namely, roll, name and marks. Note that if you initialize a

variable at class level than this value will be treated as a default value for that variable.

Page 47 of 64 [email protected]

DATABASE CONNECTIVITY Database Connectivity helps a Front-End application like JAVA to connect to the database like MySQL.

JDBC(Java DataBase Connectivty) is a framework that helps you send and execute SQL statements from

within Java application code.

What does JDBC do?

1. Establish a connection with the database.

2. Send SQL statements to the database server.

3. Process the „resultset‟ obtained.

What are different classes used for database connectivity?

There are 4 main classes in the JDBC API that are generally used for database connectivity.

1. DriverManager Class: loads the JDBC driver needed to access a particular data source,

locates and logs on to the database and return a Connection object.

2. Connection class: manages the communications between a Java client application and a

specific database e.g. MySQL database.

3. Statement Class: contains SQL strings that are submitted to the DBMS. An SQL SELECT

Statement returns a „ResultSet‟ object that contains the data retrieved as the result of SQL

statement.

4. ResultSet Class: provides pre-defined methods to access, analyze and convert data values

returned by an executed SQL SELECT statement.

Steps for creating Database Connectivity Application:

1. Import the Packages: it is required for database programming.

import java.sql.*;

Also, add MySQL JDBC Driver to your project.

2. Register the JDBC Driver: this will iniatialise a driver, so you can open a communication channel

with the database from the Java Application.

A class named „Class‟ offers a method called „forName()‟ that registers the driver with the

DriverManager.

Class.forName(“java.sql.Driver”);

OR

Class.forName(“com.mysql.jdbc.Driver”);

3. Open a connection: this requires using the DriverMananger.getConnection() method to create a

connection object which represents a physical connection with the database. A “Connection”

represented through a „connection‟ object is the session between the application program and

the database. To do any operation on the database, one must have a connection object. To

connect to a database, you need to know database‟s complete URL, the userid and its

password.

Connection con=DriverManager.getConnection(“jdbc:mysql://localhost/mydatabase”,”root”,”1234”);

4. Execute query: in this step, you need to first create an object of type „Statement‟ for building and

submitting an SQL statement to the database using „createStatement()‟ method of „connection‟

type object.

Statement s=con.createStatement();

Next you need to execute the SQL statement using „executeQuery()‟ method. The method

returns a resultSet which is an object of ResultSet type and contains the resultant dataset.

ResultSet rs=s.executeQuery(“SELECT * FROM students WHERE std=12 ORDER BY roll”);

A resultset refers to a logical set of records that are fetched from the database by executing a

query.

Note that if the SQL statement is an Update, Insert or Delete statement, then you can execute

SQL query using executeUpdate() method.

ResultSet rs=s.executeUpdate(“DELETE FROM students WHERE std=12”);

Page 48 of 64 [email protected]

5. Extract data from the resultset: ResultSet object provides methods for obtaining column/field

data for a row: rs.getString(“regno”); // where regno is a field of students table.

getxxxx() methods provides the means for retrieving field values from the current row.

ResultSet Cursor: when the resultset object is first created the cursor is positioned before the

first row.

Various Navigational methods of ResutSet object

Method name Description

rs.first() Moves the cursor to the first row

rs.next() Moves the cursor to the next row in the recordset

rs.previous() Moves the cursor to the previous record in a recordset

rs.last() Moves the cursor to the last row in the recordset

rs.relative(int r) Moves the cursor relative to its current position. Ex if the cursor is at row/record 3, then rs.relative(4) will place the cursor at the 7th record in the resultset

rs.absolute(int r) Positions the cursor on the rth row of the resultset. Ex. rs.absolute(4) will place the cursor at the 4th record of the resultset

rs.getRow() Retrieves the current row number the cursor is pointing at.

We can sum up five basic steps to connect to the database as follows:

1. Importing Packages:

import java.sql.*;

2. Declare the following Global variables:

Connection conn=null;

Statement s;

ResultSet rs;

3. Registering the JDBC Driver:

Class.forName(“com.sql.jdbc.Driver”).newInstance();

4. Opening the Connection. To use DriverManager class you can do as follows:

String url=”jdbc:mysql://localhost/mydatabase”;

String user=”root”;

String pass=”1234”;

conn=DriverManager.getConnection(url,user,pass);

5. Executing the SQL statements.

s=conn.createStatement();

rs=s.executeQuery(“SELECT * FROM students WHERE std=12”);

How to retrieve a data based on user specified value: Enter Class tClass Enter Section tSection rs=s.executeQuery(“Select * From students Where std= ” + tClass.getText() + “ and section= ” + tSection.getText() );

Note that there should be a space between “....std= ” & “ and section= ”

Page 49 of 64 [email protected]

INHERITANCE Inheritance is the capability of one class to derive properties from another class. Thus, the class inheritance lets you derive new classes called „derived classes‟ from old ones with the derived class inheriting the properties and methods of the old class known as base class. Need:

1. Reusability: it allows addition of new features to an existing class without modifying it. One can derive a new class(subclass or derived class) from an existing one and new features to it.

2. Transitivity: this means, if a class B inherits properties of another class A, then all the subclasses of B will automatically inherit the properties of A.

Types of Inheritance:

1. Single Inheritance: when a class is derived from one base class ONLY.

2. Multiple Inheritance: when a class is derived from more than one base class.

3. Hierarchical Inheritance: when more than one class is derived from ONE base class.

4. Multi-Level Inheritance: when a subclass is derived from a class that itself is derived from another class.

5. Hybrid Inheritance:

A

B

C

A B

C

A

B C D

A

B

A

B

C

A

B C D

B C D

Page 50 of 64 [email protected] Syntax:

class <derived-class> extends <base-class>{ -----;

} Example: class One { private int a ; char b; protected double z; One(){ System.out.println(“Constructor of class One”); } } class Two extends One{ int x,y; //new members of subclass Two(){ System.out.println(“Constructor of class Two”); } } Here the class „Two‟ is a sub-class or a derived class of the class „One‟ which is the base or superclass. Note that while extending classes instance variables and methods of super-class also become part of the new sub-class. Now the question arise, can a sub-class can access all the members of its super-class? the answer depends on the various access-specifiers used for the members of a super-class.

Access Specifiers/Access Control of Inherited Members Although a sub-class inherits all the members of its super-class, yet it can access only those variables or methods for which it has access permissions. In other words, the access of inherited members depends upon their access modifiers i.e. whether they are private or public or protected.

Modifiers Specification

private Members are accessible only inside their own class where they have been originally declared and nowhere else.

public Members are accessible in all the classes whether a sub-class or class in the same package or class in another class along-with their own class

protected Members are accessible inside their own class as well as in all sub-classes of their class, regardless of whether sub-classes exist in the same package or any other package.

default These are those members that are declared without any access modifiers i.e. only with a data type. These members are accessible only inside those classes that are in the same package.

private protected

These members are accessible only from sub-classes whether in the same package or any other package

Modifier Inside own class

Inside sub-classes Inside non-sub-classes

In the same package

In other packages

In the same package

In other packages

public Yes Yes Yes Yes Yes

protected Yes Yes Yes Yes No

default Yes Yes Yes No No

private protected

Yes Yes Yes No No

private Yes No No No no

Things you should know about the Inheritance in JAVA:

Java allows ONLY single Inheritance and Hierarchical and Multi-Level Inheritance which means that a class has at most one immediate super-class.

Every class in Java has one and only one immediate/direct super-class, but might have several sub-classes.

The inheritance relationship is transitive. Therefore, every class inherits variables and methods from all classes which are higher in the class hierarchy (direct or indirect super-class)

Page 51 of 64 [email protected]

Overriding methods and Hiding Member Variables: Sometimes, a sub-class uses the same name for variables and methods as in the super-class. This leads to the following behaviour:

Methods are OVERRIDEN

Variables are HIDDEN class A{ void print1(){ System.out.println(“The class A”); } } class B extends A { void print1(){ System.out.println(“The class B”); } } Coding behind a BUTTON: B objB1=new B(); objB1.print1(); In the above example, the „print1‟ method of class B will be executed and Not that of the class A. You can say „print1()‟ method of class A will be overridden by the „print1()‟ method of class B. Similarly, variables of super-class are said to be HIDDEN, if the variable with the same name and type exist in the sub-class or derived class. Thus, a method in a sub-class hides or overshadows a method inherited from the super-class if both methods have the same signature i.e. same name, number and type of arguments, and the same return type. This property is known as Overriding the inherited methods. You can still refer to the method of the super-class by using the keyword super i.e. super.overridenMethod() refers to the method as it is defined in the super-class. Similarly, you can refer to the super-classes hidden variable by : super.hiddenVariable class A{ void print1(){ System.out.println(“The class A”); } } class B extends A { void print1(){ System.out.println(“The class B”); } void print2(){ super.print1(); } Coding behind a BUTTON: B objB1=new B(); objB1.print1(); // print1 of class B will be called objB1.print2(); // print2 of class B will be called which in turn will call print1 of class A

NOTE that an object of a sub-class cannot directly access an Overridden method of super-class. it can do so by calling a method of the sub-class which in turn can call the Overridden method of the super-class with the keyword „super‟.

The keyword „final‟:

Using final keyword with a variable makes it a constant and they cannot be changed in the class and sub-classes.

Using final keyword with methods will not allow them to be overridden by sub-classes methods.

Using final keyword with a class will not allow it to be extended or say inherited.

Page 52 of 64 [email protected] Example to depict the concepts of:

Overridden Methods Hidden Variables Accessing Overridden Methods Accessing Hidden Variables

class superClass { String id=”id of super-class”;

void print() { System.out.println(“print method of the super-class”); }

} class subClass extends superClass { String id=”id of sub-class”; //overriding super-classes variable id

void print() { // overriding super-classes method print() System.out.println(“print method of the sub-class”); } void print2(){ System.out.println(id); print() ; System.out.println();

System.out.println(super.id); // accessing the hidden variable of the superclass super.print(); // accessing overridden method of the superclass }

} The OUTPUT of the method print2() will be: id of sub-class print method of the sub-class id of super-class print method of the super-class

Method Overloading/Function Overloading A function name having several definitions in the same scope that are differentiated by the number and type of arguments is said to be an overloaded functions or methods.

The key to Method Overloading is a method‟s argument list which is also known as the function signature. It is the signature and not the function type that enables function overloading.

A function‟s argument list is known as a function‟s signature. Functions with the same name and signature but different return types are not allowed in Java. But you can have functions with the same name and different return types ONLY IF their signature is

different. o Same name, different return types and different signatures

int sqr(int n) { return n * n ; } float sqr(float n) { return n * n ; }

o Same name, same return type and different signatures void sqr(int n) { System.out.println( n * n ) ; } void sqr(float n) { System.out.println( n * n ) ; }

o Same name, same signature but different return type are NOT ALLOWED but if the

signatures of two functions differ in either the number or type of their arguments, the two methods are considered to be OVERLOADED

Page 53 of 64 [email protected]

ABSTRACT CLASSES

An ABSTRACT class is the one that simply represents a concept and whose objects can‟t be created. Such a class is created through the keyword „abstract‟.

An ABSTRACT class needs to be extended or inherited because such a class cannot create an object of its type.

Example: public abstract class Shape { String name; double area ; public void display(){ } } class Circle extends Shape { ........... } class Rectangle extends Shape { ........ }

ABSTRACT METHODS

AM‟s are methods with no method statements. Sub-classes must provide the method statements for the inherited abstract methods.

To define a method as abstract, we need to use the keyword „abstract‟ with the method and its declaration with a semi-colon.

The „abstract methods‟ of super-class would require overriding in each sub-class. public abstract class Shape { String name; double area ; public abstract void display() ; // an abstract method } class Circle extends Shape{ double radius; double calcArea() { return 3.154 * radius * radius ; } public void display() { //overriding abstract method display() System.out.println(“Radius= ” + radius); System.out.println(“Area= ” + area) ; } }

A sub-class cannot override methods that are declared „final‟ in the super-class. A sub-class must override methods that are declared „abstract‟ in the super-class or the sub-class itself

must be abstract.

INHERITANCE AND CONSTRUCTORS Constructor Functions, even though, they are member methods of the class, are not inherited by the sub-class. We can explicitly call the constructor of the super-class using the keyword „super‟. Ex. to call the constructor of the super-class A in sub-class B: super() ; Such an explicit call of the constructor of a super-class must be the first statement in the sub-class constructor.

Page 54 of 64 [email protected]

HTML

1. A web browser is a WWW client that navigates through the WWW and displays web pages.

2. Web Servers are computers on which web documents reside. They provide 4 major function: Serving web pages Running gateway programs Controlling access to the server Monitoring and logging server access

o Example, apache web server, MS internet Information Server(IIS), netscape navigator server

3. A location on a web server is called a web site

4. Each web site has got a unique address called URL (Uniform Resource Locator)

5. A set of rules on which the internet structure of WWW is built is called HTTP (HyperText Transfer

Protocol)

6. A file‟s internet address or URL is determined by: o The type of server or protocol like http. o The name of the server or domain name, like yahoo.com o The location of the file on the server, like http://yahoo.com/index.htm

HTML: it is a page-layout and hyperlink specification markup language. It is NOT a programming language. HTML is made up of elements or tags and its attributes which work together. A TAG is a coded HTML command that indicates that how a part of a web page should be displayed. An ATTRIBUTE is a special word used with a tag to specify additional information to the tag. TML tags are contained within angle brackets (<>). These tags or elements are NOT CASE SENSITIVE. The basic structure of writing HTML file is as follows: <HTML> <HEAD> <TITLE> MY FIRST WEB PAGE </TITLE> </ HEAD> <BODY> ACTUAL CONTENT TO BE DISPLAYED ON THE WEB PAGE THE VARIOUS HTML TAGS ARE DEFINED HERE </ BODY> </ HTML>

<HTML> tag identifies the document as HTML document.

<HEAD> tag contains information about the document title, scripts used, style definitions and document descriptions.

<TITLE> tag contains the document‟s title. It is included with the <HEAD> tag.

<BODY> tag encloses all tags and their attributes and the information to be displayed in the web page. HTML documents can be written in notepad or any text editor and has to be saved with an extension „.htm‟ or „.html‟. Container elements or tags require pair tags i.e. starting as well as ending tag. Empty tags require just a starting tag only ex. <br>, <hr> etc.

Page 55 of 64 [email protected] The syntax to write a tag: <TAGNAME ... ATTRIBUTE=VALUE... ATTRUBUTE=VALUE... ATTRIBUTE=VALUE..> </ TAGNAME> Every HTML element consists of a tag-name followed by an optional list of attributes and their values and all placed between opening and closing angle brackets. Tag attribute come after tag-name each separated by one or more space. A tag attribute‟s value, if any, is given after an equal to (=) sign. Note that, if value of an attribute is a single word then no need to put a double quote around that value otherwise you have to put a double quote. HTML TAGS/ELEMENTS

1) <HTML>

2) <BODY>

a. ATTRIBUTES:

i. BACKGROUND=”imagefile.jpg”

ii. BGCOLOR=color-code OR color-name

iii. TEXT=text-color

iv. ALINK=active-link color

v. VLINK=visited-link color

vi. TOPMARGIN=value in pixels

vii. LEFTMARGIN=value in pixels

3) <H1> TO <H6>

a. ATTRIBUTES:

i. ALIGN=center/right/left

<H1> TO <H6> tags are differentiated from each other through these factors: typeface, point-

size and space above and below them.

4) <BR> - this will move the following text to the next immediate line without any space.

5) <P> - this will move the following text to the next line leaving one blank line in between.

a. ATTRIBUTES:

i. ALIGN=center/right/left

6) <CENTER> - this will centralize a segment of text.

7) <BASEFONT> -

a. ATTRIBUTES:

i. SIZE= 1 TO 7 or relative +1 + 2 ....

ii. FACE= any font name

iii. COLOR= color code or color name

8) <FONT>

a. ATTRIBUTES:

i. SIZE= 1 TO 7 or relative +1 + 2 ....

ii. FACE= any font name

iii. COLOR= color code or color name

Note that BASEFONT is used to set default settings for a text. This is because it affects all the text that

follows it until a new tag affecting that is encountered. While FONT tag affects a text up-to its closing tag

ONLY.

Page 56 of 64 [email protected]

9) <HR> produces a horizontal line spread across the width of the browser window.

a. ATTRIBUTES:

i. SIZE= 3(default) – 72 pixels This attribute specifies the thickness.

ii. WIDTH= percentage of the window covered by ruler

iii. COLOR= name or color code

iv. NOSHADE to display rule in flat 2D. The default is 3D

10) <B> Bold Text </B>

11) <I> Italic Text </I>

12) <U> Underlined Text </U>

13) <TT> Typewriter text </TT>

14) <SUB> Subscript Text </SUB>

15) <SUP> Superscript Text </SUP>

Nesting Tags:

<CENTER> <B> <U> A NESTED TEXT </U> </B> </CENTER>

In such case, the innermost tag must be closed first and then the outer one.

LISTS: These are values arranged in some specific order. There can be three types of Lists:

Ordered (OL) Un-Ordered (UL) Definition (DL)

16) <OL> ..... <LI> :this is a numbered or ordered list. The default list is 1,2,3 ..... the <LI> tag specifies the

List Item to be displayed

a. ATTRIBUTES:

i. START= a number. This attribute will change the start value of the list.

ii. TYPE=can be: A / a / I / i /1

17) <UL> ...... <LI>: this is an un-ordered or bulleted list. The default list is a solid circle (disc) ..... the <LI>

tag specifies the List Item to be displayed

a. ATTRIBUTES:

i. TYPE=can be: DISC (solid circle) / CIRCLE ( hollow circle) / SQUARE (solid square)

18) <DL>...... <DT> ..... <DD>: a definition list (<DL>) consist of alternating a „definition term‟(<DT>) and a

„definition description‟(<DD>)

a. ATTRIBUTES:

i. COMPACT with this attribute, <DD> appears on the same line with <DT>

Example:

<HTML>

<HEAD>

<TITLE>My first page</TITLE><BR>

</HEAD>

<BODY BGCOLOR= yellow TEXT=blue >

<H1> <CENTER> Heading H1</CENTER> </H1>

<H2> Heading H2 </H2>

<B> Bold Element </B>

Normal

<BR> <U> Underine Element </U>

<BR> <I> Italic Element </I>

<BR><SMALL>small Element</SMALL>

<BR> 2

<FONT FACE=broadway COLOR=maroon SIZE=21>X</FONT>avier's

<HR SIZE=12 NOSHADE COLOR =green>

<BR><TT> This is a typewrite Text </TT>

<BR> H <SUP>2</SUP>SO<SUB>4</SUB>

<BR> &lt; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

&gt;

Page 57 of 64 [email protected]

<OL TYPE=A START= 5>

<LI> HARDWARE

<LI> SOFTWARE

<OL>

<LI> OS

<LI> SYSTEM S/W

</OL>

<LI> FIRMWARE

<LI> MALWARE

</OL>

<UL TYPE=disc>

<LI> HARDWARE

<LI> SOFTWARE

<OL>

<LI> OS

<LI> SYSTEM S/W

</OL>

<LI> FIRMWARE

<LI> MALWARE

</UL>

<DL>

<DT> HTML

<DD> HYPERTEXT MARKUP LANGUAGE

</DL>

<DL COMPACT>

<DT> XML

<DD>EXTENSIBLE MARKUP LANGUAGE

</DL>

</body>

</html>

Table Heading Columns(TH)

Table Rows(TR)

Table Data for each column(TD)

Page 58 of 64 [email protected] <HTML>

<HEAD>

<TITLE> TABLES </TITLE>

</HEAD>

<BODY>

<H1> HTML 2ND ASSIGNMENT : TABLES 1</H1>

<TABLE BORDER=2>

<THEAD>

<TR> <TD> THIS IS A TABLE HEADER

</THEAD>

<TBODY>

<CAPTION> THIS IS A TABLE CAPTION </CAPTION>

<TH> ROLL <TH> NAME <TH> PHONE

<TR> <TD> 1 <TD width=170> AMIT SHARMA <TD>9213214455

<TR> <TD> 2 <TD> SUBHASH V <TD>8764150339

<TR> <TD> 3 <TD> ASHOK SINGH <TD>9828119759

<TR> <TD> 4 <TD> NIKHIL <TD> 9828211044

</TBODY>

<TFOOT>

<TR> <TD> THIS IS A TABLE FOOTER

</TFOOT>

</TABLE>

<CENTER> <U>USING FONT ELEMENT </U></CENTER> <P>

<FONT FACE=IMPACT SIZE="6" COLOR=MAROON> I </FONT> NDIA IS MY COUNTRY <P>

THE GRASS IS <FONT FACE=BROADWAY SIZE="7" COLOR=GREEN> GREEN </FONT>

AND SKY IS <FONT FACE=BROADWAY SIZE="7" COLOR=BLUE> BLUE </FONT>

</BODY>

</HTML>

19) <TABLE> : as seen in the above example of a table, a table is a grid of columns and rows. It has got

many sub-elements as described below:

a. <CAPTION>: this sub-element is used to give a caption or title to the table.

b. <TH>: this sub-element is used to define the table‟s column headings. The data provided within

this element appears „bold‟ and „centralized‟ automatically.

c. <TR>: this sub-element is used to start a new row for the table. Every <TR> starts a new row in

the table.

d. <TD>: this sub-element specifies the value that will appear for a particular column. Every <TD>

will display the value under a new column.

e. <THEAD>: this sub-element is used to define a set of header rows.

i. There can be ONLY 1 <THEAD> in the table.

ii. Rows specified in <THEAD> will be repeated at the top of every page if the table spans

more than one page.

Page 59 of 64 [email protected]

f. <TBODY>: this sub-element contains the rows to be displayed in the table.

g. <TFOOT>: this sib-element is used to define a set of footer rows.

i. There can ONLY 1 <TFOOT> in the table.

ii. It must precede the <TBODY> (if any) element.

iii. Rows specified in <TFOOT> will be repeated at the bottom of every page if table spans

more than one page.

Various attributes of the <Table> tag and its sub-elements:

<TABLE>

o BORDER = n [ 0 is no border, 1 / 2 / 3 / …. SPECIFIES THE THICKNESS]

o BORDERCOLOR=color-name or color-code

o FRAME=above/below/border/box/hsides/lhs/rhs/void/vsides – allows you to choose

which portion of the border will be displayed.

above: displays top edge only

below: displays bottom edge only

border: displays all 4 sides(default)

box: displays all 4 sides like border

hsides: displays top and bottom edge only

lhs: displays left edge only

rhs: displays right edge only

void: displays no border

vsides: displays left and right edges

o RULES=all/cols/groups/none/rows - deals with inside border.

all: displays all border

cols: displays border within cells

groups: displays border between all cell groups

none: hides all interior borders.

Rows: displays border between rows only

o CELLSPACING =in pixels – this is the amount of space between cells.

o CELLPADDING = in pixels - this is the amount of space between cell border and cell

content.

o ALIGN=left/right/center

o BACKGROUND= the image file address

o BGCOLOR= color code or color name

o HEIGHT= in %age or pixels

o WIDTH=in %age or pixels

o SUMMARY=

<TD> Tag: its attributes will apply ONLY for a particular cell and its content.

o ALIGN=left/right/center - controls the horizontal alignment of the cell content.

o WIDTH= pixels or percentage - specifies the width of the cell

o BACKGROUND= image file that will be set ONLY for a particular cell.

o BGCOLOR= color that will be set ONLY for a particular cell.

o ROWSPAN= the amount of row that a cell content will cover or span.

o COLSPAN= the amount of column that a cell content will cover or span

o VALIGN= top/middle/bottom - in cells that have span of more than one rows,

data can be vertically aligned.

Page 60 of 64 [email protected]

<TR> tag and <TH> : its attributes are applied to the all the cells of a particular row.

o ALIGN= left/center/right

o WIDTH= in pixels or percentage

o BACKGROUND= image file for that particular row

o BGCOLOR=color code or color name for that particular row

o VALIGN=top/middle/bottom

Table Example 2:

<html>

<head>

<title> My Page</title>

</head>

<body>

<table border=3 cellspacing=16 cellpadding=20 bgcolor=grey>

<caption>ABC Co.Sales </Caption>

<tr bgcolor=blue> <th>zone <th>qtr1 <th>qtr2

<tr> <td bgcolor=red> Delhi <td> 12133 <td> &nbsp;

<tr> <td>Mumbai <td>1530 <td>1800

<tr> <td> jaipur <td> 10 <td>12

<tr> <td>jodhpur <td>1530 <td>1800

<tr> <td colspan =2 align=center> Bikaner <td>1400

<tr > <td rowspan=2 bgcolor=blue>Delhi <td> UP <td>MP

<tr> <td> Sikkim <td> HP

</table>

<a href="C:\Users\subhashv\Music\hindi songs\mysong1.mp3">Play</a>

</body>

</html>

20) <FORM> tag:

HTML Forms

Forms are a vital tool for the webmaster to receive information from the web surfer, such as: their name, email address, credit card, etc. A form will take input from the viewer and depending on your needs, you may store that data into a file, place an order, gather user statistics, register the person to your web forum, or maybe subscribe them to your weekly newsletter.

Text Fields

<input> has a few attributes that you should be aware of.

type - Determines what kind of input field it will be. Possible values are: password: to create a password box text: to create text-field radio: to create radio button checkbox: to create check-box

name - Assigns a name to the given field so that you may reference it later. size - Sets the horizontal width of the field. The unit of measurement is in blank spaces. maxlength - Dictates the maximum number of characters that can be entered.

HTML Code:

<form method="post" action="mailto:[email protected]"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"> </form>

Input Forms:

Name:

Password:

Page 61 of 64 [email protected] Do not use the password feature for security purposes. The data in the password field is not encrypted and is not secure in any way.

HTML Form Email

Now we will add the submit functionality to your form. Generally, the button should be the last item of your form and have its name attribute set to "Send" or "Submit". Name defines what the label of the button will be. Here is a list of important attributes of the submit:

In addition to adding the submit button, we must also add a destination for this information and specify how we want it to travel to that place. Adding the following attributes to your <form> will do just this.

method - We will only be using the post functionality of method, which sends the data without displaying any of the information to the visitor.

action - Specifies the URL to send the data to. We will be sending our information to a fake email address.

HTML Code:

<form method="post" action="mailto:[email protected]"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"><br /> <input type="submit" value="Send"> </form>

Email Forms:

Name:

Password:

Send

Simply change the email address to your own and you will have set up your first functional form!

HTML Radio Buttons

Radio buttons are a popular form of interaction. You may have seen them on quizzes, questionnaires, and other web sites that give the user a multiple choice question. Below are a couple attributes you should know that relate to the radio button.

value - specifies what will be sent if the user chooses this radio button. Only one value will be sent for a given group of radio buttons (see name for more information).

name - defines which set of radio buttons that it is a part of. Below we have 2 groups: shade and size. To group a set of radio buttons, their “name” attribute should have the same name.

HTML Code:

<form method="post" action="mailto:[email protected]"> What kind of shirt are you wearing? <br /> Shade: <input type="radio" name="shade" value="dark">Dark <input type="radio" name="shade" value="light">Light <br /> Size: <input type="radio" name="size" value="small">Small <input type="radio" name="size" value="medium">Medium <input type="radio" name="size" value="large">Large <br /> <input type="submit" value="Email Myself"> </form>

Radios:

What kind of shirt are you wearing?

Shade: Dark Light

Size: Small Medium Large

Email Myself

If you change the email address to your own and "Email Myself" then you should get an email with "shade=(choice) size=(choice)".

Page 62 of 64 [email protected]

HTML Check Boxes

Check boxes allow for multiple items to be selected for a certain group of choices. The check box's name and value attributes behave the same as a radio button.

HTML Code:

<form method="post" action="mailto:[email protected]"> Select your favorite cartoon characters. <input type="checkbox" name="toon" value="Goofy">Goofy <input type="checkbox" name="toon" value="Donald">Donald <input type="checkbox" name="toon" value="Bugs">Bugs Bunny <input type="checkbox" name="toon" value="Scoob">Scooby Doo <input type="submit" value="Email Myself"> </form>

Check Boxes:

Select the 2 greatest toons.

Goofy

Donald

Bugs Bunny

Scooby Doo

Email Myself

HTML Drop Down Lists

Drop down menus are created with the <select> and <option> tags. <select> is the list itself and each <option> is an

available choice for the user.

HTML Code:

<form method="post" action="mailto:[email protected]"> College Degree? <select name="degree"> <option>Choose One</option> <option>Some High School</option> <option>High School Degree</option> <option>Some College</option> <option>Bachelor's Degree</option> <option>Doctorate</option> <input type="submit" value="Email Yourself"> </select> </form>

Drop Down Lists:

Education? Choose One Email Yourself

HTML Selection Forms

Yet another type of form, a highlighted selection list. This form will post what the user highlights. Basically just another type of way to get input from the user.

The size attribute selects how many options will be shown at once before needing to scroll, and the selected option tells the browser which choice to select by default.

HTML Code:

<form method="post" action="mailto:[email protected]"> Musical Taste <select multiple name="music" size="4"> <option value="emo" selected>Emo</option> <option value="metal/rock" >Metal/Rock</option> <option value="hiphop" >Hip Hop</option> <option value="ska" >Ska</option> <option value="jazz" >Jazz</option>

Page 63 of 64 [email protected]

<option value="country" >Country</option> <option value="classical" >Classical</option> <option value="alternative" >Alternative</option> <option value="oldies" >Oldies</option> <option value="techno" >Techno</option> </select> <input type="submit" value="Email Yourself"> </form>

Selection Forms:

Musical Taste

Emo

Metal/Rock

Hip Hop

SkaEmail Yourself

HTML Text Areas

Text areas serve as an input field for viewers to place their own comments onto. Forums and the like use text areas to post what you type onto their site using scripts. For this form, the text area is used as a way to write comments to somebody.

Rows and columns need to be specified as attributes to the <textarea> tag. Rows are roughly 12pixels high, the same as in word programs and the value of the columns reflects how many characters wide the text area will be. i.e. The example below shows a text area 5 rows tall and 20 characters wide. Another attribute to be aware of is the wrap. Wrap has 3 values.

wrap= "off" "virtual" "physical"

Virtual means that the viewer will see the words wrapping as they type their comments, but when the page is submitted to you, the web host, the document sent will not have wrapping words. Physical means that the text will appear both to you, the web host, and the viewer including any page breaks and additional spaces that may be inputed. The words come as they are. Off of course, turns off word wrapping within the text area. One ongoing line.

HTML Code:

<form method="post" action="mailto:[email protected]"> <textarea rows="5" cols="20" wrap="physical" name="comments"> Enter Comments Here </textarea> <input type="submit" value="Email Yourself"> </form>

Text Area:

Enter Comments Here

Email Yourself

Also note that any text placed between the opening and closing textarea tags will show up inside the text area when the browser views it.

Page 64 of 64 [email protected]

<html>

<head>

<title> </title>

</head>

<body bgcolor=yellow>

<FORM METHOD=GET>

Enter Name <input type=text name=uname> <br> <hr size=3>

Enter Password <input type=password name=pwd> <br>

Stream <input type=radio name=str value=sc> Science

<input type=radio name=str value=comm> Commerce

<input type=radio name=str value=ar> Arts <br><br>

Hobbies : <input type=checkbox name=hobbies value=cr>Cricket

<input type=checkbox name=hobbies value=foot>FootBall

<input type=checkbox name=hobbies value=volley>VolleyBall <br><br>

City : <select name=city>

<option> Jaipur

<option>Ajmer

<Option> Kota

</select> <br><br>

City : <select name=city size=5>

<option> Jaipur

<option>Ajmer

<Option> Kota

</select>

Your Comments : <textarea cols=40 row=5 name=suggest> </textarea>

<br> <input type=reset value=Clear>

<br><br> <input type=submit value="Proceed">

</body>

</html>


Recommended