0% found this document useful (0 votes)
12 views

Java Lab Problem MCA

BU MCA Java lab problem

Uploaded by

dhanush.v.rao
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Java Lab Problem MCA

BU MCA Java lab problem

Uploaded by

dhanush.v.rao
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

DAYANANDA SAGAR

COLLEGE OF ARTS, SCIENCE AND COMMERCE

MASTER OF COMPUTER APPLICATIONS

ADVANCED JAVA LAB MANUAL


CODE:MCA405P
PREPARED BY
MR.GURUNATH.R (ASST.PROF)
MRS.SRIVATSALA.V (LECTURER)

MCA405P: ADVANCED JAVA PROGRAMMING


LAB
LIST OF PROGRAMS
1. Write a Java program that works as a simple
calculator. Use a grid layout to arrange buttons for the
digits and for the +, -,*, % operations. Add a text field
to display the result.
2. Write a Java program that creates three threads.
First thread displays “Good Morning” every one
second, the second thread displays “Hello” every two
seconds and the third thread displays “Welcome”
every three seconds. ----
3. Write a java program that simulates a traffic light.
The program lets the user select one of three lights:
red, yellow, or green. When a radio button is selected,
the light is turned on, and only one light can be on at a
time No light is on when the program starts
4.Write a Java Program to execute select query using
JDBC.
5. Write a Java Program to Create Thread using
Interface and class.
6. Write a Java Program to Implement Producer and
Consumer problem using Threads.
7. Write a Java Program to Implement DOM parser .
8. Write a Java Program to Implement SAX parser.
9. Write a Java Program to Implement Singleton
design pattern using java.
10. Write a Java Program to Implement Factory and
AbstractFactory design pattern
using java.
11. Write a Java Program to Implement Observer
Design pattern method using java.
12. Write a Java Program to Implement Adapter
design design pattern using java
13. Write a Java Program to Implement proxy design
pattern using java
14. Write a Java Program to Implement Helloworld
program using servlets.
15. Write a JSP Program using Expression, Scriplet
and Directive.

PROGRAMS

1. Write a Java program that works as a simple


calculator. Use a grid layout to arrange buttons for the
digits and for the +, -,*, % operations. Add a text field
to display the result.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet implements
ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}

Output:
2. Write a Java program that creates three threads.
First thread displays “Good Morning” every one
second, the second thread displays “Hello” every two
seconds and the third thread displays “Welcome”
every three seconds.

class A extends Thread


{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{}
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{}
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}

Output:
3. Write a java program that simulates a traffic light.
The program lets the user select one of three lights:
red, yellow, or green. When a radio button is selected,
the light is turned on, and only one light can be on at a
time No light is on when the program starts

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TrafficLight extends JFrame implements
ActionListener
{
String msg=" " ;
private JLabel label;
private JTextField display;
private JRadioButton r1,r2,r3;
private ButtonGroup bg;
private Container c;
public TrafficLight()
{
setLayout(new FlowLayout());
c=getContentPane();
label=new JLabel(" Traffic Light");
display =new JTextField(10);
r1=new JRadioButton("RED");
r2=new JRadioButton("GREEN");
r3=new JRadioButton("YELLOW");
bg=new ButtonGroup();
c.add(label);
c.add(r1);
c.add(r2);
c.add(r3);
c.add(display);
bg.add(r1);
bg.add(r2);
bg.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);
setSize(400,400);
setVisible(true);
c.setBackground(Color.pink);
}
public void actionPerformed(ActionEvent ie)
{
msg=ie.getActionCommand();
if (msg.equals("RED"))
{
c.setBackground(Color.RED);
display.setText(msg+ " :TURN ON");
}
else if (msg.equals("GREEN"))
{
c.setBackground(Color.GREEN);
display.setText(msg+ " :TURN ON");
}
else if (msg.equals("YELLOW"))
{
c.setBackground(Color.YELLOW);
display.setText(msg+ " :TURN ON");
}
}
public static void main(String args[])
{
TrafficLight light=new TrafficLight();
light.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);
}
}
Output:
4. Write a Java Program to execute select query using
JDBC
//STEP 1. Import required packages

import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER =
"com.mysql.jdbc.Driver";
static final String DB_URL =
"jdbc:mysql://localhost/student";

// Database credentials
static final String USER = "root ";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to a selected
database...");
conn = DriverManager.getConnection(DB_URL,
USER, PASS);
System.out.println("Connected database
successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();

String sql = "SELECT


regno,name,course,address,emailid,phone FROM
student";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String regno = rs.getString("regno");
String name = rs.getString("name");
String course = rs.getString("course");
String emailid = rs.getString("emailid");
String phone=rs.getString(“phone”);

//Display values
System.out.print("regno: " +regno);
System.out.print(", name: " + name);
System.out.print(", course: " + course);
System.out.println(", emailid: " + emailid);
System.out.println(", phone: " + phone);

}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}
Create database Student and a table called student
under it in mysql
Login to mysql with username “root” and password :
no password or whatever password you have created.

5. Write a Java Program to Create Thread using


Interface and class.

//This class is made as a thread by implementing


"Runnable" interface.
class FirstThread implements Runnable
{

//This method will be executed when this thread is


executed
public void run()
{

//Looping from 1 to 10 to display numbers from 1 to


10
for ( int i=1; i<=10; i++)
{
//Displaying the numbers from this thread
System.out.println( "Messag from First Thread :
" +i);

/*taking a delay of one second before displaying


next number
*
* "Thread.sleep(1000);" - when this statement is
executed,
* this thread will sleep for 1000 milliseconds (1
second)
* before executing the next statement.
*
* Since we are making this thread to sleep for one
second,
* we need to handle "InterruptedException". Our
thread
* may throw this exception if it is interrupted
while it
* is sleeping.
*
*/
try
{
Thread.sleep (1000);
}
catch (InterruptedException
interruptedException)
{
/*Interrupted exception will be thrown when a
sleeping or waiting
*thread is interrupted.
*/
System.out.println( "First Thread is
interrupted when it is sleeping"
+interruptedException);
}
}
}
}
//This class is made as a thread by implementing
"Runnable" interface.
class SecondThread implements Runnable
{

//This method will be executed when this thread is


executed
public void run()
{

//Looping from 1 to 10 to display numbers from 1


to 10
for ( int i=1; i<=10; i++)
{
System.out.println( "Messag from Second
Thread : " +i);

/*taking a delay of one second before displaying


next number
*
* "Thread.sleep(1000);" - when this statement is
executed,
* this thread will sleep for 1000 milliseconds (1
second)
* before executing the next statement.
*
* Since we are making this thread to sleep for
one second,
* we need to handle "InterruptedException".
Our thread
* may throw this exception if it is interrupted
while it
* is sleeping.
*/
try
{
Thread.sleep(1000);
}
catch (InterruptedException
interruptedException)
{
/*Interrupted exception will be thrown when a
sleeping or waiting
* thread is interrupted.
*/
System.out.println( "Second Thread is
interrupted when it is sleeping"
+interruptedException);
}
}
}
}
public class ThreadProg
{
public static void main(String args[])
{
//Creating an object of the first thread
FirstThread firstThread = new FirstThread();

//Creating an object of the Second thread


SecondThread secondThread = new
SecondThread();

//Starting the first thread


Thread thread1 = new Thread(firstThread);
thread1.start();
//Starting the second thread
Thread thread2 = new Thread(secondThread);
thread2.start();
}
}

Output:
6.Write a Java Program to Implement Producer and
Consumer problem using Threads.
class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{

System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueSet)
try
{
wait();
}
catch (Interrupted Exception e)
{

System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer (Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run ()
{
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to
stop.");
}
}
Output:
7. Write a Java Program to Implement DOM parser .

import java.io.File;
import
javax.xml.parsers.DocumentBuilderFactory
;
import
javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

//Get Document Builder


DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
//Build Document
Document document = builder.parse(new
File("employees.xml"));

//Normalize the XML Structure; It's just too


important !!
document.getDocumentElement().normalize();

//Here comes the root node


Element root = document.getDocumentElement();
System.out.println(root.getNodeName());

//Get all employees


NodeList nList =
document.getElementsByTagName("employee");
System.out.println("=======================
=====");

for (int temp = 0; temp < nList.getLength(); temp+


+)
{
Node node = nList.item(temp);
System.out.println(""); //Just a separator
if (node.getNodeType() ==
Node.ELEMENT_NODE)
{
//Print each employee's detail
Element eElement = (Element) node;
System.out.println("Employee id : " +
eElement.getAttribute("id"));
System.out.println("First Name : " +
eElement.getElementsByTagName("firstName").ite
m(0).getTextContent());
System.out.println("Last Name : " +
eElement.getElementsByTagName("lastName").ite
m(0).getTextContent());
System.out.println("Location : " +
eElement.getElementsByTagName("location").item
(0).getTextContent());
}
}

Output:

employees
============================

Employee id : 111
First Name : Lokesh
Last Name : Gupta
Location : India

Employee id : 222
First Name : Alex
Last Name : Gussin
Location : Russia

Employee id : 333
First Name : David
Last Name : Feezor
Location : USA

8. Write a Java Program to Implement SAX parser.

<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
UserHandler.java

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class UserHandler extends DefaultHandler {

boolean bFirstName = false;


boolean bLastName = false;
boolean bNickName = false;
boolean bMarks = false;

@Override
public void startElement(String uri,
String localName, String qName, Attributes
attributes)
throws SAXException {
if (qName.equalsIgnoreCase("student")) {
String rollNo = attributes.getValue("rollno");
System.out.println("Roll No : " + rollNo);
} else if (qName.equalsIgnoreCase("firstname")) {
bFirstName = true;
} else if (qName.equalsIgnoreCase("lastname")) {
bLastName = true;
} else if (qName.equalsIgnoreCase("nickname")) {
bNickName = true;
}
else if (qName.equalsIgnoreCase("marks")) {
bMarks = true;
}
}

@Override
public void endElement(String uri,
String localName, String qName) throws
SAXException {
if (qName.equalsIgnoreCase("student")) {
System.out.println("End Element :" + qName);
}
}

@Override
public void characters(char ch[],
int start, int length) throws SAXException {
if (bFirstName) {
System.out.println("First Name: "
+ new String(ch, start, length));
bFirstName = false;
} else if (bLastName) {
System.out.println("Last Name: "
+ new String(ch, start, length));
bLastName = false;
} else if (bNickName) {
System.out.println("Nick Name: "
+ new String(ch, start, length));
bNickName = false;
} else if (bMarks) {
System.out.println("Marks: "
+ new String(ch, start, length));
bMarks = false;
}
}
}
SAXParserDemo.java

import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserDemo {


public static void main(String[] args){

try {
File inputFile = new File("input.xml");
SAXParserFactory factory =
SAXParserFactory.newInstance();
SAXParser saxParser =
factory.newSAXParser();
UserHandler userhandler = new UserHandler();
saxParser.parse(inputFile, userhandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

9. Write a Java Program to Implement Singleton


design pattern using java.

public class MySingleTon {


private static MySingleTon myObj;
/**
* Create private constructor
*/
private MySingleTon(){
}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
public void getSomeThing(){
// do something here
System.out.println("I am here....");
}
public static void main(String a[]){
MySingleTon st = MySingleTon.getInstance();
st.getSomeThing();
}
}

10. Write a Java Program to Implement Factory and


AbstractFactory design pattern using java.

Step 1
Create an interface for Shapes.
Shape.java
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same
interface.
Rectangle.java
public class Rectangle implements Shape {
@ Override
public void draw() {
System .out.println("Inside Rectangle::draw() m
ethod.");
}
}
Square.java
public class Square implements Shape {
@ Override
public void draw() {
System .out.println("Inside Square::draw() m
ethod.");
}
}
Circle.java
public class Circle implements Shape {
@ Override
public void draw() {
System .out.println("Inside Circle::draw() m ethod.");
}
}
Step 3
Create an interface for Colors.
Color.java
public interface Color {
void fill();
}
Step4
Create concrete classes implementing the same
interface.
Red.java
public class Red implements Color {
@ Override
public void fill() {
System .out.println("Inside Red::fill() m ethod.");
}
}
Green.java
public class Green implements Color {
@ Override
public void fill() {
System .out.println("Inside Green::fill() m ethod.");
}
}
Blue.java
public class Blue implements Color {
@ Override
public void fill() {
System .out.println("Inside Blue::fill() m ethod.");
}
}
Step 5
Create an Abstract class to get factories for Color and
Shape Objects.
AbstractFactory.java
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape) ;
}
Step 6
Create Factory classes extending AbstractFactory to
generate object of concrete class based on
given information.
ShapeFactory.java
public class ShapeFactory extends AbstractFactory {
@ Override
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
@ Override
Color getColor(String color) {
return null;
}
}
ColorFactory.java
public class ColorFactory extends AbstractFactory {
@ Override
public Shape getShape(String shapeType){
return null;
}
@ Override
Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
}else if(color.equalsIgnoreCase("GREEN")){
return new Green();
}else if(color.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
}
}
Step 7
Create a Factory generator/producer class to get
factories by passing an information such as
Shape or Color
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory getFactory(String
choice){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
}else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
Step 8
Use the FactoryProducer to get AbstractFactory in
order to get factories of concrete classes by
passing an information such as type.
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDem o {
public static void m ain(String[] args) {
//get shape factory
AbstractFactory shapeFactory =
FactoryProducer.getFactory("SHAPE");
//get an object of Shape Circle
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw m ethod of Shape Circle
shape1.draw();
//get an object of Shape Rectangle
Shape shape2 =
shapeFactory.getShape("RECTANGLE");
//call draw m ethod of Shape Rectangle
shape2.draw();
//get an object of Shape Square
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw m ethod of Shape Square
shape3.draw();
//get color factory
AbstractFactory colorFactory =
FactoryProducer.getFactory("COLOR");
//get an object of Color Red
Color color1 = colorFactory.getColor("RED");
//call fill m ethod of Red
color1.fill();
//get an object of Color Green
Color color2 = colorFactory.getColor("Green");
//call fill m ethod of Green
color2.fill();
//get an object of Color Blue
Color color3 = colorFactory.getColor("BLUE");
//call fill m ethod of Color Blue
color3.fill();
}
}
Step 9
Verify the output.
Inside Circle::draw() m ethod.
Inside Rectangle::draw() m ethod.
Inside Square::draw() m ethod.
Inside Red::fill() m ethod.
Inside Green::fill() m ethod.
Inside Blue::fill() m ethod.

11. Write a Java Program to Implement Observer


Design pattern method using java.
Step 1
Create Subject class.
Subject.java
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers = new
ArrayList<Observer>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyAllObservers();
}public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
Step 2
Create Observer class.
Observer.java
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Binary String: " +
Integer.toBinaryString( subject.getState() )
);
}
}
OctalObserver.java
public class OctalObserver extends Observer{
public OctalObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Octal String: " +
Integer.toOctalString( subject.getState() ) );
}
}
HexaObserver.java
public class HexaObserver extends Observer{
public HexaObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}@Override
public void update() {
System.out.println( "Hex String: " +
Integer.toHexString( subject.getState()
).toUpperCase() );
}
}
Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
System.out.println("First state change: 15");
subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}
Step 5
Verify the output.
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010

12. Write a Java Program to Implement Adapter


design design pattern using java

Step 1
Create interfaces for Media Player and Advanced
Media Player.
MediaPlayer.javapublic interface MediaPlayer {
public void play(String audioType, String fileName);
}
AdvancedMediaPlayer.java
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
Step 2
Create concrete classes implementing the
AdvancedMediaPlayer interface.
VlcPlayer.java
public class VlcPlayer implements
AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file. Name: "+
fileName);
}
@Override
public void playMp4(String fileName) {
//do nothing
}
}
Mp4Player.java
public class Mp4Player implements
AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: "+
fileName);
}
}
Step 3
Create adapter class implementing the MediaPlayer
interface.
MediaAdapter.java
public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase("vlc") ){
advancedMusicPlayer = new VlcPlayer();
}else if (audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName)
{if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}
else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
Step 4
Create concrete class implementing the MediaPlayer
interface.
AudioPlayer.java
public class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
//inbuilt support to play mp3 music files
if(audioType.equalsIgnoreCase("mp3")){
System.out.println("Playing mp3 file. Name: " +
fileName);
}
//mediaAdapter is providing support to play other file
formats
else if(audioType.equalsIgnoreCase("vlc") ||
audioType.equalsIgnoreCase("mp4")){
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.play(audioType, fileName);
}
else{
System.out.println("Invalid media. " + audioType + "
format not supported");
}
}
}
Step 5
Use the AudioPlayer to play different types of audio
formats.
AdapterPatternDemo.java
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
audioPlayer.play("avi", "mind me.avi");
}
}
Step 6
Output.
Playing mp3 file. Name: beyond the horizon.mp3
Playing mp4 file. Name: alone.mp4
Playing vlc file. Name: far far away.vlc
Invalid media. avi format not supported

13. Write a Java Program to Implement proxydesign


pattern using java

Step 1
Create an interface.
Image.java
public interface Image {
void display();
}
Step 2
Create concrete classes implementing the same
interface.
RealImage.java
public class RealImage implements Image {
private String fileName;
public RealImage(String fileName){
this.fileName = fileName;
loadFromDisk(fileName);
}
@Override
public void display() {
System.out.println("Displaying " + fileName);
}private void loadFromDisk(String fileName){
System.out.println("Loading " + fileName);
}
}
ProxyImage.java
public class ProxyImage implements Image{
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName){
this.fileName = fileName;
}
@Override
public void display() {
if(realImage == null){
realImage = new RealImage(fileName);
}
realImage.display();
}
}
Step 3
Use the ProxyImage to get object of RealImage class
when required.
ProxyPatternDemo.java
public class ProxyPatternDemo {
public static void main(String[] args) {
Image image = new ProxyImage("test_10mb.jpg");
//image will be loaded from disk
image.display();
System.out.println("");
//image will not be loaded from disk
image.display();
}
}
Step 4
Output:
Loading test_10mb.jpg
Displaying test_10mb.jpg
Displaying test_10mb.jpg

Or any jpg files we can use .

14. Write a Java Program to Implement HelloWorld


program using servlets.

// Import required java libraries


import java.io.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
// do nothing.
}

Output:
Open the file HelloWorld.jsp in browser
Apache Tomcat Server should be up and running .
HelloWorld is the message printed in web page
15. Write a JSP Program using Expression, Scriplet
and Directive.

Client-side html file


<html>
<body>
<font color="blue" >
<h2>Using Scriptlet, Expression, Declaration in one
Example</h2>
</font> <h3>
<form method="get"
action="http://localhost:8080/ThreeInOne.jsp">

Enter User Name <input type="text" name="t1">


<br>
Enter First Number <input type="text" name="t2"
value="enter integer value"> <br>
Enter Second Number <input type="text"
name="t3" value="enter integer value"> <br>
<input type="submit" value="SEND">
</form> </h3>
</body>
</html>

Server side jsp file.

<body>
<%! String str;
int fn, sn, product;
%>
<%!
String stdUser = "Rao"; %>
<% str = request.getParameter("t1");
String str1 = request.getParameter("t2");
String str2 = request.getParameter("t3");
fn = Integer.parseInt(str1);
sn = Integer.parseInt(str2);
product = fn * sn;
%>
<%

out.println("Accessing global variables from


scriptlet:<br>");
if(str.endsWith(stdUser))
out.println("<b>Product of " + fn + " and " + sn + "
is " + product + "</b>");
else
out.println("<b>You are not eligible to get product
as your login failed</b>");
%>
<hr>
Accessing global variables from
Expression<br>
Your first number: <%= fn %>. <br>
Your Second number: <%= sn %>. <br>
Their product: <%= product %>. <br>
</body>

You might also like