12 Ip Java Notes 1

Share Embed Donate


Short Description

IP Java Notes for Class 11 and 12...

Description

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)

JAVA PROGRAM

CONSTANTS/ LITERALS

VARIABLES

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

NUMERIC CONSTANTS

STRING CONSTANTS

Can ONLY be Numbers.

These are any characters i.e. alphabets, numbers or special characters enclosed in Double Quotes (“ “).

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

Ex. “123”, “Hello”, “####”, “12 + 10 = “ 

Numbers inside quotes are treated as a STRING and NOT as a NUMBER

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 1X2=  Adding two Strings will join or concatenate them i.e.  Adding two Numbers will sum them i.e.  Any NUMBER added with STRING will result in a STRING i.e.

“12” + “13” will result in 12 + 13 will result in

“1213” 25

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.

Page 4 of 64

[email protected]

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

In JAVA Programming Language, Numeric Variables/Constants can further be sub-divided into the following types: Byte 1 byte These types o byte differ in the Short 2 byte capacity of o short Integer Types numbers that Int 4 byte they can o int store Long 8 bytes o long Float 8 bytes o float Real Types Double 16 bytes 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:

;

2. To STORE value in variable the syntax is:

= ;

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: MEMORY byte b1;

b1

s1

n1

n2

short s1; int n1;

n3

long n2; float n3; double n4; String s2;

s2

n4

Page 5 of 64

[email protected] MEMORY

How to STORE: b1 b1 = 23 ;

s1

23

123

n4 = 657.43876 ;

452

123456 n4

12345.765

n2 = 123456 ; n3 = 12345.765 ;

n2

n3

s1 = 123; n1 = 452 ;

n1

657.43876

s2 St. Xaviers School, Jaipur

s2 = “St. Xaviers School, Jaipur” ; YOU CAN DEFINE AND STORE SIMULTANEOUSLY ALSO : byte b1 = 23 ;

In this piece of code you are storing a constant value in these variables.

short s1 = 123; int n1 = 452 ;

If CONSTANT is numeric, then VARIABLE should also be a numeric.

long n2 = 123456 ; float n3 = 12345.765 ;

If CONSTANT is a string, then VARIABLE should also be a string.

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

Also, you CANNOT store real numbers in integer type variables

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 :

ab

new

long

12ab

….

1a

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

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:

MEMORY

byte b1 = 12 ; b1

short s1 = b1 * 10 ; int n1 = b1 + s1 * 2 + 10 ;

12

16.0

double n4 = n1 + n2 + n3 /10 ; String s2 = “10” + “dulkar” ;

120

n1 262

n2 32

n3

long n2 = n1 / s1 + 10 * 3 ; float n3 = n2 / 2 ;

s1

n4 295.6

s2 “10dulkar”

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.

Page 7 of 64 Example - Parentheses

[email protected]

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 ++ --

&& Remember only

||

! ~ unary + - pre ++ -- unary operators

?:

(type) new

*/%

= += -= etc

*/%

+-

+-

comparisons

> >>>

&& ||

< >= instanceof = assignments == !=

Use () for all others

& ^ |

1. Arithmetic Operators: a. +

->

2 +4=6

b. -

->

21 – 2 = 19

c. *

->

2*3=6

d. /

->

13 / 2 = 6

e. %

->

13 % 2 = 1

13.0 / 2 = 6.5

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=

->greater or equal

->

12>=12

true

iv. less or equal

->

4not 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(&&)

OR(||)

^

C1

C2

RESULT

C1

C2

RESULT

C1

C2

RESULT

T

T

T

T

T

T

T

T

F

T

F

F

T

F

T

T

F

T

F

T

F

F

T

T

F

T

T

F

F

F

F

F

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

+

short nt

bytei nt

*

long

/

-

int

short

long

long

long

 Pure Real expressions where all the operands are real constants and/or real type variables and it results in a real value only. float

+

double

float nt

*

/

double

-

float

double

double

double

double

 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. int

+

long

*

float nt

/

double

-

short

float

double

double

double

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.

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 ;

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.

double n2 ; n2 = a ;

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

int a ; double n2= 121 ;

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

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 ;

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

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

.

class

sqrt method

( double type constant or variable) parameter

 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

Page 11 of 64  Math.pow(double,double)

[email protected] >

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:

 2ab + ab

2

x

2a2 + ba

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



To convert STRING number into SHORT : o



Long.parseLong()

To convert STRING number into FLOAT : o



Integer.parseInt()

To convert STRING number into LONG : o



Short.parseShort()

To convert STRING number into INT : o



Byte.parseByte()

Float.parseFloat()

To convert STRING number into DOUBLE : o

Double.parseDouble()

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 ?” );

STRING CONSTANT

STRING CONSTANT

STRING VARIABLE

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.

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 see the following screen.

6.

and click on „Finish‟ Button. Now you will

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.

GRAPHICAL USER PALETTE

FORM

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

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.

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

There will be many methods associated with different GUI control variables. To use a method you should use the following syntax: guicontrolname.methodname(); 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.

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

String s1= txtN1.getText() ;

Ex.

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( ) 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. String s1=” Welcome to my Program” ;

Ex.

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

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



long



byte



float



int



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

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

long

float

double

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

Statement 1

Statement 2

Statement 3

STOP

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¨ CONDITION

r¨ ;g dj¨

ugh r¨ og dj¨

TRUE

FALSE

START

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.

Statement 1

If – else block

Statement 2

F Condition ?

T Statement 3

Statement 5

Statement 4

Statement 6

Statement 7

Statement 8

STOP

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. In the Flow Chart, you can see that,

START

Statement 1 Statement 2 Statement 5 and Statement 6 will be executed in the program.

Statement 1

Statement 2

And till condition is TRUE: Statement 3 and Statement 4 will be executed again and again.

Condition ?

Loop body

T F

Statement 3

And when the condition becomes FALSE control comes out of the loop and : Statement 5 and Statement 6 will be executed in sequence.

Statement 4

Statement 5

Statement 6

STOP

BLOCKS

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

Block begins with opening curly bracket

int a=10; b= a+ c ;

These 3 statements are part of a block.

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

Block ends with closing curly bracket

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

Ex.

{ int a=10; {

MAIN BLOCK

int b = a + 20 ;

SUB BLOCK

System.out.println ( a ) ; }

System.out.println ( b ) ; }

// error

// no error

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

}

START

Statement 1

Statement 2

Condition ?

T Statement 3

Statement 4

Statement 5

Statement 6

STOP

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 if

,¢lk g¨ ( condition ) {

r¨ ;g dj¨

statements to be executed if the condition is TRUE ;

} else {

ugh r¨ ;g dj¨

statements to be executed

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

if the condition is FALSE ;

} START

In the Flow Chart, you can see that, Statement 1

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.

If – else block

Statement 2

F Condition ?

T

F

Statement 3

Statement 5

Statement 4

Statement 6

Statement 7

Statement 8

STOP

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 ;

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

} else if ( condition 2 ){ statements to be executed if the condition 2 is TRUE ; } else if ( condition 3 ){

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.

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) {

If(condition1) Statement 1;

Statement 1; } else if(condition 2) {

else if(condition 2) Statement 2;

Statement 2; } else if(condition 3) {

else if(condition 3) Statement 3;

Statement 3; } else

else Statement 4 ;

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)

The code to the left will

If(condition1) {

Statement 1;

result in an error as you are

Statement 2 ;

executing 2 statements

Statement 1;

without giving blocks.

Statement 2 ;

else if(condition2)

}

Statement 3; Statement 4 ;

The correct code is on the

else if(condition2) {

right side.

Statement 3; Statement 4 ; }

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

=90 ) {

if ( tot >=90 ) {

gr = “A+” ;

gr = “A+” ;

}

}

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

else if ( tot >=80 ) {

gr = “A” ;

gr = “A” ;

}

}

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

gr = “B” ;

gr = “B” ;

}

}

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

else if ( tot >=60 ) {

gr = “C” ;

gr = “C” ;

}

}

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

else if ( tot >=50 ) {

gr = “D” ;

gr = “D” ;

}

}

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

else if ( tot >=40 ) {

gr = “E” ;

gr = “E” ;

}

}

if ( tot < 40 ) {

else {

gr = “FAIL” ; }

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 4. switch :

[email protected]

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 : statement1 ; break; case : statement2;

Example : int a = Integer.parseInt(t1.getText()) ; String msg = “” ; switch ( a ) {

break;

case 1 : msg = “MON” ; break ;

case : statemet3 ; break ;

case 2 : msg = “TUE” ; break ;

case : statement4; break; default :

case 3 : msg = “WED” ; break ;

statemetDefault ;

case 4 : msg = “THU” ; break ;

}  Variable must be of integer or char type AND

case 5 : msg = “FRI” ; break ;

expression should result an integer value or char

case 6 : msg = “SAT” ; break ;

value..  No two case statements can be same.  “break “ statement is needed to avoid an error or say

case 7 : msg = “SUN” ; break ;

a concept namely “FALL THROUGH” associated

default : msg = “Wrong Number” ;

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.

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

This piece of „switch; statement is actually performing OR ( || ) operation.

case „a‟ : case „E‟ :

If the case matches „A‟ then the control will fall through all other cases in the absence of „break‟ statement.

case „e‟ : case „I‟ : case „i‟ : case „O‟ :

The following equivalent „if‟ statement will explain this.

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

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”;

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

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

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

Statement 1

INTIALISE LOOP CONTROL VARIABLE

Loop back to check condition

Condition ?

II

I

Loop terminated if condition becomes false

T LOOP BODY

F

III

UPDATE LOOP CONTROL VARIABLE

IV

Statement 5

Statement 6

STOP

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.

Page 31 of 64 I.

[email protected]

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

1 2 for( initialization ; test condition If TRUE 3 ….. loop body ;

4 update ) {

;

} If

FALSE come out of the Loop

5 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
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF