Вы находитесь на странице: 1из 56

Faculty of Engineering Sciences and Technology

Lab Manual
Object Oriented Programming

Experimen
t
No

Experiment

Date

Signature

1
2

3
4
5

8
9
10
11
12
13
14
15
16

Getting familiar with the Java development kit (JDK) 5.0 Installation for windows,
defining class path in environment variable- and compile and run a simple
program.
a. Making the First Java Program.
b. Understanding and Using escape sequences with System.out.println
c. Studying different data types, variables, variable names, variable
declaration, variable definition, variable initialization.
Studying Math functions.
Taking Input from the user at console screen using MyInput.java class.
a. Arithmetic operators, conditional operators, assignment operators,
Increment/decrement operators.
b. Studying loops in java. For loops, nested for loops, while loops, nested
while loops, do while loops, nested do while loops.
a. Studying loops in Java with cross combination, for-while, while-for, dowhile while, while do-while, for do-while, do-while for.
b. Decision making and conditioning using If statements, If-else
statements, switch-case.
a.
User defined methods, passing values to methods, and returning
values from methods.
b. Arrays, array index, single and multi dimensional arrays. Arrays and
loops. Sorting data in arrays.

The design principles of graphical user interfaces (GUIs) using layout managers
to arrange GUI components
Objective of experiment covers the basic component of SWING and their
interaction used in different program of Java, such as Label, Button, Text Box,
Combo Box, Radio Button, JList.
Show Message and Confirm Dialog Box - Swing Dialogs
To create a Login Form, we have used two class files:
1) NextPage.java
2) Login.java

Index

Experiment 1
.

Objective
Getting familiar with the Java development kit (JDK) 5.0 Installation for windows, defining class path in environment
variable- and compile and run a simple program
Theory
Java development kit (JDK) 5.0 Installation for windows

1- Go to google.com and enter search query as download java sdk 1.5


2- You are most likely to be returned with java official download page as shown above.

3- Click on Download button against JDK 5.0 update 16.

4- Download the exe file to your local disk. I used Mozilla Firefox browser, so the download manager looks like this.

5- After successful download, double click on the downloaded exe file


Tips:
JDK is easy to install. Post installation, you will need to set some environment variables in windows. You will be
guided through those steps in lab file shortly.
JDK includes JRE, Software development kit, Runtime environment for java and java plug-in for internet explorer,
mozilla firefox and netscape.

6- You can change the location of install by clicking on the Change button. If the default location suggested is ok,
click on next
7- Note down the location where j2se has been installed. Java Platform is also called as J2SE (Java 2 Platform
Standard Edition)

8- You will be shown the Progress screen for J2SE installation.

91011121314-

Above screen is for custom setup of JRE. Java Runtime Environment.


Click on change button if you wish to change the setup location or click on next button.
Java compilation is done using a command line tool javac
Java source code is of extension .java
After compilation of .java using javac tool, .class is created.
.class is the compiled binary version of the source code.

15- Above screen shows the progress of Java Platform Runtime Environment.

16- In this step you can choose to install java plugins on web-browsers.

17- This screen suggests that Java has been successfully installed on your machine.
To set up environment variables in windows in order that you can compile and run java applications using
command line:
-

Environment variables are global variables in an operating systems.


You can set and unset their values. They are not case-sensitive.
PATH can be set using command prompt by the SET command.
Ex: set PATH = C:\ant\bin; C:\java\bin;

Any environment variables value in windows can be accessed by prefixing and suffixing % symbol.
To view the PATH value use command : ECHO %PATH%

Steps:
1- Right Click on My Computer => Properties
2- Go to Advanced tab and click on Environment Variables. See the below System Properties screen

3- In the Environment variables screen, Click on Path and click on Edit button.
4- Add to the variable value, bin folder of the java installation. In my case java was installed at C:\Program
Files\Java\jdk1.5.0_16, so I added path of bin folder: C:\Program Files\Java\jdk1.5.0_16\bin

5- For example, if the path was C:\something\bin


6- Use a semicolon to delimit and append
Files\Java\jdk1.5.0_16\bin

JDK

bin

folder

to

it:

C:\something\bin;

C:\Program

7- You can test java installation by opening a command prompt and running javac .

8- You can test java runtime environment installation by running java in command prompt as shown in the screen
right.

To write a simple program in java, compile and run it.


1- Open notepad and type the content.

2- Save it as HelloWorld.java . Naming is strictly case-sensitive, make sure you type as it is given above.
3- Now open a command prompt and change to the directory where you have saved HelloWorld.java
4- Enter SET CLASSPATH = .
5- Press enter; this sets the classloader path to search for class files in the current directory.
If the compilation is succesful, you would not be shown any errors.
6- Type java HelloWorld and press enter. Please note that you did not include any extension such as .java or .class
to the class name you wish to run.You would get nice output greeting Hello World !!

Congratulations you have just successfully compiled and run a program in JAVA.
End of Lab

10

Experiment 2(a)

Objective
Making the First Java Program.
Theory
Analyzing the First Program.

// Here is simple Java language program called FirstClass.java.


public class FirstClass
{
Main function returning no values

Start and end of main functions body

public static void main(String args[])


{
System.out.println("My First Program in Java.");
}
}

The symbol // stands for a commented line. The compiler ignores a commented line. Java also supports multi-line
comments. These type of comments should begins with a /* end with a */ or begin with /* and end with */.
The next line declares a class FirstClass. To create a class prefixes the keyword, class, with the class (which is also the
name of the file).
class FirstClass
The classname generally begins with a capital letter.
The keyword class declares the definition of the class. FirstClass is the identifier for the name of the class. The entire
class definition is done within the open and closed curly braces. This marks the beginning and end of the class definition
block.
public static void main(String args[])
This is the main method, from where the program will begin its execution. All Java Applications should have one main
method. Let us understand what each word in this statement means.
The public keyword is an access modifier. It indicates that the class member can be accessed from anywhere in the
program. In this case, the main method is declared as public, so that JVM can access this method.
The static keyword allows the main to be called, without needing to create an instance of the class. But, in this case
copy of the main method is available in memory, even if no instance of that class has been created. This is important,
because the JVM first invokes the main method to execute the program. Hence, this method must be static. It should not
depend on instances of the class being created.
The void keyword tells the compiler that the method does not return any value when executed.
The main() method perform a particular task, and it is the point from which all Java Applications start.
String args[] is the parameter passed to the main method. The variables mentioned within the parenthesis of a method
receive any information that is to be passed to the method. These variables are the parameters of that method. Even if no
data has to be passed to the main method, the method name has to followed by an empty parentheses.
11

args[] is an array of type String. The argument passed at command line is stored in this array. The code within the
opening and closing curly braces of the main method is called the method block. The statements to be executed from the
main method need to be specified in this block.
System.out.println("My First Program in Java");
This line displays the string. My First Program in Java on the screen. It is followed by a new line. The println() method
produces the output. This method displays the string that is passed to it, with the help of System.out. Here System is a
predefined class that provides access to the system, and out is the output stream connected to the console.
Example
Program

Output

public class FirstClass


{
public static void main(String args[])

My First Program in Java.

{
System.out.println("My First Program in Java.");
}
}

Assignment
Using the program below, make a resume showing your complete details.
Program
public class MyResume
{
public static void main(String args[])
{
System.out.println("****************************RESUME****************************");
System.out.println("******************************CV******************************");
System.out.println("**************************************************************");
System.out.println("==============================================================");
System.out.println("Name
: Abc");
System.out.println("Fathers Name
: Xyz");
System.out.println("Date of Birth
: dd-mm-yyyy");
System.out.println("Address
: Engineering Department, Main Campus, Iqra University,");
System.out.println("
Shaheed-e-Millat Road, Defence View Karachi");
System.out.println("CNIC
: XXXXX-XXXXXXX-X");
System.out.println("Gender
: Male");
System.out.println("HSC (College\\Board) : Science (Pre Engg), Iqra College, Karachi Board");
System.out.println("HSC Year
: August 2005 ");
System.out.println("SSC (School\\Board) : Science, Iqra School, Karachi Board");
System.out.println("SSC Year
: August 2003 ");
}
}

12

Experiment 2(b)
Objective
Understanding and Using escape sequences with

System.out.println

Escape Sequences are used to adjust spacing between lines or characters or the characters themselves.
No.
Syntax
Application
Example
1
\n
New Line
System.out.println(\n);
2
\t
Tab eight spaces to right
System.out.println(\t);
3
\b
Back space One space back
System.out.println(\b);
4
\r
Carriage return Start of same line
System.out.println(\r);
5
\
Printing single quote
System.out.println(\);
6
\
Printing double quotes
System.out.println(\);
7
\\
Printing back space
System.out.println(\\);
Example
Program

Output

public class FormatExample


{
public static void main(String[] args)
{
A
Iqra University
20
35.5
1234567

System.out.println("A");
System.out.println("Iqra University");
System.out.println(20);
System.out.println(35.5);
System.out.println(1234567);
}
}
public class FormatExample1
{
public static void main(String[] args)
{

A Iqra University 2035.5 1234567

System.out.println("A Iqra University" + " " + 20 + " " + 35.5 + " " +
1234567);
}
}

Exercise
Write the output for following programs and give reasons.
Program
Output
public class FormatExample2
{

Write the output for the program on


left

public static void main(String[] args)


{
System.out.println("A");
System.out.println("Iqra University");
System.out.println(20);
System.out.println(35.5);
System.out.println(1234567);
}
}

13

Assignment
Use the program below to make your resume with escape sequences showing your complete details.
Program
public class FormatResume
{
public static void main(String[] args)
{
System.out.println("\t****************************RESUME****************************");
System.out.println("\t******************************CV******************************");
System.out.println("\t**************************************************************");
System.out.println("\t==============================================================");
System.out.println("Name
: " + "Abc");
System.out.println("Fathers Name
: " + "Xyz");
System.out.println("Date of Birth
: "+ 11 + "," + 11 +"," + 1989);
System.out.println("Address
: "+"Engineering Department, Main Campus, Iqra University,");
System.out.println("
"+ "Shaheed-e-Millat Road, Defence View Karachi");
System.out.println("Cell Phone
: " + 300+"," + 1234567);
System.out.println("CNIC
: " + 12345+"," + 1234567+"," +1);
System.out.println("Gender
: " + "Male");
System.out.println("HSC (College\\Board) : "+ "Science (Pre Engg), Iqra College, Karachi Board");
System.out.println("HSC Year
: August " + 2005);
System.out.println("SSC (School\\Board) : " + "Science, Iqra School, Karachi Board");
System.out.println("\nSSC Year
: August " + 2003);
}
}

14

Experiment 2(c)

Objective
Studying different data types, variables, variable names, variable declaration, variable definition, variable initialization
Theory
Variables are declared by first writing
data types followed be a variable name, e.g.
int a=10;
Here
int is data type,
a is variable name
and after the equals to sign (=) is the value in it 10
the value is always followed by a terminator

No.
1
2
4

Data Type
Single Character
Decimal Integer
Float

Double

Syntax
char
int
float
double

Range
One character within single quotes
-2,147,483,648 to +2,147,483,648
-3.40292347E+38 to +3.40292347E+38
-1.797769313486231570E+308 to
+1.797769313486231570E+308

Example
char a=a;
int a=10;
float a=1234.567;
double a=123456;

Variable Names
Variable names will always start with an alphabet.
Variable names can contain numbers (1,2,45,66) and underscores (_) but no other special characters (!@#$%^&*).
A variable name cannot be used for multiple declarations.
Example
Program

Output

public class DataTypesExample


{
public static void main(String[] args)
{
char a='a';
int b=12;
float c = 33.15;
double d=1234567;
System.out.println("Char value : " + a);
System.out.println("Decimal value : " + b);
System.out.println("Floating Point Value : " + c);
System.out.println("Double Value : " + d);

Char value : a
Decimal value : 12
Floating Point Value : 33.15
Double Value : 1234567

}
}
public class DataTypesExample1
{
public static void main(String[] args)
{
char a='a',a1='b';
int b=12,b1=13;
float c=12.55F,c1=13.55F;
double d=1234567,d1=1234568;
System.out.println(a +" " + b + " " + c + " " + d);
System.out.println(a1 +" " + b1 + " " + c1 + " " + d1);
}
}

a 12 12.55 1234567.0
b 13 13.55 1234568.0

15

Exercise
Write the output for following programs.
Program

Output

public class DataTypesExample2


{

Write the output for the program on left

public static void main(String[] args)


{
char a='A';
int b=97;
float c=12.5F;
double d=1234567;
System.out.println(a +" " + b + " " + c + " " + d);
}
}

Assignment
Using the program below, make a resume with format variables showing your complete details.
Program
public class ResumeFormating
{
public static void main(String[] args)
{
int dd,mm,yyyy,cell1,cnic3;
int cnic1,cnic2,cell2;
dd=11;
mm=11;
yyyy=1989;
cell1=300;
cell2=1234567;
cnic1=12345;
cnic2=1234567;
cnic3=1;
System.out.println("\t****************************RESUME****************************");
System.out.println("\t******************************CV******************************");
System.out.println("\t**************************************************************");
System.out.println("\t==============================================================");
System.out.println("Name
: Abc");
System.out.println("Fathers Name
: Xyz");
System.out.println("Date of Birth
: " + dd + "-" + mm +"-" + yyyy);
System.out.println("Address
: " + "Engineering Department, Main Campus, Iqra University,");
System.out.println("
" + "Shaheed-e-Millat Road, Defence View Karachi");
System.out.println("Cell Phone
: 0" + "-" + cell1 + "-" + cell2);
System.out.println("CNIC
: "+ cnic1 + "-" + cnic2 + "-" + cnic3);
System.out.println("Gender
: Male");
System.out.println("HSC (College\\Board) : Science (Pre Engg), Iqra College, Karachi Board");
System.out.println("HSC Year
: August 2005");
System.out.println("SSC (School\\Board) : Science, Iqra School, Karachi Board");
System.out.println("HSC Year
: August 2003");
}
}

16

Experiment 3

Objective
Studying Math functions.
Theory
Math class file is included for the definitions of math functions listed below. It is written as java.lang.Math
Trignometic / Maths
Functions
sin(n)
cos(n)
Example
tan(n)
The program below shows the result for math and trigonometric functions. The functions pass
the values to variables which are further used for printing in System.out. println
sinh(n)
Program
Output
hosh(n)
public class
MathClass
tanh(n)
{
pow(nmb,pwr)
public static void main(String[] args)
sqrt(n)
{
double a=45,b=1,sn,cs,tn,snh,csh,tnh;
sn=Math.sin(a);
cs=Math.cos(a);
tn=Math.tan(a);
snh=Math.sinh(b);
csh=Math.cosh(b);
tnh=Math.tanh(b);

Trigonometric Functions
sin 45 = 0.8509035245341184
cos 45 =0.5253219888177297
tan 45 =1.6197751905438615

System.out.println("\nTrignometric Functions");
System.out.println("sin 45 = " + sn);
System.out.println("cos 45 =" + cs);
System.out.println("tan 45 =" + tn);

Hyperbolic Functions
sinh 1 = 1.1752011936438014
cosh 1 = 1.543080634815244
tanh 1 = 0.7615941559557649

System.out.println("\nHyperbolic Functions");
System.out.println("sinh 1 = " + snh);
System.out.println("cosh 1 = " + csh);
System.out.println("tanh 1 = " + tnh);
}
}

The program below shows the result for math and trigonometric functions. It also demonstrates that some functions may
be called within the body of another function. For example here all the trigonometric functions are called inside println
function.
Program
Output
public class MathClass1
{
public static void main(String[] args)
{
double a=45,b=1,sn,cs,tn,snh,csh,tnh;
sn=Math.sin(a);
cs=Math.cos(a);

Trignometric Functions
sin 45 = 0.8509035245341184
cos 45 =0.5253219888177297
tan 45 =1.6197751905438615
Hyperbolic Functions
sinh 1 = 1.1752011936438014
17

tn=Math.tan(a);
snh=Math.sinh(b);
csh=Math.cosh(b);
tnh=Math.tanh(b);
System.out.println("\nTrignometric Functions");
System.out.println("sin 45 = " + sn);
System.out.println("cos 45 =" + cs);
System.out.println("tan 45 =" + tn);

cosh 1 = 1.543080634815244
tanh 1 = 0.7615941559557649

System.out.println("\nHyperbolic Functions");
System.out.println("sinh 1 = " + snh);
System.out.println("cosh 1 = " + csh);
System.out.println("tanh 1 = " + tnh);

Math Functions
pow 2,3 = 8.0
sqrt 49 = 7.0

System.out.println("\nMath Functions");
System.out.println("pow 2,3 = "+ Math.pow(2,3));
System.out.println("sqrt 49 = "+ Math.sqrt(49));
}
}

Assignment
Assingment
Program the following.
Implement the following equation
3x4 sin(180x) + 4x3 cos(90x) + x2sin(tan(45)) + 7x + 9cos(90x2 )
where x may be user defined value.

18

Experiment 4

Objective
Taking Input from the user at console screen using MyInput.java class.
Note: From Network Directory > e-Lecture, you will find a file named MyInput.java. Copy the said file and paste it to
below location.
..java\bin\
Compile MyInput.java, upon successful compilation you will find MyInput.class.
Theory (Functionality of MyInput):
Class defines the basic input method from the user on console. There is a variety of input method you
will find in MyInput class such as:
readint():
readFloat():
readLong():
readDouble():
readString():
readMyChar():

accepts a Integer value from user at command line.


accepts a Float value from user at command line.
accepts a Long value from user at command line.
accepts a Double value from user at command line.
accepts a String value from user at command line.
accepts a Character value from user at command line.

In addition to above method, to make our program more reliable MyInput.class also provides
Exception Handling to each functions, in case of exception, user will get a Error message and will prompt for Input again.
Example
Write the output after supplying appropriate input on console screen.
Program
public class ConsoleInput
{
public static void main(String[] args) throws Exception
{

Output

Write the output for the program on left

char a;
int b;
float c;
double d;
System.out.println("Enter Character Value :");
a =MyInput.readMyChar();
System.out.println("Enter Double Value :");
d =MyInput.readDouble();
System.out.println("Enter Integer Value :");
b =MyInput.readInt();
System.out.println("Enter Float Value :");
c =MyInput.readFloat();
System.out.println("Output of provided values");
System.out.println(a +" " + d + " " + b + " " + c);
}
}

19

Assignment
Use the program below to make a resume that takes input from the user and shows complete details.
Program
public class ResumeBuilder
{
public static void main(String[] args) throws Exception
{
String name,fname,cell,address,phone,nic,gender,contact;
int dd,mm,yyyy;
System.out.println("********* Bulid your own resume by providing information *********\n");
System.out.println("Enter your full name :");
name = MyInput.readString();
System.out.println("Enter your father name :");
fname = MyInput.readString();
System.out.println("Enter your date of birth, (only accept integer value(s).");
System.out.println("Enter Day : ");
dd = MyInput.readInt();
System.out.println("Enter Month : ");
mm = MyInput.readInt();
System.out.println("Enter Year : ");
yyyy = MyInput.readInt();
System.out.println("Enter your gender : ");
gender = MyInput.readString();
System.out.println("Enter your mobile number : ");
cell = MyInput.readString();
System.out.println("Enter your home contact number : ");
contact = MyInput.readString();
System.out.println("Enter your NIC number ");
nic = MyInput.readString();
System.out.println("Enter your Address :");
address = MyInput.readString();
System.out.println("******************************CV******************************");
System.out.println("**************************************************************");
System.out.println("==============================================================");
System.out.println("\tName:\t\t" + name );
System.out.println("\tFather Name:\t" + fname );
System.out.println("\tDate of birth:\t" + dd + "-" + mm + "-" + yyyy );
System.out.println("\tGender:\t\t" + gender);
System.out.println("\tMobile Number:\t" + cell);
System.out.println("\tContact Number:\t" + contact);
System.out.println("\tNIC Number:\t" + contact);
System.out.println("\tAddress:\t" + address);
System.out.println("\tHSC (College\\Board):\tScience (Pre Engg), Iqra College, Karachi Board");
System.out.println("\t\t\t\tShaheed-e-Millat Road, Defence View Karachi");
System.out.println("\tHSC Year: August 2005");
System.out.println("\tSSC (School\\Board): Science, Iqra School, Karachi Board");
System.out.println("\tSSC Year: August 2003");
}
}

20

Experiment 5(a)

Objective
Arithmetic operators, conditional operators, assignment operators, Increment/decrement operators.
Provide
Theory
Arithmetic
Relational
Assignment
Increment/decrement
operators
operators
operators
operators
Add
Subtract
Multiplication
Division
Remainder

+
*
/
%

Greater Than
Less Than
Greater or Equal
Less or Equal
Equal Equal
Not Equal

>
<
>=
<=
==
!=

Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment

Example
Explain the following program after careful study.
Program

Output

public class ArithmeticOperation


{
public static void main(String[] args)
{
int a=2,b=4,c1,c2,c3,c4,d1,d2,d3,d4;
c1=c2=c3=c4=5;
d1=d2=d3=d4=8;
System.out.println(a+b + " " + (b-a) + " " + a*b + " " + a/b);
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a>=b);
System.out.println(a<=b);
System.out.println(a==b);
System.out.println(a!=b);
System.out.println(c1+=3);
System.out.println(c2-=3);
System.out.println(c3*=3);
System.out.println(c4/3);
System.out.println(d1++ + " " + ++d2 + " " + d3-- + " " + --d4);

6280
false
true
false
true
false
true
8
2
15
1
8987

}
}

Exercise
Write output for following programs and give reasons.
Program
public class ArithmeticOperation1
{
public static void main(String[] args) throws
Exception
{
int a=5;
System.out.println(a++ + " " + a);
System.out.println(a);
}
}
public class ArithmeticOperation2
{
public static void main(String[] args)
{

Output

Write the output for the program on left

Write the output for the program on left

int a=5;
System.out.println(++a + " " + a);
System.out.println(a);
}
}
public class ArithmeticOperation3

Write the output for the program on left


21

+=
-=
*=
/=

Increment
Decrement

++
--

{
public static void main(String[] args)
{
int a=5;
System.out.println(a-- + " " + a);
System.out.println(a);
}
}

Program
public class ArithmeticOperation4
{
public static void main(String[] args)
{
int a=5;
System.out.println(--a + " " + a);
System.out.println(a);
}
}
public class ArithmeticOperation5
{
public static void main(String[] args)
{
int a=5;
System.out.println(a++ + " " + ++a + " " + a + " " +a--);
System.out.println(a);
}
}
public class ArithmeticOperation6
{
public static void main(String[] args)
{
int a=5;
System.out.println(a+5 + " " + ++a + " " + a);
System.out.println(a);
}
}
public class ArithmeticOperation7
{
public static void main(String[] args)
{
int a=5;
System.out.println((a-=5) + " " + --a + " " +a);
System.out.println(a);
}
}
public class ArithmeticOperation8
{
public static void main(String[] args)
{
int a=5;
System.out.println((a+=5) + " " + a++ + " " + a);
System.out.println(a);
}
}
public class ArithmeticOperation9
{
public static void main(String[] args)
{

Output
Write the output for the program
on left

Write the output for the program


on left

Write the output for the program


on left

Write the output for the program


on left

Write the output for the program


on left

Write the output for the program


on left

int a=5;
System.out.println((a+=5) + " " + ++a + " " + a);
System.out.println(a);
}
}

22

Assingment
Program the following.
Prompt user to input distance in Kilometers and display it in meters.
For the following equation 3x4 + 4x3 + x2 + 7x + 9 , substitute the value of x and generate the result.
Input any number from user and generate its square e.g. square of 8 is 64
Input any number from user and generate its cube e.g. cube of 8 is 512
Input a 4 digit number in any integer type variable and sum all the four digits, e.g. int a =3487, result = 22

23

Experiment 5(b)

Objective
Studying loops in java. For loops, nested for loops, while loops, nested while loops, do while loops, nested do while loops.
Theory
for
for(initialization ; check range ; iteration)
{
body
}

while
initialization;
while(check range)
{
body
iteration;
}

Example
The table below shows simple loops.
All the three programs have same output.
Loop
Program
Output

For

While

}
}

Do
while

This table below shows nested loops


All the three programs have same output.
Nested
Program
Loop

public class ForLoop


{
public static void main(String[]
args)
{
for(int a=0;a<=12;a++)
System.out.println(a + " " +a*2);
}
}

public class WhileLoop


{
public static void main(String[]
args)
{
int a=0;
while(a<=12)
{
System.out.println(a + " * 2 = " +
a*2);
a++;
}

public class DoWhileLoop


{
public static void main(String[]
args)
{
int a=0;
do
{
System.out.println(a + " 2 * = " +
a*2);
a++;
}
while(a<=12);
}
}

For

0x2=0
1x2=2
2x2=4
3x2=6
4x2=8
5 x 2 = 10
6 x 2 = 12
7 x 2 = 14
8 x 2 = 16
9 x 2 = 18
10 x 2 = 20
11 x 2 = 22
12 x 2 = 24

do while
initialization;
do
{
body
iteration;
} while(check range)

While

Do while

24

Output

public class ForLoop1


{
public static void main(String[]
args)
{
for(int a=0;a<=3;a++)
{
for(int b=0;b<=3;b++)
{
System.out.print(a + "" + b +"\t");
}
System.out.println("\n");
}
}
}
public class WhileLoop1
{
public static void main(String[]
args)
int a=0,b;
while(a<=3)
{
b=0;
while(b<=3)
{
System.out.print(a +""+ b + "\t");
b++;
}
System.out.println("\n");
a++;
}
}
}
public class DoWhileLoop1
{
public static void main(String[]
args)
{
int a=0,b;
do
{
b=0;
do
{
System.out.print(a + "" + b + "\t");
b++;
}while(b<=3);
System.out.print("\n");
a++;
}
while(a<=3);
}
}

00
10
20
30

01
11
21
31

02
12
22
32

03
13
23
33

Exercise
Carefully observer the following program and write output with reasons.
Program
Output
public class ForLoopExample
{
public static void main(String[] args)
{
for(int a=0;a<=12;a++)
System.out.println(a + " x 2 = " + a*2);
}
}
public class ForLoopExample1
{
public static void main(String[] args)
{

Write the output for the program on left

Write the output for the program on left

for(int a=0;1;a++);
System.out.println(a+" x 2 = " + a*2);
}
}
public class WhileExample
{
public static void main(String[] args)
{
int a=0;
while(0)
{
System.out.println(a + " x 2 = " + a*2);
a++;
}

Write the output for the program on left

}
}

Assignment:
Input any number from user and generate its factorial e.g. factorial of 7 is 5040
For the following output write programs with a logical method.
Program
Output
Write the program for the output on right

Write the program for the output on right

Write the program for the output on right

Write the program for the output on right

10 x 2 = 20
12 x 2 = 24
14 x 2 = 28
16 x 2 = 32
18 x 2 = 36
20 x 2 = 40
33
32
31
30
23
22
21
20
13
12
11
10
03
02
01
00
00
00
00
00
00
11
00
00
00
00
22
00
00
00
00
33
12 x 2 = 24
11 x 2 = 22
10 x 2 = 20
9 x 2 = 18
8 x 2 = 16
7 x 2 = 14
6 x 2 = 12
5 x 2 = 10
4x2=8
3x2=6
2x2=4
1x2=2
0x2=0
Explain the program on left and its output which is given
25

public class NestedFor1


{
public static void main(String[] args)
{
int a,b;
long c=1;
for(a=0;a<=8;a++)
{
for(b=8;b>a;b--)
System.out.print(" ");
System.out.print(c*c);
System.out.print("\n");
c=c*10+1;

below

1
2
3
4
5
6
7

1
2
3
4
5
6
7
8

+
+ +
+ + +
+ + + +

+
+
+
+
+

1
1 2
1 2 3
1 2 3 4

1
2
3
4
5

1
2
3
4
5
6

}
}
}
Write the program for the output on right

26

1
2
3
4
5
6
7

1
2
3
4
5
6

1
2
3
4
5

1
2 1
3 2 1
4 3 2 1

+
+ +
+ + +
+ + + +

Experiment 6(a)

Objective
Studying loops in Java with cross combination, for-while, while-for, do-while while, while do-while, for do-while, do-while
for.
Theory
for while
for( )
{
while( )
}

while for
while( )
{
for( )
}

for do-while

do-while for

while do-while

for( )
{
do
while( )
}

do
{
for( )
}while( )

while( )
{
do
while( )
}

do-while
while
do
{
while( )
}while( )

Example
The table below shows loops with cross combinations.
Loop
Program
Output

For While

While For

public class ForWhileNested


{
public static void main(String[]
args)
{
int a,b=0;
for(a=0;a<=3;a++)
{
b=0;
while(b<=3)
{
System.out.print(a + " " + b + "
" + "\t" );
b++;
}
System.out.print("\n");
}
}
}
public class WhileForNested
{
public static void main(String[]
args)
{
int a=0,b;
while(a<=3)
{
for(b=0;b<=3;b++)
{
System.out.print(a+ " " + b +
"\t");
}
System.out.print("\n");
a++;
}
}
}

00
10
20
30

01
11
21
31

02
12
22
32

03
13
23
33

Assignment
With the help of above program make the following crossed combination programs for the same output.
For Do-while
Do-while For
While Do-while
Do-while while

27

Experiment 6(b)
Objective
Decision making and conditioning using If statements, If-else statements, switch-case.
Theory
If
if(cond)
{
Body
}

Nested If
if(cond)
{
If(cond)
{
body
}
}

If-else
if(cond)
{
body
}
else
{
Body
}

Else-if

Switch-case

if(cond)
{
body
}
else
If(cond)
{
Body
}

switch(cond)
{
case1:
body
case2:
body
}

Example
This program illustrates simple if and nested if statements with else conditions.
Program
Output
public class SimpleIfElse
{
public static void main(String[] args) throws
Exception
{

Write the output for the program on left

int cp=0;
System.out.println("Enter Java marks
between 1 & 100");
cp = MyInput.readInt();
if(cp>=0 && cp<=100)
{
if(cp>=75)
System.out.println("\nGrade A");
else
if(cp>=50)
System.out.println("\nGrade C");
else
if(cp>=40)
System.out.println("\nFail");
}
else
System.out.println("\nIncorrect Input");
}
}

28

This program lets the user choose a number between 1 and 99 and guesses it in less than 10 hints.
Program
Output
public class NumberThinking
{
public static void main(String[] args) throws Exception
{
float gss,incr;
char ch;
System.out.println("Think of a number Between 1 & 99\n");
System.out.println("Press `g` for grater\n");
System.out.println("Press `l` for less\n");
System.out.println("Enter for exit\n");
incr=gss=50;
while(incr>1.0)
{
System.out.println("\nIs your number greater, less or equal
to :" + gss);
incr/=2;
if((ch=MyInput.readMyChar())=='e')
break;
else if(ch=='g')
gss+=incr;
else
gss-=incr;
}
System.out.println("You guessed " + gss);
}
}

Think of a number between 1 and 99


Press `g` for greater
Press `l` for less
Enter for exit
Is your number greater, less or equal to 50
Is your number greater, less or equal to 75
Is your number greater, less or equal to 88
You guessed 88

This is a simple calculator program that adds or subtracts two numbers entered by the user.
Program
Output
public class Calculator
{
public static void main(String[] args) throws Exception
{

Write the output for the program on left

float nm1=1.0F,nm2=1.0F;
char op;
System.out.println("\n\t\tSimple Calculator.\n");
System.out.println("Enter a first number :");
nm1 = MyInput.readFloat();
System.out.println("Enter operator (only +, -, *, /).");
op = MyInput.readMyChar();
System.out.println("Enter a second number :");
nm2 = MyInput.readFloat();
switch(op)
{
case'+':
System.out.println("Addition of two: " +
break;

(nm1+nm2));

case'-':
System.out.println("Subtration of two: " + (nm1-nm2));
break;
case'*':
System.out.println("Multiplication of two: " + (nm1*nm2));
break;
case'/':
if(nm1!=0 && nm2 !=0)
{
System.out.println("Division of two: " + (nm1/nm2));
}
else
{
System.out.println("Invalid Operation");
}
break;
default:
System.out.println("\nUnknown Operator\n");
}
}
}
29

Assignment
Program the following.
Make the number guessing program with switch case.
Make an alphabet guessing program using if-else.
Complete the simple calculator program for multiplication and division. Also make it using if-else.
Make your resume such that in the name field it dose not accept any thing else than alphabets and space bar.
Look at the scenario below.
Marks
Grade
GPA
Design a marks sheet for a student with 5 subjects
0-49
F
2
Math, Physics, Electronics, Islamiat, Computer Programming.
50-59
C
2.25
Take marks as input from user calculate grade for each subject,
60-69
C+
2.5
70-79
B
2.75
CGPA and percentage. Detect error for out ranged numbers e.g. below 0 or
80-89
B+
3
above 100.
90-95
96-90

30

A
A+

3.5
4

Experiment 7(a)
Objective
User defined methods, passing values to methods, and returning values from methods.
Theory
Method gives user a facility to make functions according to their own needs.
Example
This program has a simple method with no return type or arguments passing and prints a sentence.
Program
Output
public class SimpleFunction
{
public static void main(String[] args)
{
SimpleFunction func = new SimpleFunction();
func.printIqra();
Iqra University
}
public void printIqra()
{
System.out.println("Iqra University");
}
}

This program has a function with no return type but two arguments passed as integers and printed with their sum.
Program
Output
public class FuncArguments
{
public static void main(String[] args)
{
FuncArguments func = new FuncArguments();
func.add(2,4);
}
public void add(int a,int b)
{
System.out.println(a + "+ " + b + " = " + (a+b));
}

2+4=6

This program has a function with integer return type and two arguments passed as integers.
Program
Output
public class FuncReturn
{
public static void main(String[] args)
{
int holdValue;
FuncReturn func = new FuncReturn();
holdValue = func.add(2,4);
System.out.println("Function Value : " + holdValue);
}

Function Value : 6

public int add(int a,int b)


{
int c;
c=a+b;
return c;
}
}

Program
public class FunctionCalculator
{
static char type;
double nm1,nm2,ans;
public double funcAdd() throws Exception
{
31

System.out.println("Your selected operation type is Addition.");


System.out.println("Enter a first number :");
nm1 = MyInput.readDouble();
System.out.println("Enter a second number :");
nm2 = MyInput.readDouble();
ans= nm1+nm2;
return ans;
}
public double funcSub() throws Exception
{
System.out.println("Your selected operation type is Subtraction.");
System.out.println("Enter a first number :");
nm1 = MyInput.readDouble();
System.out.println("Enter a second number :");
nm2 = MyInput.readDouble();
ans= nm1-nm2;
return ans;
}
public double funcDiv() throws Exception
{
System.out.println("Your selected operation type is Division.");
System.out.println("Enter a first number :");
nm1 = MyInput.readDouble();
System.out.println("Enter a second number :");
nm2 = MyInput.readDouble();
if(nm1!=0 && nm2!=0)
{
ans= nm1/nm2;
return ans;
}
else
{
System.out.println("Invalid Operation");
return 0;
}
}
public double funcMul() throws Exception
{
System.out.println("Your selected operation type is Multiplication.");
System.out.println("Enter a first number :");
nm1 = MyInput.readDouble();
System.out.println("Enter a second number :");
nm2 = MyInput.readDouble();
ans= nm1*nm2;
return ans;
}
public static void main(String[] args) throws Exception
{
FunctionCalculator funcObject = new FunctionCalculator();
System.out.println("\nSimple Calculator using functions");
System.out.println("\nChoose operation type.\n");
System.out.println("1 for Addition.\n");
System.out.println("2 for Subtration.\n");
System.out.println("3 for Division.\n");
System.out.println("4 for Multiplication.");
System.out.println("Provide a operation number here :");
type= MyInput.readMyChar();
switch(type)
{
case'1':
System.out.println(funcObject.funcAdd());
break;
case'2':
System.out.println(funcObject.funcSub());
break;
case'3':
System.out.println(funcObject.funcDiv());
break;
case'4':
System.out.println(funcObject.funcMul());
break;
default:
System.out.println("Invalid operation type");
}
}
}

32

Experiment 7(b)

Objective
Arrays, array index, single and multi dimensional arrays. Arrays and loops. Sorting data in arrays.
Theory
Arrays
are
multiple
values at one time.
length and have
as indexes for data
from zero.

0
1

int a[]={9,4,7,2,6};

2
3
Index/address
4

a
9
4
7
2
6

variables
Values

that

can

hold

They have a specified


addresses known
retrieval starting

Example
Below are three tables showing one dimensional character, integer and float arrays. Each table shows three different
methods of declaring and initializing an array.
Method 1
(Declaration and initialization)

char

char a[]={'a','b','c','d','e'};

Method 2
(Separate declaration and initialization)
char a[] = new char[5] ;
a[0]='a';
a[1]='b';
a[2]='c';
a[3]='d';
a[4]='e';

ONE DIMENSIONAL INTEGER ARRAY


Method 1
(Declaration and Initialization)

int

int a[]={1,2,3,4,5};

Method 2
(Separate declaration and initialization)
int a[] = new int[5];
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
a[4]=5;

Method 3
(Separate declaration and initialization)
int a[] = new int[5];
for(int a1=0;a1<=4;a1++)
System.out.println(a1+ " " + a[a1]=a1+1);

ONE DIMENSIONAL FLOAT ARRAY


Method 1
(Declaration and initialization)

float

float a[]={1.1,1.2,1.3,1.4,1.5};

Program
public class ArrayExample
{
public static void main(String[]
args)throws Exception
{
int i;
float[] marks=new float[5];
float sum=0,avg=0;
for(i=0;i<5;i++)
{
System.out.println(Enter marks for
student:+(i+1));

Method 2
(Separate declaration and initialization)
float a[] = new float[5];
a[0]=1.1;
a[1]=1.2;
a[2]=1.3;
a[3]=1.4;
a[4]=1.5;

Output
Write the output for the program on left

33

Method 3
(Separate declaration and initialization)
float a[] new float[5];
for(int a1=1;a1<=5;a1++)
System.out.println(a1 + " " + a[a1]=1+
(a1/10.0));

marks[i]=MyInput.readFloat();
System.out.print(\n);
}
for(i=0;i<5;i++)
{
sum=sum+marks[i];
}
avg=sum/5;
System.out.print(The average of the
class is : +avg);
}
}
public class ArrayExample1
{
public static void main(String[]
args)throws Exception
{
final int LIM=5;
int i=0,sum=0;
float[] marks=new float[LIM];

Write the output for the program on left

for(i=0;i<LIM;i++)
{
System.out.println("Enter marks for
student :"+(i+1));
marks[i]=MyInput.readFloat();
System.out.print("\n");
}
for(i=0;i<LIM;i++)
{
if(marks[i]>=60)
{sum++;}
}
System.out.println("The number of
students who have passed is "+ sum);
}
}

The picture below shows how a two dimensional array may look like.
Two dimensional Array
0
1
2
3
4

0
1
2
3
4

5
6
7
8
9

10
11
12
13
14

15
16
17
18
19

Table below shows three different methods of declaring and initializing a two dimensional integer array.
TWO DIMENSIONAL INTEGER ARRAY

Int

Method 1
(Declaration and initialization)
int aa[][]={
{0,1,2,3,4},
{5,6,7,8,9},
{10,11,12,13,14},
{15,16,17,18,19}
};

Method 2
(Separate declaration and initialization)
int myArray[][] = new int[4][5];
myArray [0][0]=1; myArray [0][1]=2;
myArray [0][2]=3;
myArray 0][3]=4; myArray [0][4]=5;
myArray [1][0]=6; myArray [1][1]=7;
myArray [1][2]=8;
myArray [1][3]=9; myArray[1][4]=10;
myArray 2][0]=11; myArray[2][1]=12;
myArray[2][2]=13;
myArray [2][3]=14; myArray [2][4]=15;
myArray [3][0]=16; myArray [3][1]=17;
myArray [3][2]=18; myArray [3][3]=19;
myArray [3][4]=20;

34

Method 3
(Separate declaration and initialization)
public class ArrayExample2
{
public static void main(String[] args)
{
int myArray[][] = new int[4]
[5];
for(int a=0;a<4;a++)
{
for(int b=0;b<5;b++)
{
System.out.print(myArray[a]
[b]=((a*10)+b));
System.out.print("\t");
}
System.out.print("\n");
}
}

}}
Write the output for the program on left

public class TwoDemArray


{
public static void main(String[] args)throws Exception
{
final int max=5, len=2;
float myArray[][] = new float[max][len];
int i;
for(i=0;i<max;i++)
{
System.out.print("\nPlease enter roll number: ");
myArray[i][0]=MyInput.readInt();
System.out.print("\nPlease enter marks: ");
myArray[i][1]=MyInput.readInt();
System.out.print("\n\n");
}
for(i=0;i<max;i++)
{
System.out.print("\nRoll number: "+ myArray[i][0]);
System.out.println("\nMarks: "+myArray[i][0]);
System.out.print("\n");
}
}
}

This program shows a two dimensional character array namely myArray of fixed length (5 rows and 15 columns) or say 5
single dimensional arrays, each of length 15, initialized in one of the several ways shown above for integer arrays.
ALGORITHMS
Arrays have many properties applicable on them. Three such properties are.
-

Searching an array,
Entering data in an array,
Sorting an array.
Hence we apply these on array using algorithms which may be categorized as follows.

Searching
- By address or location
- By Value

Sorting
- Ascending / Descending
Exercise
This program prompts the user for a number from the given data searches and returns its location.
Program
Output
public class ArrayExample3
{
public static void main(String[] args)throws Exception
{

Write the output for the program on left

int a[]={8,6,3,7,2},vl,a1,a2=0;
for(a1=0;a1<=4;a1++)
System.out.println(a[a1]);
System.out.println("\nFrom the above enter one value
to search : ");
vl=MyInput.readInt();
while(a[a2]!=vl)
{
a2++;
}
System.out.println("Location of " + vl + " is " + a2+1);
}
}

35

This program sorts the numbers in side the array in ascending order.
Program
Output
public class ArrayExample4
{
public static void main(String[]
args)throws Exception
{
int tmp,arr[]={23,16,97,33,42};
for(int a=0;a<5;a++)
{
for(int b=0;b<4;b++)
{
if(arr[b]>arr[b+1])
{
tmp=arr[b];
arr[b]=arr[b+1];
arr[b+1]=tmp;
}
}
}
for(int c=0;c<5;c++)
System.out.println(arr[c]);
}
}
public class ArraySorting
{
public static void main(String[]
args)throws Exception
{ final int LIM=5;
int in,out,i,temp;
int[] numbers=new int[LIM];

Write the output for the program on left

Write the output for the program on left

for(i=0;i<LIM;i++)
{
System.out.println("Enter number:");
numbers[i]=MyInput.readInt();
System.out.print("\n");
}
for(out=0;out<LIM-1;out++)
{
for(in=out+1;in<LIM;in++)
{
if(numbers[out]>numbers[in])
{
temp=numbers[in];
numbers[in]=numbers[out];
numbers[out]=temp;
}
}
}
i=0;
System.out.println("\nSorted list:");
for(i=0;i<LIM;i++)
{
System.out.print("\n"+numbers[i]);
}
}
}

This program randomly generates 10 values between 1 and 100 to be placed in double array.
Program
Output
public class ArrayExample5
{
public static void main(String[] args)
+{

Write the output for the program on left

double a[] = new double[10];


int b;
for(b=0;b<10;b++)
{
System.out.println(a[b]=(Math.random()
%100+1));
}
}
}
36

Assignment
Program the following.
.
Consider a one dimensional character array of length 5 and holding data a, e, i, o and u. Sort them in ascending
order.
Randomly place values in a 2 dimensional integer array.
In the resume of experiment number 11 use arrays where necessary, e.g. 1 dimensional character array for name,
fathers name, address, University etc fields.

37

Experiment 13

Objective
The design principles of graphical user interfaces (GUIs) using layout managers to arrange GUI components
Theory:
GUI & GUI Components:
A graphical user interface (GUI) presents a user friendly mechanism for interacting with an application.
GUIs are built from GUI components. These are sometimes called controls or widgets. A GUI component is an object with
which the user interacts via mouse, the keyboard, or another form of input.
Swing Components:
Most GUI applications require more elaborate, customized user interfaces. Several Swing GUI
components from package javax.swing that are used to build Java GUIs. Most Swing components are pure Java
components-they are written, manipulated and displayed completely in Java. They are part of the Java Foundation
Classes (JFC)-Javas libraries for cross-platform GUI Development. Most Swing components are not tied to actual GUI
components supported by the underlying platform on which an application executes. Such GUI components are known as
lightweight components.
Layout Managers:
Layout managers are provided to arrange GUI components in a container for presentation purposes.
Programmers can use the layout managers for basic layout capabilities instead of determining the exact position and size
of every GUI component. All layout managers implement the interface LayoutManager (in package java.awt). Below
Table summarizes the layout managers presented in Experiment
Layout manager
FlowLayout
BorderLayout
GridLayout

Description
Default for javax.swing.JPanel. Places components
sequentially (left to right) in the order they were
added
Default for JFrames (and other windows). Arranges
the components into five areas: NORTH, SOUTH,
EAST, WEST and CENTER.
Arranges the components into rows and columns.

38

Example - FlowLayout
Flowlayout allows components to flow over multiple lines
Program

Output

//FlowLayoutFrame.java
import java.awt.FlowLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JButton;
public class FlowLayoutFrame extends JFrame
{
private JButton leftJButton;
private JButton centerJButton;
private JButton rightJButton;
private FlowLayout layout;
private Container container;
public FlowLayoutFrame()
{
super("Flow Layout Demo");
layout = new FlowLayout(); //creat FlowLayout
container = getContentPane(); //get container to layout
setLayout(layout); //set frame layout
leftJButton = new JButton("Left"); //create Left Button
add( leftJButton ); //add Left button to frame
centerJButton = new JButton("Center"); //create Center
Button
add( centerJButton ); //add Left button to frame
rightJButton = new JButton("Right"); //create Left Button
add( rightJButton ); //add Right button to frame
}// end FlowLayoutFrame constructor
public static void main( String args[] )
{
FlowLayoutFrame flowLayoutFrame = new
FlowLayoutFrame();
flowLayoutFrame.setDefaultCloseOperation( JFrame.EXI
T_ON_CLOSE );
flowLayoutFrame.setSize( 300, 75 );
flowLayoutFrame.setVisible (true);
}//end main
//end class FlowLayoutDemo
}//end Class FlowlayoutFrame

39

Example - BorderLayout
BorderLayout containing five buttons.
Program

Output

class BorderlayoutFrame extends JFrame {


// main
public static void main(String[] args) {
JFrame window = new BorderlayoutFrame();
window.setVisible(true);
}
//constructor
BorderlayoutFrame() {
//... Create components (but without listeners)
JButton north = new JButton("North");
JButton east = new JButton("East");
JButton south = new JButton("South");
JButton west = new JButton("West");
JButton center = new JButton("Center");
//... Create content pane, set layout, add components
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(north , BorderLayout.NORTH);
content.add(east , BorderLayout.EAST);
content.add(south , BorderLayout.SOUTH);
content.add(west , BorderLayout.WEST);
content.add(center, BorderLayout.CENTER);
//... Set window characteristics.
setContentPane(content);
setTitle("Border layout Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
}

40

Example - GridLayout
GridLayout containing six buttons.
Program

Output

//GridLayoutFrame.java
import java.awt.GridLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JButton;
public class GridLayoutFrame extends JFrame
{
private JButton buttons[]; //array of buttons
private final String names[] = { "one", "two", "three", "four", "five",
"six" };
private Container container; //frame container
private GridLayout gridlayout1; //first
GridLayout gridLayout1 = new GridLayout( 2,3,5,5 ); //2 by 3; gaps
of 5
//no-argument constructor
public GridLayoutFrame()
{
super ( "GridLayout Demo" );
container = getContentPane(); //get content pane
setLayout( gridLayout1 ); //set JFrame Layout
buttons = new JButton[ names.length]; //create array of JButtons
for (int i = 0 ; i < names.length ; i++ )
{
buttons[i] = new JButton( names[i]);
add(buttons[i]);
} //end for
} //end GridLayouFrame constructor
public static void main( String args[] )
{
GridLayoutFrame gridLayoutFrame = new
GridLayoutFrame();

gridLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CL
OSE);
gridLayoutFrame.setSize( 300, 200 );
gridLayoutFrame.setVisible( true ); //display
frame
}//end main
} //end class GridLayouFrame

41

Experiment 14

Objective
Objective of experiment covers the basic component of SWING and their interaction used in different program of
Java, such as Label, Button, Text Box, Combo Box, Radio Button, JList.

JButton Program

Output

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonDemo {
JFrame jtfMainFrame;
JButton jbnButton1, jbnButton2;
JTextField jtfInput;
JPanel jplPanel;
public JButtonDemo() {
jtfMainFrame = new JFrame("Which Button Demo");
jtfMainFrame.setSize(50, 50);
jbnButton1 = new JButton("Button 1");
jbnButton2 = new JButton("Button 2");
jtfInput = new JTextField(20);
jplPanel = new JPanel();
jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys
jbnButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jtfInput.setText("Button 1!");
}
});
jbnButton2.setMnemonic(KeyEvent.VK_I);
jbnButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jtfInput.setText("Button 2!");
}
});
jplPanel.setLayout(new FlowLayout());
jplPanel.add(jtfInput);
jplPanel.add(jbnButton1);
jplPanel.add(jbnButton2);
jtfMainFrame.getContentPane().add(jplPanel,
BorderLayout.CENTER);
jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
jtfMainFrame.pack();
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
// Set the look and feel to Java Swing Look
try {
UIManager.setLookAndFeel(UIManager
.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
JButtonDemo application = new JButtonDemo();
}
}

42

There are two text box in the program one is editable and other is locked, if user input any text in editable text box the text
will appear over the locked text box

JTextFeild Program

Output

// A program to demonstrate the use of JTextFields's


//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTextFieldDemo extends JFrame {
//Class Declarations
JTextField jtfText1, jtfUneditableText;
String disp = "";
TextHandler handler = null;
//Constructor
public JTextFieldDemo() {
super("TextField Test Demo");
Container container = getContentPane();
container.setLayout(new FlowLayout());
jtfText1 = new JTextField(10);
jtfUneditableText = new JTextField("Uneditable text field",
20);
jtfUneditableText.setEditable(false);
container.add(jtfText1);
container.add(jtfUneditableText);
handler = new TextHandler();
jtfText1.addActionListener(handler);
jtfUneditableText.addActionListener(handler);
setSize(325, 100);
setVisible(true);
}
//Inner Class TextHandler
private class TextHandler implements ActionListener {
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jtfText1)
{
disp = "text1 : " + e.getActionCommand();
}
else if (e.getSource() == jtfUneditableText)
{
disp = "text3 : " + e.getActionCommand();
}
JOptionPane.showMessageDialog(null, disp);
}
}
//Main Program that starts Execution
public static void main(String args[])
{
JTextFieldDemo test = new JTextFieldDemo();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}// End of class TextFieldTest

43

There are number of colors written over the JList Box in the program, upon the clicking event of any color item in JList, the
color of the frame will change to selected color. The default color of frame is white.

JList Program

Output

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
public class JListDemo extends JFrame {
JList list;
String[] listColorNames = { "black", "blue", "green", "yellow",
"white" };
Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN,
Color.YELLOW, Color.WHITE };
Container contentpane;
public JListDemo() {
super("List Source Demo");
contentpane = getContentPane();
contentpane.setLayout(new FlowLayout());
list = new JList(listColorNames);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contentpane.add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
contentpane.setBackground(listColorValues[list
.getSelectedIndex()]);
}
});
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
JListDemo test = new JListDemo();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

44

The program contains two combo box containing items A-J character in combo box.

ComboBox Program

Output

import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ComboBoxSample {
public static void main(String args[]) {
String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","I",
"J" };
String title = (args.length == 0 ? "Example JComboBox" :
args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentpane = frame.getContentPane();
JComboBox comboBox1 = new JComboBox(labels);
comboBox1.setMaximumRowCount(5);
contentpane.add(comboBox1, BorderLayout.NORTH);
JComboBox comboBox2 = new JComboBox(labels);
comboBox2.setEditable(true);
contentpane.add(comboBox2, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

The program contains a Jlabel having text IQRA UNIVERSITY.

JLabel Program

Output

import java.awt.*;
import javax.swing.*;
public class JLabelDemo {
public static void main(String[] args) {
JLabel label = new JLabel("IQRA UNIVERSITY");
label.setOpaque(true);
label.setBackground(Color.blue);
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new FlowLayout());
cp.setBackground(Color.white);
cp.add(label);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

45

There are four JRadio buttons. Upon clicking a single item in the frame that JRadio Buttons text will appear over the
command prompt window.

JRadioButton Program

Output

// JRadioButton Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JRadioButtonExample {
public static void main(String[] args) {
ActionListener listener = new ActionListener() {
public void actionPerformed (ActionEvent e) {
System.out.println(e.getActionCommand());
}
};
Box p = new Box(BoxLayout.Y_AXIS);
ButtonGroup group = new ButtonGroup();
String[] sa = {"ugli","kiwi","passion","kumquat"};
for(int i=0;i<sa.length;++i) {
JRadioButton b = new JRadioButton(sa[i]);
group.add(b);
p.add(b);
b.addActionListener(listener);
}
JFrame frame = new JFrame("Fruits");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(p);
frame.pack();
frame.setVisible(true);
}
}

46

There are five check boxes containing the sports name of Game. Upon checking different check box that contain sports
that will appear over the command prompt window.

JCheckBox

Output

Program

// JCheckBox Example
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
class JCheckBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
Box box = new Box(BoxLayout.Y_AXIS);
cp.add(box);
box.add(new JLabel("Tick the sports you like..."));
String[] sports = {"Football", "Rugby",
"Cricket","Badminton", "Baseball"};
JCheckBox[] cba = new JCheckBox[sports.length];
for (int i = 0; i < sports.length; i++) {
cba[i] = new JCheckBox(sports[i]);
box.add(cba[i]);
cba[i].addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBox jCheckBox = (JCheckBox)e.getSource();
if(jCheckBox.isSelected())
System.out.println(jCheckBox.getText() + " selected");
else
System.out.println(jCheckBox.getText() + " deselected");
}
});
}
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

47

Experiment 15
.
Show Message and Confirm Dialog Box - Swing Dialogs
Program

Output

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ShowMessageDialog{
JButton button;
public static void main(String[] args){
ShowMessageDialog md = new ShowMessageDialog();
}
public ShowMessageDialog(){
JFrame frame = new JFrame("Message Dialog Box");
button = new JButton("Show simple message dialog
box");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(button);
button = new JButton("Show \"Ok/Cancel\" messagedialog
box");
button.addActionListener(new MyAction());
panel.add(button);
button = new JButton("Show \"Yes/No/Cancel\" dialog
box");
button.addActionListener(new MyAction());
panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent ae){
String str = ae.getActionCommand();
if(str.equals("Show simple message dialog box")){
JOptionPane.showMessageDialog(null, "This is the
simple message dialog box.", "Iqra University", 1);
}
else if(str.equals("Show \"Ok/Cancel\" messagedialog
box")){
if(JOptionPane.showConfirmDialog(null, "This is
the \"Ok/Cancel\"message dialog box.", "Iqra University",
JOptionPane.OK_CANCEL_OPTION) == 0)
JOptionPane.showMessageDialog(null, "You clicked on
\"Ok\" button","Iqra University", 1);
else
JOptionPane.showMessageDialog(null, "You clicked on
\"Cancel\" button","Iqra University", 1);
}
else if(str.equals("Show \"Yes/No/Cancel\" dialog box")){
JOptionPane.showConfirmDialog(null, "This is
the \"Yes/No/Cancel\" message dialog box.");
}
}
}
}

48

Swing Input Dialog Box Example - Swing Dialogs


Program

Output

import javax.swing.*;
import java.awt.event.*;
public class ShowInputDialog{
public static void main(String[] args){
JFrame frame = new JFrame("Input Dialog Box Frame");
JButton button = new JButton("Show Input Dialog Box");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String str = JOptionPane.showInputDialog(null, "Enter
some text : ",
"Iqra University", 1);
if(str != null)
JOptionPane.showMessageDialog(null, "You entered
the text : " + str,
"Iqra University", 1);
else
JOptionPane.showMessageDialog(null, "You pressed
cancel button.",
"Iqra University", 1);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
frame.setVisible(true);
}
}

49

Combo Box operation in Java Swing


In this program, you can learn how to operate the Combo Box component, you will learn how to add items to the combo
box, remove items from the combo box.
Program
Output
import javax.swing.*;
import java.awt.event.*;
public class AddRemoveItemFromCombo{
JComboBox combo;
JTextField txtBox;
public static void main(String[] args){
AddRemoveItemFromCombo ar = new
AddRemoveItemFromCombo();
}
public AddRemoveItemFromCombo(){
JFrame frame = new JFrame("Add-Remove Item of a Combo
Box");
String items[] = {"Java", "JSP", "PHP", "C", "C++"};
combo = new JComboBox(items);
JButton button1 = new JButton("Add");
txtBox = new JTextField(20);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (!txtBox.getText().equals("")){
int a = 0;
for(int i = 0; i < combo.getItemCount(); i++){
if(combo.getItemAt(i).equals(txtBox.getText())){
a = 1;
break;
}
}
if (a == 1)
JOptionPane.showMessageDialog(null,"Combo has already
this item.");
else
combo.addItem(txtBox.getText());
}
else{
JOptionPane.showMessageDialog(null,"Please enter text in
Text Box");
}
}
});
JButton button2 = new JButton("Remove");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (combo.getItemCount() > 0)
combo.removeItemAt(0);
else
JOptionPane.showMessageDialog(null,"Item not available");
}
});
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
panel.add(txtBox);
panel.add(combo);
panel.add(button1);
panel.add(button2);
frame.add(panel);
// frame.add(panel1);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Selecting a JRadioButton Component in a Button Group


In this program, you will learn how to set the radio buttons in a group so that only one can be selected at a time.
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

Output

public class SelectRadioButton{


JLabel label;
50

public static void main(String[] args){


SelectRadioButton sr = new SelectRadioButton();
}
public SelectRadioButton(){
JFrame frame = new JFrame("Radio button selection");
JRadioButton first = new JRadioButton("First");
JRadioButton second = new JRadioButton("Second");
JRadioButton third = new JRadioButton("Third");
JRadioButton fourth = new JRadioButton("Fourth");
JRadioButton fifth = new JRadioButton("Fifth");
JPanel panel = new JPanel();
panel.add(first);
panel.add(second);
panel.add(third);
panel.add(fourth);
panel.add(fifth);
ButtonGroup bg = new ButtonGroup();
bg.add(first);
bg.add(second);
bg.add(third);
bg.add(fourth);
bg.add(fifth);
first.addActionListener(new MyAction());
second.addActionListener(new MyAction());
third.addActionListener(new MyAction());
fourth.addActionListener(new MyAction());
fifth.addActionListener(new MyAction());
label = new JLabel("Iqra University");
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
label.setText(e.getActionCommand());
JOptionPane.showMessageDialog(null,"This is the " +
e.getActionCommand() +
" radio button.");
}
}
}

51

Setting a Tool Tip for an Item in a JList Component


In this program, you will learn how to set the tool tip text for items present in the JList component of the Java Swing. Tool
Tip text is the help text of any component for user.
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

Output

public class TooltipTextOfList{


private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements
ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter
text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added
successfully.");
txtItem.setText("");
}
}
}
}

52

Experiment 16

To create a Login Form, we have used two class files:


1) NextPage.java
2) Login.java
In the Login.java, we have create two text fields text1 and text2 to set the text for username and password. A button is
created to perform an action. The method text1.getText() get the text of username and the method text2.getText() get the
text of password which the user enters. Then we have create a condition that if the value of text1 and text2 is iqra, the
user will enter into the next page on clicking the submit button. The NextPage.java is created to move the user to the next
page. In case if the user enters the invalid username and password, the class JOptionPane provides the MessageDialog
to shows the error message.

Program
import javax.swing.*;
import java.awt.*;

Output

class NextPage extends JFrame


{
NextPage()
{
setDefaultCloseOperation(javax.swing.
WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome To Iqra University");
setSize(400, 200);
}
}
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Login extends JFrame implements ActionListener
{
JButton SUBMIT;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
Login()
{
label1 = new JLabel();
label1.setText("Username:");
text1 = new JTextField(15);
label2 = new JLabel();
label2.setText("Password:");
text2 = new JPasswordField(15);
SUBMIT=new JButton("SUBMIT");
panel=new JPanel(new GridLayout(3,1));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
add(panel,BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae)
{
String value1=text1.getText();
String value2=text2.getText();
if(value1.equals("iqra") && value2.equals("iqra")) {
53

NextPage page=new NextPage();


page.setVisible(true);
JLabel label = new JLabel("Welcome:"+value1);
page.getContentPane().add(label);
}
else{
System.out.println("enter the valid username and
password");
JOptionPane.showMessageDialog(this,"Incorrect login or
password",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String arg[])
{
try
{
Login frame=new Login();
frame.setSize(300,100);
frame.setVisible(true);
}
catch(Exception e)
{JOptionPane.showMessageDialog(null, e.getMessage());}
}
}

54

In this section, you will learn about creation of menus, submenus and Separators in Java Swing. Menu bar contains a
collection of menus. Each menu can have multiple menu items these are called submenu.
Program
import javax.swing.*;

Output

public class SwingMenu{


public static void main(String[] args) {
SwingMenu s = new SwingMenu();
}
public SwingMenu(){
JFrame frame = new JFrame("Creating a JMenuBar,
JMenu, JMenuItem and seprator Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
filemenu.add(new JSeparator());
JMenu editmenu = new JMenu("Edit");
editmenu.add(new JSeparator());
JMenuItem fileItem1 = new JMenuItem("New");
JMenuItem fileItem2 = new JMenuItem("Open");
JMenuItem fileItem3 = new JMenuItem("Close");
fileItem3.add(new JSeparator());
JMenuItem fileItem4 = new JMenuItem("Save");
JMenuItem editItem1 = new JMenuItem("Cut");
JMenuItem editItem2 = new JMenuItem("Copy");
editItem2.add(new JSeparator());
JMenuItem editItem3 = new JMenuItem("Paste");
JMenuItem editItem4 = new JMenuItem("Insert");
filemenu.add(fileItem1);
filemenu.add(fileItem2);
filemenu.add(fileItem3);
filemenu.add(fileItem4);
editmenu.add(editItem1);
editmenu.add(editItem2);
editmenu.add(editItem3);
editmenu.add(editItem4);
menubar.add(filemenu);
menubar.add(editmenu);
frame.setJMenuBar(menubar);
frame.setSize(400,400);
frame.setVisible(true);
}
}

55

In this section, you will learn how to create toolbar in java. Swing provides a most important feature for creating an
interactive component.
Program
import javax.swing.*;
import java.awt.*;

Output

public class CreateToolbar{


public static void main(String[] args) {
JFrame frame = new JFrame("Create a toolbar Which
have three buttons Such as: Cut, Copy, Paste");
JToolBar toolbar = new JToolBar("Toolbar",
JToolBar.HORIZONTAL);
JButton cutbutton = new JButton(new
ImageIcon("cut.gif"));
toolbar.add(cutbutton);
JButton copybutton = new JButton(new
ImageIcon("copy.gif"));
toolbar.add(copybutton);
JButton pastebutton = new JButton(new
ImageIcon("paste.gif"));
toolbar.add(pastebutton);
frame.getContentPane().add(toolbar,BorderLayout.NORTH
);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPa
ne.PLAIN_DIALOG);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
);
frame.setSize(500,400);
frame.setVisible(true);
}
}}

56

Вам также может понравиться