0% found this document useful (0 votes)
2 views111 pages

Advanced Java

The document contains multiple Java programming questions and their corresponding solutions, covering topics such as object counting, client-server communication using sockets, hierarchical inheritance, GUI event handling with AWT, multilevel inheritance, exception handling, threading, and JDBC connectivity for database operations. Each question includes code snippets and expected output to illustrate the concepts. The document serves as a comprehensive guide for Java programming practices and principles.

Uploaded by

Geetu Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views111 pages

Advanced Java

The document contains multiple Java programming questions and their corresponding solutions, covering topics such as object counting, client-server communication using sockets, hierarchical inheritance, GUI event handling with AWT, multilevel inheritance, exception handling, threading, and JDBC connectivity for database operations. Each question includes code snippets and expected output to illustrate the concepts. The document serves as a comprehensive guide for Java programming practices and principles.

Uploaded by

Geetu Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 111

Ques1.

Write a program to count total number of objects created


by the user.

import java.lang.*;
class Object
{
static int i=0;

Object()
{
i++;
}
public static void main(String args[])
{
Object o1 = new Object();
System.out.print("object created no. ="+i);
Object o2 = new Object();
System.out.print("object creted no. ="+i);
}
}
OUTPUT

object created no. =1


object created no. =2
Ques10. To create a client server communication in which you
have to show how to make communication to the server using
socket program.

Client.java

import java.net.*;
import java.io.*;
public class Client
{
public static void main(String[] args)
{
if(args.length != 2)
System.out.println("Usage : not done");
Else
{
String inp;
try
{
Socket sock = new
Socket(args[0],Integer.valueOf(args[1]).intValue());
DataInputStream is =new
DataInputStream(sock.getInputStream());

System.out.println("address :"+sock.getInetAddress());
System.out.println("port :"+sock.getPort());
System.out.println("Local
address :"+sock.getLocalAddress());
System.out.println("Local
port :"+sock.getLocalPort());
while((inp =is.readLine()) != null )
{
System.out.println(inp);
}
}
catch (UnknownHostException e)
{
System.out.println("Known Host:"+e.getMessage());
}
catch (IOException e)
{
System.out.println("error
IO:"+e.getMessage());
}
finally
{
System.out.println("end of program");
}

}
}
}
Server.java

import java.net.*;
import java.io.*;
import java.util.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(1111);
Socket sock1 = sock.accept();
System.out.println(sock1.toString());
System.out.println("address :"+sock1.getInetAddress());
System.out.println("ports :"+sock1.getPort());
DataOutputStream out = new
DataOutputStream(sock1.getOutputStream());

out.writeBytes("Welcome"+sock1.getInetAddress().getHostName()
+"We are"+new Date());
sock1.close();
sock.close();
}catch(IOException err) {
System.out.println(err.getMessage());
}
finally {
System.out.println("end of program");
}

}
OUTPUT

Server window

Socket[addr=/192.168.1.5,port=1153,localport=1111]
address :/192.168.1.5
ports :1153
end of program

Client window

address :abc/192.168.1.5
port :1111
Local address :/192.168.1.5
Local port :1156
WelcomeabcWe areFri Mar 20 13:14:11 IST 2009
end of program
Ques4. Write a program showing hierarchal inheritance

class Info
{
int pid;
char branch;
char year;

Info(int p,char ch,char y)


{
pid = p;
branch = ch;
year = y;
}

void display()
{
System.out.println("\nPID\t: "+pid);

System.out.print("Branch\t: ");
if(branch == 'i')
System.out.println("Information Technology");
if(branch =='e')
System.out.println("Electronics and Telecommunication");
if(branch =='c')
System.out.println("Computer Science");

System.out.print("Year\t: ");
if(year == 'f')
System.out.println("FE");
if(year == 's')
System.out.println("SE");
if(year == 't')
System.out.println("TE");
}
}

class Fe extends Info


{
int c;
int cpp;

Fe(int p,char ch,char y,int m1,int m2)


{
super(p,ch,y);
c = m1;
cpp = m2;
}

void fdisplay()
{
display();
System.out.println("Performance:");
System.out.println("\tC\t"+c);
System.out.println("\tC++\t"+cpp);
}
}

class Se extends Info


{
int vb;
int html;

Se(int p,char ch,char y,int m1,int m2)


{
super(p,ch,y);
vb = m1;
html= m2;
}

void sdisplay()
{
display();
System.out.println("Performance:");
System.out.println("\tVB\t"+vb);
System.out.println("\tHTML\t"+html);
}
}
class Te extends Info
{
int matlab;
int java;

Te(int p,char ch,char y,int m1,int m2)


{
super(p,ch,y);
matlab = m1;
java = m2;
}
void tdisplay()
{
display();
System.out.println("Performance:");
System.out.println("\tMATLAB\t"+matlab);
System.out.println("\tSJava\t"+java);
}
}

class Language
{
public static void main(String args[])
{
Fe F = new Fe(1074,'i','f',9,8);
Se S = new Se(1064,'e','s',6,8);
Te T = new Te(1054,'c','t',9,9);
F.fdisplay();
S.sdisplay();
T.tdisplay();
}
}
OUTPUT

PID : 1074
Branch : Information Technology
Year : FE
Performance:
C 9
C++ 8

PID : 1064
Branch : Electronics and Telecommunication
Year : SE
Performance:
VB 6
HTML 8

PID : 1054
Branch : Computer Science
Year : TE
Performance:
MATLAB 9
SJava 9
Ques9. Write a program to create GUI in which event handling is
done using AWT

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="MouseEvents" width=300 height=100>


</applet>
*/

public class MouseEvents extends Applet implements


MouseListener,MouseMotionListener
{
String msg="";
int mouseX=0,mouseY=0;

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
mouseX=0;
mouseY=10;
msg="Mouse clicked";
repaint( );
}

public void mouseEntered(MouseEvent me)


{
mouseX=0;
mouseY=10;
msg="Mouse entered";
repaint( );
}
public void mouseExited(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse exited";
repaint( );
}

public void mousePressed(MouseEvent me)


{
mouseX=me.getX( );
mouseY=me.getY( );
msg="Down";
repaint( );
}

public void mouseReleased(MouseEvent me)


{
mouseX=me.getX( );
mouseY=me.getY( );
msg="Up";
repaint( );
}

public void mouseDragged(MouseEvent me)


{
mouseX=me.getX( );
mouseY=me.getY( );
msg="*";
showStatus("Dragging mouse at " + mouseX + "," + mouseY);
repaint( );
}

public void mouseMoved(MouseEvent me)


{
showStatus("Moving mouse at " + me.getX() + "," +
me.getY());
}

public void paint(Graphics g)


{
g.drawString(msg,mouseX,mouseY);
}
}
OUTPUT
Ques8. Write a program to create applet window

import java.applet.*;
import java.awt.*;

public class DrawingLines extends Applet {

int width, height;

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( Color.white );
}

public void paint( Graphics g ) {


g.setColor( Color.red );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
}
}
}
OUTPUT
Ques6. Write a program to create a thread by implementing a
runnable interface

class MyRunnable implements Runnable{

private int a;

public MyRunnable(int a){

this.a = a;

public void run(){

for (int i = 1; i <= a; ++i){

System.out.println(Thread.currentThread().getName() + " is " +


i);

try{

Thread.sleep(1000);

catch (InterruptedException e){}

}
class MainMyThread{

public static void main(String args[]){

MyRunnable thr1, thr2;

thr1 = new MyRunnable(5);

thr2 = new MyRunnable(10);

Thread t1 = new Thread(thr1);

Thread t2 = new Thread(thr2);

t1.start();

t2.start();

}
OUTPUT

Thread-0 is 1
Thread-1 is 1
Thread-0 is 2
Thread-1 is 2
Thread-0 is 3
Thread-1 is 3
Thread-0 is 4
Thread-1 is 4
Thread-0 is 5
Thread-1 is 5
Thread-1 is 6
Thread-1 is 7
Thread-1 is 8
Thread-1 is 9
Thread-1 is 10
Ques3. Write a program related to multilevel inheritance

class Box {
private double width;

private double height;

private double depth;

Box(Box ob) { // pass object to constructor


width = ob.width;
height = ob.height;
depth = ob.depth;
}

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}

Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

Box(double len) {
width = height = depth = len;
}

double volume() {
return width * height * depth;
}
}

class BoxWeight extends Box {


double weight; // weight of box

BoxWeight(BoxWeight ob) { // pass object to constructor


super(ob);
weight = ob.weight;
}

BoxWeight(double w, double h, double d, double m) {


super(w, h, d); // call superclass constructor
weight = m;
}

BoxWeight() {
super();
weight = -1;
}

BoxWeight(double len, double m) {


super(len);
weight = m;
}
}

class Shipment extends BoxWeight {


double cost;

Shipment(Shipment ob) { // pass object to constructor


super(ob);
cost = ob.cost;
}

Shipment(double w, double h, double d, double m, double c) {


super(w, h, d, m); // call superclass constructor
cost = c;
}

Shipment() {
super();
cost = -1;
}

Shipment(double len, double m, double c) {


super(len, m);
cost = c;
}
}

class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);

double vol;

vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is " + shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();

vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is " + shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
OUTPUT

Volume of shipment1 is 3000.0


Weight of shipment1 is 10.0
Shipping cost: $3.41

Volume of shipment2 is 24.0


Weight of shipment2 is 0.76
Shipping cost: $1.28
Ques7. Write a program to handle all types of exceptions using try
and catch

import java.io.*;

public class exceptionHandle{


public static void main(String[] args) throws Exception{
try{
int a,b;
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage() + " is not a numeric value.");
System.exit(0);
}
}
}
OUTPUT

67
gf
For input string: "gf" is not a numeric value.
Ques5. Write a program to demonstrate threads using thread class

public class ThreeThreadsTest {


public static void main(String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
new SimpleThread("Bora Bora").start();
}
}

class SimpleThread extends Thread {


public SimpleThread(String str) {
super(str);
}

public void run() {


for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
System.out.println("DONE! " + getName());
}
}
OUTPUT

0 Jamaica
0 Fiji
0 Bora Bora
1 Fiji
2 Fiji
1 Jamaica
1 Bora Bora
2 Jamaica
3 Fiji
3 Jamaica
2 Bora Bora
3 Bora Bora
4 Fiji
4 Jamaica
5 Fiji
4 Bora Bora
5 Jamaica
6 Fiji
5 Bora Bora
6 Bora Bora
6 Jamaica
7 Fiji
7 Bora Bora
8 Fiji
9 Fiji
7 Jamaica
8 Bora Bora
DONE! Fiji
8 Jamaica
9 Bora Bora
9 Jamaica
DONE! Bora Bora
DONE! Jamaica
Ques11. Write a program to extract data from database using
JDBC connectivity

import java.sql.*;
public class AuthorsInfo {

public static void main(String[] args)


{
try
{
String str="select * from authors";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:MyData");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(str);
System.out.println("Author ID\tFirst Name\tLast
Name\tCity");
while(rs.next())
{
String id=rs.getString("ID");
String lname=rs.getString("au_lname");
String fname=rs.getString("au_fname");
String city=rs.getString("city");
System.out.print(id+"\t\t");
if(fname.length()<=7)
{
System.out.print(fname+"\t\t");
}
else
{
System.out.print(fname+"\t");
}
if(lname.length()<=7)
{
System.out.print(lname+"\t\t");
}
else
{
System.out.print(lname+"\t");
}
System.out.println(city+"\t");
}
con.close();
}
catch(Exception e)
{
System.out.println("Eror occured");
System.out.println("Error: "+e);
}
}

}
Table made to fetch data from “authors”

authors
ID au_fname au_lname city
4 Marie Green Oakland
5 Dean Straight Greenland
6 Livia Karsen Roorkie
7 JK Copper New York
8 Dirk Stringer Oakland
OUTPUT

Author ID First Name Last Name City


4 Marie Green Oakland
5 Dean Straight Greenland
6 Livia Karsen Roorkie
7 JK Copper New York
8 Dirk Stringer Oakland
Ques13. Write a program to display information about the resultset
using metadata classes

import java.sql.*;
public class ColumnInfo {
public static void main(String[] args)
{
try
{
String str="select * from authors";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:MyData");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(str);
ResultSetMetaData rsmd=rs.getMetaData();
rs.next();
System.out.println("Numbers of attributes in the authors
table: "+rsmd.getColumnCount());
System.out.println("");
System.out.println("--------------------------------");
System.out.println("Attributes of the authors table");
System.out.println("--------------------------------");
for(int i=1;i<=rsmd.getColumnCount();i++)
{
System.out.println(rsmd.getColumnName(i)+" :
"+rsmd.getColumnTypeName(i));
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println("Error : "+e);
}
}

}
OUTPUT

Numbers of attributes in the authors table: 4

--------------------------------
Attributes of the authors table
--------------------------------
ID : COUNTER
au_fname : VARCHAR
au_lname : VARCHAR
city : VARCHAR
Ques2. Write a program to store width, height and depth of a room

import java.io.*;
import java.util.*;
public class Room {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the width of a room");
int w=sc.nextInt();
System.out.println("Enter the height of a room");
int h=sc.nextInt();
System.out.println("Enter the depth of a room");
int d=sc.nextInt();
int volume=w*h*d;
System.out.println("Volume of a room : "+volume);
}
}
OUTPUT

Enter the width of a room


56
Enter the height of a room
47
Enter the depth of a room
69
Volume of a room : 181608
Ques12. Write a program to insert data into a table using prepared
statements through GUI

import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
//<applet code=DataInApp.class width="500" height="200"> </applet>
public class DataInApp extends JApplet
{
JPanel p;
JLabel ls,lname,ladd,fname;
JTextField ts,tname,tadd,tfname;
JButton b;
public void init()
{
p=new JPanel();
ls=new JLabel("ID");
fname=new JLabel("First name");
lname=new JLabel("Last name");
ladd=new JLabel("City");

ts=new JTextField(10);
tfname=new JTextField(10);
tname=new JTextField(10);
tadd=new JTextField(10);

b=new JButton("Insert");

getContentPane().add(p);
p.add(ls);
p.add(ts);
p.add(fname);
p.add(tfname);
p.add(lname);
p.add(tname);
p.add(ladd);
p.add(tadd);
p.add(b);

EventHandle eobj=new EventHandle();

b.addActionListener(eobj);
}
class EventHandle implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:MyData");
PreparedStatement
s=con.prepareStatement("insert into authors values(?,?,?,?)");
s.setString(1,ts.getText());
s.setString(2,tfname.getText());
s.setString(3,tname.getText());
s.setString(4,tadd.getText());
s.executeUpdate();
getAppletContext().showStatus("done");
con.close();

con=DriverManager.getConnection("jdbc:odbc:MyData");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select *
from authors");
while(rs.next())
{
System.out.println(rs.getString(1)+"
"+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4));
}
con.close();
}
catch(Exception e)
{
getAppletContext().showStatus("Exception
"+ e);
}
}
}
}
Table before inserting was done

authors
ID au_fname au_lname city
1 Sarita Juneja America
2 Neha Jain Delhi
3 George Gunman Guhana
4 Marie Green Oakland
5 Dean Straight Greenland
6 Livia Karsen Roorkie
7 JK Copper New York
8 Dirk Stringer Oakland
9 Ruby Goel Madras
10 Shahnaz Hussain Mumbai
OUTPUT
Table after the insertion of an item

4 Marie Green Oakland


5 Dean Straight Greenland
6 Livia Karsen Roorkie
7 JK Copper New York
8 Dirk Stringer Oakland
3 George Gunman Guhana
2 Neha Jain Delhi
1 Sarita Juneja America
9 Ruby Goel Madras
10 Shahnaz Hussain Mumbai
11 Jacky Sheroff Dehradun
Submitted to: Submitted by:
Miss. Ayushi Neha Jain
05/I.T./4228
VIII Semester
S.NO PROGRAM T.SIGN
1 Write a program to count total number of
objects created by the user.
2 Write a program to store width, height and
depth of a room
3 Write a program related to multilevel
inheritance
4 Write a program related to hierarchical
inheritance
5 Write a program to demonstrate threads
using thread class
6 Write a program to create a thread by
implementing runnable interface
7 Write a program to handle all types of
exceptions using try and catch
8 Write a program to create applet window
9 Write a program to create GUI in which
event handling is done using AWT
10 To create a client server communication in
which you have to show how to make
communication to the server and how to
implement server using socket program
11 Write a program to extract data from
database using JDBC connectivity
12 Write a program to insert data into a table
using prepared statements through GUI
13 Write a program to display information
about the resultset using metadata classes
Ques14 Write a program to demonstrate string methods

public class StringDemo2


{
public static void main(String[] args)
{
String strob1="First String";
String strob2="Second String";
String strob3=strob1;
System.out.println("Length of strob1: "+strob1.length());
System.out.println("Char at index 3 in strob1:
"+strob1.charAt(3));
if(strob1.equals(strob2))
{
System.out.println("strob1 = = strob2");
}
else
{
System.out.println("strob1 != strob2");
}
if(strob1.equals(strob3))
{
System.out.println("strob1 = = strob3");
}
else
{
System.out.println("strob1 != strob3");
}
}

}
OUTPUT

Length of strob1: 12
Char at index 3 in strob1: s
strob1 != strob2
strob1 = = strob3
B) Write a program to bubble sort the string

public class SortString


{
static String
arr[]={"Now","is","the","time","for","all","good","men","to","come","to","t
he","aid","of","their","country"};
public static void main(String[] args)
{
for(int j=0;j<arr.length;j++)
{
for(int i=j+1;i<arr.length;i++)
{
if(arr[i].compareTo(arr[j])<0)
{
String t=arr[j];
arr[j]=arr[i];
arr[i]=t;
}
}
System.out.println(arr[j]);
}
}

}
OUTPUT

Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
C) Write a program to demonstrate use of indexof( ) and
lastindexof( )

public class indexofDemo


{
public static void main(String[] args)
{
String s="Now is the time for all the good men"+"to come to
the aid of their country.";
System.out.println(s);
System.out.println("indexof(t) = "+s.indexOf('t'));
System.out.println("lastIndexof(t) = "+s.lastIndexOf('t'));
System.out.println("indexof(the) = "+s.indexOf("the"));
System.out.println("lastIndexof(the) = "+s.lastIndexOf("the"));
System.out.println("indexof(t,10) = "+s.indexOf('t',10));
System.out.println("lastIndexof(t,60) = "+s.lastIndexOf('t',60));
System.out.println("indexof(the,10) = "+s.indexOf("the",10));
System.out.println("lastIndexof(the,60) =
"+s.lastIndexOf("the",60));
}

}
OUTPUT

Now is the time for all the good mento come to the aid of their country.
indexof(t) = 7
lastIndexof(t) = 68
indexof(the) = 7
lastIndexof(the) = 58
indexof(t,10) = 11
lastIndexof(t,60) = 58
indexof(the,10) = 24
lastIndexof(the,60) = 58
Ques15
A)Write a program to demonstrate use of if else statements

public class IfElse


{
public static void main(String[] args)
{
int month=4;
String season;
if(month==12||month==1||month==2)
{
season ="winter";
}
else if(month==4||month==3||month==5)
{
season ="Spring";
}
else if(month==6||month==7||month==8)
{
season ="Summer";
}
else if(month==11||month==10||month==9)
{
season ="Autumn";
}
else
{
season ="Bogus Month";
}
System.out.println("April is in the "+ season +".");
}

}
OUTPUT

April is in the Spring.


B) Write a program showing whether the number is prime or
not.

public class Prime


{
public static void main(String[] args)
{
int num;
boolean isPrime=true;
num=14;
for(int i=2;i<=num/2;i++)
{
if(num%i==0)
{
isPrime=false;
break;
}
}
if(isPrime)
{
System.out.println("Prime");
}
else
{
System.out.println("Not prime");
}
}

}
OUTPUT

Not prime
C) Write a program to demonstrate use of switch statements

public class SampleSwitch


{
public static void main(String[] args)
{
for(int i=0;i<6;i++)
{
switch(i)
{
case 0:
System.out.println("i is zero");
break;
case 1:
System.out.println("i is one");
break;
case 2:
System.out.println("i is two");
break;
case 3:
System.out.println("i is three");
break;
default:
System.out.println("i is greater than 3");
break;
}
}
}
}
OUTPUT

i is zero
i is one
i is two
i is three
i is greater than 3
i is greater than 3
D) Write a program to demonstrate use of while loop

public class While


{
public static void main(String[] args)
{
int n=10;
while(n>0)
{
System.out.println("tick "+n);
n--;
}
}

}
OUTPUT

tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
E) Write a program using do-while to process a menu selection

public class Menu


{
public static void main(String[] args) throws java.io.IOException
{
char choice;
do
{
System.out.println("Help on:");
System.out.println("1: if:");
System.out.println("2: switch:");
System.out.println("3: while:");
System.out.println("4: do-while:");
System.out.println("5: for: \n");
System.out.println("Choose one:");
choice=(char)System.in.read();
}
while(choice<'1'||choice>'5');
System.out.println("\n");
switch(choice)
{
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else staements;");
break;
case '2':
System.out.println("The Switch:\n");
System.out.println("switch(expression) {");
System.out.println(" Case contant:");
System.out.println(" Statement sequence");
System.out.println(" break;");
System.out.println(" //.....");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while(condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.println("for(init;condition;iteration)");
System.out.println("statement;");
break;
}
}
}
OUTPUT

Help on:
1: if:
2: switch:
3: while:
4: do-while:
5: for:

Choose one:
2

The Switch:

switch(expression) {
Case contant:
Statement sequence
break;
//.....
}
Ques16
A)Write a program to average an array of values

public class Average


{
public static void main(String[] args)
{
double nums[]={10.1,11.2,12.3,13.4,14.5};
double result=0;
int i;
for(i=0;i<5;i++)
{
result=result+nums[i];
}
System.out.println("Average is: "+result/5);
}
}
OUTPUT

Average is: 12.299999999999999


B) Write a program to demonstrate 2-D array

public class TwoDArray


{
public static void main(String[] args)
{
int twod[][]=new int[4][5];
int i,j,k=0;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
{
twod[i][j]=k;
k++;
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
System.out.print(twod[i][j]+" ");
System.out.println();
}
}
}
OUTPUT

01234
56789
10 11 12 13 14
15 16 17 18 19
Ques17
A)Write a program to demonstrate the basic arithmetic
operators

public class BasicMath


{
public static void main(String[] args)
{
System.out.println("Integer Arithmetic");
int a=1+1;
int b=a*3;
int c=b/4;
int d=c-a;
int e=-d;
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("c = "+c);
System.out.println("d = "+d);
System.out.println("e = "+e);
System.out.println("Floating point arithmetic");
double da=1+1;
double db=da*3;
double dc=db/4;
double dd=dc-da;
double de=-dd;
System.out.println("da = "+da);
System.out.println("db = "+db);
System.out.println("dc = "+dc);
System.out.println("dd = "+dd);
System.out.println("de = "+de);
}
}
OUTPUT

Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating point arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
B) Write a program to demonstrate the bitwise logical
operators

public class BitLogic


{
public static void main(String[] args)
{
String
binary[]={"0000","0001","0010","0011","0100","0101","0110","0111","100
0","1001","1010","1011","1100","1101","1110","1111"};
int a=3;
int b=6;
int c=a|b;
int d=a&b;
int e=a^b;
int f=(~a&b)|(a&~b);
int g=~a&0x0f;
System.out.println("a= "+binary[a]);
System.out.println("b= "+binary[b]);
System.out.println("c= "+binary[c]);
System.out.println("d= "+binary[d]);
System.out.println("e= "+binary[e]);
System.out.println("f= "+binary[f]);
System.out.println("g= "+binary[g]);
}

}
OUTPUT

a= 0011
b= 0110
c= 0111
d= 0010
e= 0101
f= 0101
g= 1100
C) Write a program to demonstrate use of ternary operator

public class Ternary


{
public static void main(String[] args)
{
int i,k;
i=10;
k=i<0?-i:i;
System.out.println("Absolute value of ");
System.out.println(i+" is "+k);
i=-10;
k=i<0?-i:i;
System.out.println("Absolute value of ");
System.out.println(i+" is "+k);
}
}
OUTPUT

Absolute value of
10 is 10
Absolute value of
-10 is 10
Ques18 Write a program to demonstrate method overriding

class A1
{
int i,j;
A1(int a,int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("i and j: "+i+" "+j);
}
}
class B1 extends A1
{
int k;
B1(int a,int b,int c)
{
super(a,b);
k=c;
}
void show()
{
System.out.println("k: "+k);
}
}
public class Override
{
public static void main(String[] args)
{
B1 ob=new B1(1,2,3);
ob.show();
}

}
OUTPUT

k: 3
Ques19 Write a program showing dynamic method dispatch

class C1
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class D extends C1
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class E extends C1
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
public class Dispatch
{
public static void main(String[] args)
{
C1 c=new C1();
D d=new D();
E e=new E();
C1 f;
f=c;
f.callme();
f=d;
f.callme();
f=e;
f.callme();
}
}
OUTPUT

Inside A's callme method


Inside A's callme method
Inside A's callme method
Ques20 Write a program showing use of parameterized
constructor

class Box2
{
double width,height,depth;
Box2(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
double volume()
{
return width*height*depth;
}
}
public class BoxDemo7
{
public static void main(String[] args)
{
Box2 a=new Box2(10,20,15);
Box2 b=new Box2(3,6,9);
double vol;
vol=a.volume( );
System.out.println("Volume is "+vol);
vol=b.volume( );
System.out.println("Volume is "+vol);
}
}
OUTPUT

Volume is 3000.0
Volume is 162.0
Ques21 Write a program to demonstrate method overloading

class OverloadDemo
{
void test()
{
System.out.println("No Parameters");
}
void test(int a)
{
System.out.println("a : "+a);
}
void test(int a,int b)
{
System.out.println("a and b : "+a+" "+b);
}
double test(double a)
{
System.out.println("a : "+a);
return a*a;
}
}
public class Overload
{
public static void main(String[] args)
{
OverloadDemo ob=new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10,20);
result=ob.test(123.25);
System.out.println("Result of ob.test(123.25) : "+result);
}

}
OUTPUT

No Parameters
a : 10
a and b : 10 20
a : 123.25
Result of ob.test(123.25) : 15190.5625
Ques22 Write a program to create a tiny editor

import java.io.*;
public class TinyEdit
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str[]=new String[100];
System.out.println("Enter lines of text");
System.out.println("Enter stop to quit");
for(int i=0;i<100;i++)
{
str[i]=br.readLine();
if(str[i].equals("stop"))
break;
}
System.out.println("\n Here is your file");
for(int i=0;i<100;i++)
{
if(str[i].equals("stop"))
break;
System.out.println(str[i]);
}
}
}
OUTPUT

Enter lines of text


Enter stop to quit
This is line 1.
This is line two.
Java makes working with string easy.
just create string objects
stop

Here is your file


This is line 1.
This is line two.
Java makes working with string easy.
just create string objects
Ques23
A)Write a program demonstrates use of packages

package p1;

public class Protection


{
String name;
double bal;
public Protection(String n,double b)
{
name=n;
bal=b;
}
public void show()
{
if(bal<0)
{
System.out.println("--> ");
}
System.out.println(name+": $"+bal);
}
}
import p1.*;
public class TestBalance
{
public static void main(String[] args)
{
Protection test=new Protection("J.J.Jaspers",99.88);
test.show();
}

}
OUTPUT

J.J.Jaspers: $99.88
B) Write a program to demonstrate use of interfaces

public interface IntStack


{
void push(int item);
int pop( );
}

class FixedStack implements IntStack


{
private int stck[];
private int tos;
FixedStack(int size)
{
stck=new int[size];
tos=-1;
}
public int pop()
{
if(tos<0)
{
System.out.println("Stack underflow");
return 0;
}
else
{
return stck[tos--];
}
}
public void push(int item)
{
if(tos==stck.length-1)
{
System.out.println("Stack is full");
}
else
{
stck[++tos]=item;
}
}
}
public class IFStack
{
public static void main(String[] args)
{
FixedStack mystack1=new FixedStack(5);
FixedStack mystack2=new FixedStack(8);
for(int i=0;i<5;i++)
mystack1.push(i);
for(int i=0;i<8;i++)
mystack2.push(i);
System.out.println("Stack in mystack1");
for(int i=0;i<5;i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2");
for(int i=0;i<8;i++)
System.out.println(mystack2.pop());
}

}
OUTPUT

Stack in mystack1
4
3
2
1
0
Stack in mystack2
7
6
5
4
3
2
1
0
Ques24 Write a program demonstrates remote method
invocation

myInter.java

import java.rmi.*;

public interface myInter extends Remote


{
int sum(int a,int b) throws RemoteException;
}
myClient.java

import java.rmi.*;
import java.rmi.server.*;

public class myClient


{
public static void main(String [] rags)
{
try
{
System.setSecurityManager(new RMISecurityManager());
myInter o=(myInter)Naming.lookup("rmi://localhost/server");
int ans=o.sum(23,32);
System.out.println("Ans from server "+ans);
}
catch(Exception e)
{
System.out.println("Exception at client "+e);
}
}
}
myServer.java

import java.rmi.*;
import java.rmi.server.*;

public class myServer extends UnicastRemoteObject implements myInter


{
public myServer() throws RemoteException
{
super();
}
public int sum(int a,int b) throws RemoteException
{
int ans=a+b;
return ans;
}
public static void main(String [] args)
{
try{
//System.setSecurityManager(new RMISecurityManager());
myServer s=new myServer();
Naming.rebind("server",s);
System.out.println("Server Registered");
}
catch(Exception e){
System.out.println("Exception at server "+e);
}
}
}
OUTPUT

C:>cd rmi
C:/rmi>policytool
C:/rmi>javac *.java
C:/rmi>start rmiregistry
C:/rmi>java myServer

Server registered

C:/rmi>java myClient
Ans from server 55
Ques25 Write a program demonstrating use of predefined
beans

C:>cd beans
C:/beans>cd beanbox
C:/beans/beanbox>run.bat
C:\beans\beanbox>if "Windows_NT" == "Windows_NT" setlocal

C:\beans\beanbox>set

CLASSPATH=classes;..\lib\methodtracer.jar;..\infobus.jar

C:\beans\beanbox>java sun.beanbox.BeanBoxFrame
14 A)Write a program to demonstrate string
methods
B) Write a program to bubble sort the string
C) Write a program to demonstrate use of
indexof( ) and lastindexof( )
15 A)Write a program to demonstrate use of if
else statements
B) Write a program showing whether the
number is prime or not.
C) Write a program to demonstrate use of
switch statements
D) Write a program to demonstrate use of
while loop
E) Write a program using do-while to
process a menu selection
16 A)Write a program to average an array of
values
B) Write a program to demonstrate 2-D array
17 A)Write a program to demonstrate the basic
arithmetic operators
B)Write a program to demonstrate the
bitwise logical operators
C)Write a program to demonstrate use of
ternary operator
18 Write a program to demonstrate method
overriding
19 Write a program showing dynamic method
dispatch
20 Write a program showing use of
parameterized constructor
21 Write a program to demonstrate method
overloading
22 Write a program to create a tiny editor
23 A)Write a program to demonstrate use of
packages
B)Write a program to demonstrate use of
interfaces
24 Write a program demonstrates remote
method invocation
25 Write a program demonstrating use of
predefined beans
26 Write a program demonstrating use of
userdefined beans
27 Write a program to show usage of JSP pages
28 Write a program to generate current date and
time with the use of JSP pages
Ques26 Write a program demonstrating use of user defined
beans
import javax.swing.*;
public class Logo1 extends JPanel
{
private String sname=" MY LOGO";
JLabel lname;
JTextField tname;
public Logo1()
{
lname=new JLabel(sname);
tname=new JTextField(10);
add(lname);
add(tname);
}
public void setSname(String str)
{
sname=str;
lname.setText(sname);
}
public String getSname()
{
return sname;
}
}
Now write the following code in the separate notepad and save it with .mft
extension

Name: Logo1.class
Java-Bean: true

Now create a jar file


Jar cfm Logo1.jar Logo1.mft Logo1.class

C:>cd beans
C:/beans>cd beanbox
C:/beans/beanbox>run.bat
C:\beans\beanbox>if "Windows_NT" == "Windows_NT" setlocal

C:\beans\beanbox>set

CLASSPATH=classes;..\lib\methodtracer.jar;..\infobus.jar

C:\beans\beanbox>java sun.beanbox.BeanBoxFrame
After execute run file we have following output

Now go to file menu-loadjar and load the Logo1.jar file


Now click on the Logo1 in the tool box and drag it to the Beanbox

Now go to property box and change the name of the label


Now write text in the text box
Ques27 Write a program to show usage of JSP pages

<html>
<head>
<title>
JSP Example
</title>
</head>
<body>
<h1> WELCOME<h1>
<% out.println(“hello”); %>
</body>
<html>
OUTPUT

WELCOME
Hello
Ques28 Write a program to generate current date and time
with the use of JSP pages

<html>
<h1>Welcome to JSP</h1>
<hr>server Time :
<% java.util.Date dt=new java.util.Date(); %>
<%=dt.getHours() %> : <%=dt.getMinutes() %> : <%=dt.getSeconds()%>
</html>
OUTPUT

Server time : Sun Apr 11 12:36:38 CDT 2009

You might also like