SBL Oopm - Java Lab
SBL Oopm - Java Lab
Theory:
Selection Statements:
if: The statement is used to select what part of the program should execute according to
different conditions arising in a program.
It has following three general syntaxes
1. if ( condition )
statement
2. if( condition )
Statement1
else
Statment2
3. if ( condition1)
Statement1
else if ( condition2)
Statement2
else if ( condition3)
Statement3
…
else
Statement..n
The if, if-else and if-else if statements should not have semicolons. If multiple statements are to be
written for one condition, then those statements must be enclosed inside the curly braces.
Description:
Perfect no is four digit (e.g. 1681) which is a perfect square. Also, the numbers formed by its left two
digits (e.g.16) and right two digits (e.g. 81) are also perfect squares.
Program:
import [Link].*;
class Pract01A
{
public static void main (String[] args)
{
Scanner sc = new Scanner([Link]);
int no, lf, rt;
double r1, r2, r3;
[Link]("Enter a number :");
no = [Link]();
if( no>=1000 && no<= 9999 )
{
r1 = [Link](no);
if( r1 == [Link](r1))
{
lf = no / 100;
rt = no % 100;
r2 = [Link]( lf);
r3 = [Link](rt);
if( r2 == [Link](r2) && r3 == [Link](r3))
[Link]("The number is Perfect number");
else
[Link]("The number is Not a perfect number");
}
else
[Link]("Given number is Not a perfect number");
}
else
[Link]("Given number is Not 4-digit number");
}
}
Output:
Enter a number: 1681
Given number is Perfect number
Enter a number :2536
Given number is Not a perfect number
b) Program to find sum of digits in a given integer.
e.g. input number=3482, then sum of digits =17
Theory:
Iteration statements: (Looping statements):
These statements make some part of program repeat for multiple time till some condition is
true. The statements are while, for, do-while. (same as those in C++).
while: The looping statement is used to repeat a block of statements till some condition is
true. The condition should be a Boolean expression.
while ( condition)
statements
Program :
import [Link].*;
class Pract01B
{
public static void main (String[] args)
{
Scanner sc = new Scanner([Link]);
int no, d, sum=0;
[Link]("Enter a number :");
no = [Link]();
while( no != 0 )
{
d = no % 10;
sum = sum + d;
no = no / 10;
}
[Link]("Sum of digits=" + sum);
}
}
Output :
Enter a number :6253
Sum of digits=16
Practical 2:
Aim: Write a program to calculate area of Circle and area of Rectangle using method
overloading
Theory:
Java class can consist of multiple methods with the same name but different type of
parameters or different number of parameters. Such methods are called Overloaded methods.
This feature of Java is called as Method overloading.
This is a feature of OOP called Polymorphism. This, allows defining multiple methods with
same name in the same scope (here, same class). But the methods are differentiated by their
parameters.
Overloaded Methods can have any combination of data-types, but each combination should
be unique. This unique definition of each method is also called Signature of a method.
e.g. int add (int a, int b), float add (float a, float b), long add (long a, int b), and int add (int a,
int b, int c) are all treated as different methods. These definitions are called Signatures.
Program:
import [Link].*;
class Pract02
{
static void area( int len, int br)
{
int a = len * br;
[Link]("Area of Rectangle=" + a );
}
}
}
Output :
Enter Length and breadth :
12
4
Area of Rectangle=48
Program:
import [Link].*;
class Account
{
int actno;
String name;
double balance;
void input()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Name :");
name = [Link]();
[Link]("Enter Act. No :");
actno = [Link]();
[Link]("Enter Amount in account :");
balance = [Link]();
}
void output()
{
[Link]("-- Account info. --");
[Link]("Account no :" + actno);
[Link]("Name :" + name);
[Link]("Balance Amount :" + balance);
}
void deposit(double a)
{
balance += a;
}
void withdraw(double a)
{
if( balance-a >=2000)
balance -= a;
else
[Link]("* Insufficient Balance");
}
}
class Pract03
{
public static void main (String[] args)
{
Scanner sc = new Scanner([Link]);
double amt;
Account act = new Account();
[Link]();
[Link]();
[Link]("- Enter amount to deposit :");
amt = [Link]();
[Link](amt);
[Link]();
Theory:
Strings in Java:
Any data enclosed in a double quotation symbols (“ ”) is a string in Java.
Also, strings are represented by Java class String.
e.g.
String s = “Hello Java”;
Here, an object is created that holds string ‘Hello Java’ and the reference variable s refers to it.
Every string value in Java is an object of predefined Java class String.
The class is included in Java’s default package [Link].
The String class has a lot of methods to work with string data e.g. Comparing two strings, reading
character at a required index in the string, Converting all letters in a string to upper/lower case etc.
The String class methods that are used to alter string do not alter the original string contents but they
return a new string object, which consist of an altered character.
Almost all the string methods are case sensitive.
The method that deal with the index of characters, generate
IndexOutOfBoundsException if an index outside the string length is accessed.
e.g. [Link]( 10) ; will generate above exception.
Program:
import [Link].*;
class Pract04
int j;
String r;
char ch;
j = [Link]();
[Link]("Length =" + j);
ch = [Link]( 2 );
r = [Link]( 1, 6);
[Link]("Substring 1 to 5 =" + r );
j = [Link]( 'b');
j = [Link]( 'R');
[Link]("index of R=" + j );
j = [Link]( "bc");
[Link]("index of bc=" + j );
if( [Link](c))
else
[Link]("Words in string" );
[Link]( ar[j] );
r = [Link]();
Output :
Theory:
It’s a feature of OOP by virtue of which an object can acquire (inherit) some or all the
members of another object (or a class).
Inheritance is one of the important features of OOP, by which we can define a new class
using pre-existing class, and the new class works like extension of old (i.e. pre-existing)
class.
Thus, it provides re-usability of a code.
The new class has its own features plus the features inherited form the preexisting class. This
process is called inheritance or extending class.
Single inheritance:
When a class is derived from single super class, it is called as single inheritance.
e.g.
class A
{
private in b;
void x() A
{ // some statements
}
public void y() B
{ // some statements
}
}
class B extends A
{
int m;
void pq()
{ // some statements
}
}
Output:
- Single inheritance -
Enter employee data ..
Enter Name:Ajay
Enter age:34
Enter Dept:Computer
Enter salary:45000
- Employee data -
Name : Ajay
Age : 34
Department: Computer
Salary : 45000.0
Practical :6
Aim: Write a program to input two numbers from user and display the answer of
dividing first number by second number on Exception handling in Java.
Theory:
Exception is a run-time error. Such types of errors occur when some abnormal conditions
arise in some part of a program while it is running.
These errors can occur because of: (Causes of exceptions)
Sudden failures in hardware, used by the program or use of invalid or restricted resources by
the program.
Errors can also occur while program execution because of in-correct (or invalid) data input
done by user. The other reason of run-time error is because of mismatched data types.
Run-time error can occur because some error prone statements e.g. statement accessing array
element outside the array limit.
Java uses Object-oriented approach for Exception handling. Exception in Java is an object of
some class that describes the error-condition that has occurred in some part of a program.
For handling the exceptions occurring in a program, Java provides a special block of
statements, called try-catch-finally block. try, catch and finally are the keywords in Java.
The syntax for exception handling block is as follows.
try
{
// program segment that can generate (i.e. throw) exceptions
}
catch ( exception_type1 obj1 )
{
// Statements to handle (or describe) the exception
}
catch ( exception_type2 obj2 )
{
// Statements to handle (or describe) the exception
}
catch ( exception_type3 obj3 )
{
// Statements to handle (or describe) the exception
}
… some catch blocks
finally
{
// Statements which must work (whatever way try-catch works)
}
Program statement:
Handle different exceptions.
Program :
import [Link].*;
class Pract06
{
public static void main( String[ ] args )
{
Scanner sc = new Scanner([Link]);
int a,b,c;
try
{
[Link]("Enter first integer:");
a = [Link]();
[Link]("Enter second integer:");
b = [Link]();
c = a / b;
[Link]("Ans = " + c );
}
catch( InputMismatchException ex2 )
{
[Link]("Input integer values only");
}
catch( ArithmeticException ex3 )
{
[Link]("Divide by zero Error occured");
}
catch( Exception ex )
{
[Link]("Exception occured : " + ex);
}
finally
{
[Link]("== This is finally block ==");
}
}
}
Outputs:
1)
Enter first integer:20
Enter second integer:4
Ans = 5
== This is finally block ==
2)
Enter first integer:5
Enter second integer:0
Divide by zero Error occurred
== This is finally block ==
3)
Enter first integer:15
Enter second integer:ab
Input integer values only
== This is finally block ==
Practical 7:
Aim: Write a menu driven program to work with list of names, with following options
like 1. Add name, 2. Remove name, 3. Display list Using Vector class.
Program:
import [Link].*;
class namelist
{
public static void main (String [ ] args)
{
Scanner sc = new Scanner([Link]);
Vector v = new Vector( );
String name;
int opt, i;
while( true )
{
[Link](".. Options ..");
[Link]("1.. Add Name");
[Link]("2.. Remove name");
[Link]("3.. Display names");
[Link]("4.. Quit");
[Link]("Enter option :");
opt = [Link]();
switch( opt )
{
case 1 : [Link]("-Enter a Name ");
name = [Link]();
if( [Link]( name ) )
[Link]("Name already exists in the list");
else
[Link]( name );
break;
case 2 : [Link]("-Enter a Name to remove");
name = [Link]();
if( [Link]( name ) )
[Link]( name );
else
[Link]("Name Not found in the list");
break;
case 3 :
int s = [Link]();
[Link]("Names...");
for( i=0; i<s; i++)
{
[Link]( [Link](i) );
}
break;
case 4 : [Link]( “End” );
return;
}
} // ... while ends
}
}
Output:
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :1
-Enter a Name Ajay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :1
-Enter a Name Vijay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :1
-Enter a Name Sanjay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :3
Names...
Ajay
Vijay
Sanjay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :2
-Enter a Name to remove
Vijay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :3
Names...
Ajay
Sanjay
.. Options.
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option : 4
End
Practical:8
Aim: Demonstration of Multithreading
Theory:
Java provides support for writing Multithreaded programs. A multithreaded program consists
of
multiple parts of the same program running concurrently (i.e. simultaneously). Here each part
of
the program working simultaneously is called a thread, and each thread can work
independently. Also
each thread can be performing different task.
Two ways of achieving multithreading:
[Link] Thread class of Java: The class that has to start a new thread can extend a Thread
class of Java.
The class that extends Thread has to override a run() method. The code written in run() works
as a code for new thread.
Program Statement: Define two thread classes. One prints 10 alphabets (A to J), and the other
prints 10 integers (1 to 10). Use these classes in main program to demonstrate Multithreading.
Program:
class Numbers extends Thread
{
public void run()
{
for( int i=1; i<=10; i++ )
{
[Link]( " " + i );
try
{ [Link](50);
}catch(Exception ex)
{ [Link]("Error");
}
}
}
class Chars extends Thread
{
public void run()
{
char ch='A';
for( int i=1; i<=10; i++ )
{
[Link]( " " + ch );
ch++;
try
{ [Link](50);
}catch(Exception ex)
{ [Link]("Error");
}
}
}
}
class Pract07
{
public static void main(String [] args )
{
Numbers nos = new Numbers();
// Start threads
[Link]();
[Link]();
}
}
Theory:
Applets are Java programs which run on Web Browser.
Applets run on internet Browsers only with the help of JVM in browser. HTML tag <Applet>
is used to load and run applet on a Web page.
To write applet program we need to use Java’s built-in class Applet.
Java applets entry point is init() method. And the method is called by Brower.
Applets can use limited set of Java API and are particularly used to interact with web page
user.
For running an Applet we need to use some Web Browser or one can use an application
called ‘appletviewer’, which is used for testing and running applet programs only.
Program:
import [Link];
import [Link].*;
public class Pract09 extends Applet
{
public void paint(Graphics g)
{
// Ovals for eyes
[Link]( 50, 50, 60, 30 ); // x, y, w , h
[Link]( 140, 50, 60, 30 );
// Vertical line for nose
[Link](125, 60, 125, 110); // x1, y1, x2, y2
// lips (mouth)
[Link]( 80, 130, 100, 5 ); // x, y, w, h
// full face
[Link](25, 5 , 200, 200 );
}
}
// Following line loads the applet in browser window
/*
<Applet code="[Link]" width=500 height=500>
</applet>
*/
Output:
Practical 10 :
Aim : Write a GUI based application using AWT, which inputs two numbers and
displays the sum. Use Frame, Buttons, Text boxes and Lables. Use event handling to get
the answer.
Theory :
Java provides a package [Link] that has classes and interfaces using which one can develop
GUI based applications.
Some classes are component classes e.g. Button, Label, Textfield. These classes are used to
create visible GUI components.
There are some classes like Window, Frame which are used to create containers to define
main Window for GUI applications.
It also provides some interfaces which are used in Event handling. The methods from these
interfaces must be implemented to perform required action according user’s action and other
events.
In this program we are using Button, TextField, Frame and Label classes for GUI design.
Also, ActionListener interface is used for Event handling.
The code for event handling is written in method actionPerfomed().
The classes/interfaces For event handling are imported from [Link] package.
Program :
import [Link].*;
import [Link].*;
class AddNos extends Frame
{
// Defining objects of the required AWT components
Label lbl1 = new Label("Number 1");
TextField txtno1 = new TextField();
Label lbl2 = new Label("Number 2");
TextField txtno2 = new TextField();
Button btnadd = new Button("Add");
Label lbl3 = new Label("Sum");
Label lblsum = new Label("-");
Button btnclose = new Button("Close");
// Putting components on Window
AddNos()
{
super("Add Numbers");
// Remove default layout
setLayout(null);
// set position and size of components
[Link]( 50, 50, 80, 30 );
[Link](200, 50, 80, 30 );
[Link]( 50, 100, 80, 30 );
[Link](200, 100, 80, 30 );
[Link]( 50, 150, 80, 30 );
[Link](200, 150, 80, 30 );
[Link]( 100, 200, 70, 30 );
[Link]( 200, 200, 70, 30 );
// add the components on window
add(txtno1); add(txtno2); add(lbl1);
add(lbl2); add(lbl3); add(lblsum);
add(btnadd); add(btnclose);
Theory :
Java Swing :
• Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’
• Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and
Applets
• Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.
• Java Swing Components are Platform-independent, and The Swing Components are
lightweight.
• Swing Supports a Pluggable look and feel and Swing provides more powerful components.
Method getState() is used to get the status of Radio button i.e. checked or unchechked. The method
returns true if checked else false.
An interface ItemListener is used to listen to the click and change events of Radio buttons. The
method itemStateChanged() is used to handle and write code for the events.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
Output :
Practical: 12
Theory :
• JavaFX is a media/graphics framework for creating GUI in Java Applications.
• It is more powerful than Java Swing.
• It is used to create both Windows as well a Web Applications.
• It draws its own components ( so less communication with OS). Hence, they are
lightweight components.
Download Prper JavaFx SDK that matches your Java version ( and JavaFX Scene if required
)
Extract the file into some folder e.g. c:\javafx17
Go to Settings -> Env Varibales
Add following name :
Name : PATH_TO_FX
Value : c:\javafx17\lib (in out example)
Run :
java --module-path C:\JavaFX17\lib --add-modules [Link] JavaFx1
Program :
JavaFx_Shapes.java
// user defined mthod to create Text object for given co-ordinates and
String data
Text createText(String data, double x, double y )
{
Text text = new Text(data);
[Link](x);
[Link](y);
return text;
}
}
public static void main(String []args)
{
// Load the application by calling 'launch' method
launch(args);
}
}
Output :
Practical: 13
Theory :
• JavaFX is a media/graphics framework for creating GUI in Java Applications.
• It is more powerful than Java Swing.
• It is used to create both Windows as well a Web Applications.
• It draws its own components ( so less communication with OS). Hence, they are
lightweight components.
Program :
//import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JavaFX_LoginDemo extends Application implements
EventHandler<ActionEvent>
{
TextField txtuser = new TextField();
PasswordField txtpsw = new PasswordField();
Button btnLogin = new Button("Login");
Label lblmsg = new Label("...");
Stage window;
@Override
public void start(Stage primaryStage)
{
window = primaryStage;
GridPane grid = new GridPane();
[Link]([Link]);
[Link](10);
[Link](10);
[Link](new Insets(10));
[Link]("user name...");
[Link](txtuser, 1, 1);
[Link](btnLogin, 1, 3 );
[Link](lblmsg, 1,4);
[Link](this);
-------------
Mini Project: Bank Account based on OOPM
Develop a small Java Application using Java, JDBC and Database.
Program:
Program for Bank account operations.
Form to create new Bank account. Other form for Transactions like Depositing money and
Withdrawal of amount from an account.
Create multiple bank account using database and demonstrate above operations.
Java Program :
1. Main form with menu.
import [Link].*;
import [Link].*;
-------------------------------------------------
2. Customer Form:
import [Link].*;
import [Link].*;
import [Link].*;
[Link](210,300,70,30);
[Link](320,300, 70, 30 );
void clearFields()
{
[Link]();
[Link]("");
[Link]("");
[Link]("- -");
}
class demo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String s=[Link]();
if([Link]("ADD"))
{
Connection con=null;
Statement st=null;
try
{
// string mentions which jdbc driver to load
[Link]("[Link]");
//string to mention which db to connect
con=[Link]
("jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();
else if([Link]("DELETE"))
{
clearFields();
int b;
Connection con=null;
Statement st=null;
b=[Link]([Link]());
try
{
[Link]("[Link]");
con=[Link]
("jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();
String str="delete from customer where custid=" + b;
[Link](str);
lblmsg .setText("Customer record deleted");
}
catch(Exception ec)
{
[Link]("Error ..");
}
finally
{
try
{
[Link]();
}
catch(Exception ex) { }
}
}/* End of Delete button code */
else if([Link]("OPEN"))
{
clearFields();
int a;
Connection con=null;
Statement st=null;
a=[Link]([Link]());
try
{
[Link]("[Link]");
con=[Link]
("jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();
ResultSet rs=[Link](
"select * from customer where custid="+a);
if([Link]()==true)
{
[Link]([Link]("custname"));
[Link]([Link]("amount")+"");
}
else
[Link]("No such customer");
}
catch(Exception ez)
{
[Link]("Error : " + [Link]());
}
finally
{
try
{ [Link](); }
catch(Exception ex) { }
}
}/* End of Open button code */
else
dispose();
}
} /* End of Listener class */
-----------------------------------------------
3. Account Transactions form :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
class Transaction extends Frame
{
Label lbldate = new Label();
Label l1 = new Label("CUST_ID");
TextField txtid = new TextField();
Label l3 = new Label("Amount");
TextField txtamt = new TextField();
CheckboxGroup cg=new CheckboxGroup();
Checkbox chk1=new Checkbox("WITHDRAW", cg, false);
Checkbox chk2=new Checkbox("DEPOSIT",cg, false);
Button btnnew = new Button("NEW");
Button btnadd = new Button("SUBMIT");
Button btncls = new Button("CLOSE");
Label lblmsg = new Label("TRANSACTION ID=");
Label lbltop = new Label("TRANSACTION Info..");
Transaction()
{
setLayout( null );
Calendar cal = [Link]();
String dt = [Link]([Link]) +
"/" + ([Link]([Link]) +1) + "/" +[Link]([Link]) ;
[Link]( 300, 50, 90, 30);
[Link]( 50, 50, 80 , 30 );
[Link]( 150 , 50, 80, 30 );
[Link]( 50, 150, 80 , 30 );
[Link]( 150 , 150, 80, 30 );
[Link](50, 200, 150, 30);
[Link]([Link]);
[Link](20, 30, 150, 30);
[Link]( dt );
add(lbldate);
add(l1);
add( l3 );
add(txtid);
add(txtamt);
add(lblmsg);
add(lbltop);
[Link](50,300, 70, 30 );
[Link](150, 300, 70, 30 );
[Link](250,300, 70, 30 );
add(btnnew); add(btnadd); add(btncls);
[Link](new demo());
[Link](new demo());
[Link](new demo());
add(chk1); add(chk2);
[Link](200,200,100,30);
[Link](200,250,100,30);
setSize( 500, 500 );
setVisible(true);
}
class demo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String s=[Link]();
if([Link]("CLSOE"))
{
dispose() ;
}
if([Link]("NEW"))
{
Connection con=null;
Statement st=null;
try
{
[Link]("[Link]");
con=[Link](
"jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();
String str="select count(tid)+1 as a from transaction";
ResultSet rs= [Link](str);
[Link]();
lblmsg .setText([Link]("a")+"");
}
catch(Exception ea)
{
[Link]("Error.." + ea);
[Link]("Error ");
}
finally
{
try
{ [Link](); }
catch(Exception ex) { }
}
}
if([Link]("SUBMIT"))
{
int b;
String cid=[Link]();
String tid= lblmsg .getText();
String amt=[Link]();
String type=null;
String str="";
if([Link]()==true)
type=[Link]();
if([Link]()==true)
type=[Link]();
Connection con=null;
Statement st=null;
try
{
[Link]("[Link]");
con=[Link](
"jdbc:mysql://localhost:3306/bankdemo","root","");
[Link](false);
st=[Link]();
str="insert into transaction values(" + tid;
str=str + ","+ cid ;
str=str + ","+ amt ;
str=str + ",'" + [Link]() + "'"; // yyyy-m-d
str=str + ",'" + type + "')";
[Link](str);
if([Link]("WITHDRAW"))
{
str="update customer set amount =
amount - "+ amt+" where custid="+ cid;
}
else
{
str="update customer set amount=
amount + " + amt +" where custid="+cid;
}
[Link](str);
lblmsg .setText("Transaction done!!");
[Link]();
}
catch(Exception ec)
{
[Link]("Error : "+ec);
[Link]("Error : Transation failed");
try{
[Link]();
}catch( Exception ex){ }
}
finally
{
try
{ [Link](); }
catch(Exception ex)
{
}
}
}
}
}
======0000======