Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
LAB MANUAL
A Helpful Hand
CSEROCKZ
OOP Concepts:
The object oriented paradigm is built on the foundation laid by the structured
programming concepts. The fundamental change in OOP is that a program is
designed around the data being operated upon rather upon the operations
themselves. Data and its functions are encapsulated into a single entity.OOP
facilitates creating reusable code that can eventually save a lot of work. A feature
called polymorphism permits to create multiple definitions for operators and
functions. Another feature called inheritance permits to derive new classes from
old ones. OOP introduces many new ideas and involves a different approach to
programming than the procedural programming.
Object:
Objects are the basic run time entities in an object-oriented system.
thy may represent a person, a place, a bank account, a table of data or any
item that the program has to handle.
Class:
The entire set of data and code of an object can be made of a user defined
data type with the help of a class.
I fact, Objects are variables of the type class.
Once a class has been defined, we can create any number of objects
belonging to that class
A class is thus a collection of objects of similar type.
for example: mango, apple, and orange are members of the class fruit.
ex: fruit mango; will create an object mango belonging to the class
fruit.
This insulation of the data from direct access by the program is called data
hiding.
Abstraction :
Abstraction referes to the act of representing essential features without
including the background details or explanations.
since the classes use the concept of data abstraction ,thy are known as
abstraction data type(ADT).
Inheritance :
Inheritance is the process by which objects of one class acquire the
properties of objects of another class. Inheritance supports the concept of
hierarchical classification.
for example:
Bird
Attributes:
Feathers
Lay eggs
Attributes: Attributes:
----------- -----------
---------- -----------
Robin Swallow
Penguin Kiwi
Attributes: Attributes:
_________ _________ Attributes: Attributes:
_________ _________
The bird 'robin ' is a part of the class 'flying bird' which is agian a part of the
class 'bird'. The concept of inheritance provide the idea of reusability.
POLYMORPHISM:
Polymorphism is another important oop concept. Polymorphism means the
ability to take more than one form. an operation may exhibit different instances.
The behavior depends upon the types of data used in the operation.
The process of making an operator to exhibit different behaviors in different
instance is known as operator overloading.
Polymorphism plays an important role in allowing objects having different
internal structures to share the same external interface. Polymorphism is
extensively used if implementing inheritance.
© Copyright cserockz08, 2009 www.cserockz.com Page
5
Object Oriented Programming
LAB MANUAL
Shape
Draw()
Java History:
C++
C Java
Text Editor
Javac
Java
progra
m
Output
The way these tools are applied to build and run application programs is create a
program. We need create a source code file using a text editor. The source code is
then compiled using the java compiler javac and executed using the java interpreter
java. The java debugger jdb is used to find errors. A complied java program can be
converted into a source code.
1. Write a Java program that prints all real solutions to the quadratic equation
ax2+bx+c = 0. Read in a, b, c and use the quadratic formula. If the discriminant
b2-4ac is negative, display a message stating that there are no real solutions.
2. The Fibonacci sequence is defined by the following rule. The first 2 values in
the sequence are 1, 1. Every subsequent value is the sum of the 2 values
preceding it. Write a Java program that uses both recursive and non-recursive
functions to print the nth value of the Fibonacci sequence.
3. WAJP that prompts the user for an integer and then prints out all the prime
numbers up to that Integer.
4. WAJP that checks whether a given string is a palindrome or not. Ex: MADAM
is a palindrome.
7. WAJP that reads a line of integers and then displays each integer and the sum of
all integers. (use StringTokenizer class)
8. WAJP that reads on file name from the user, then displays information about
whether the file exists, whether the file is readable, whether the file is writable,
the type of file and the length of the file in bytes.
9. WAJP that reads a file and displays the file on the screen, with a line number
before each line.
© Copyright cserockz08, 2009 www.cserockz.com Page
9
Object Oriented Programming
LAB MANUAL
10.WAJP that displays the number of characters, lines and words in a text.
11.WAJP that:
(a) Implements a Stack ADT
(b) Converts Infix expression to Postfix expression
(c) Evaluates a Postfix expression
13.Write an Applet that computes the payment of a loan based on the amount of
the loan, the interest rate and the number of months. It takes one parameter
from the browser: Monthly rate; if true, the interest rate is per month, otherwise
the interest rate is annual.
14.WAJP that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the + - x / % operations. Add a text field to display the
result.
18.WAJP that lets users create Pie charts. Design your own user interface (with
Swings & AWT).
20.WAJP that implements a simple client/server application. The client sends data
to a server. The server receives the data, uses it to produce a result and then
sends the result back to the client. The client displays the result on the console.
For ex: The data sent from the client is the radius of a circle and the result
produced by the server is the area of the circle.
22.WAJP to generate a set of random numbers. Find its sum and average. The
program should also display ‘*’ based on the random numbers generated.
23.WAJP to create an abstract class named Shape, that contains an empty method
named numberOfSides(). Provide three classes named Trapezoid, Triangle and
Hexagon, such that each one of the classes contains only the method
numberOfSides(), that contains the number of sides in the given geometrical
figure.
25.WAJP that creates 3 threads by extending Thread class. First thread displays
“Good Morning” every 1 sec, the second thread displays “Hello” every 2
seconds and the third displays “Welcome” every 3 seconds. (Repeat the same
by implementing Runnable)
type of Rodent. Create an array of Rodent, fill it with different specific types of
Rodents and call your base class methods.
Program Statement :
Write a Java program that prints all real solutions to the quadratic equation
ax2+bx+c = 0. Read in a, b, c and use the quadratic formula. If the discriminant
b2-4ac is negative, display a message stating that there are no real solutions.
Program :
import java.io.*;
class Quadratic
{
public static void main(String args[])throws IOException
{
double x1,x2,disc,a,b,c;
a=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
c=Double.parseDouble(br.readLine());
disc=(b*b)-(4*a*c);
if(disc==0)
{
System.out.println("roots are real and equal ");
x1=x2=-b/(2*a);
else if(disc>0)
{
System.out.println("roots are real and unequal");
© Copyright cserockz08, 2009 www.cserockz.com Page
13
Object Oriented Programming
LAB MANUAL
x1=(-b+Math.sqrt(disc))/(2*a);
x2=(-b+Math.sqrt(disc))/(2*a);
else
{
System.out.println("roots are imaginary");
}
}
}
Program Statement :
The Fibonacci sequence is defined by the following rule. The first 2 values in the
sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it.
Write a Java program that uses both recursive and non-recursive functions to print
the nth value of the Fibonacci sequence.
Program :
/* Recursive Solution*/
import java.io.*;
import java.lang.*;
class Demo {
int fib(int n) {
if(n==1)
return (1);
else if(n==2)
return (1);
else
return (fib(n-1)+fib(n-2));
}
}
class RecFibDemo {
public static void main(String args[])throws IOException {
Program Statement :
WAJP that prompts the user for an integer and then prints out all the prime
numbers up to that Integer.
Program :
Import java.util.*
class Test {
void check(int num) {
System.out.println ("Prime numbers up to "+num+" are:");
class Prime {
public static void main(String args[ ]) {
}
}
Program Statement :
WAJP that checks whether a given string is a palindrome or not. Ex: MADAM is a
palindrome.
Program :
import java.io.*;
class Palind {
public static void main(String args[ ])throws IOException {
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the string to check for palindrome:");
String s1=br.readLine();
if(s1.equals(s2))
System.out.println("palindrome");
else
System.out.println("not palindrome");
}
}
Program Statement :
Program :
import java.io.*;
class Test {
int len,i,j;
String arr[ ];
Test(int n) {
len=n;
arr=new String[n];
}
class Ascend {
public static void main(String args[ ])throws IOException {
Test obj1=new Test(4);
obj1.getArray();
obj1.check();
obj1.display();
}
}
Program Statement :
Program :
import java.util.*;
class Test {
int r1,c1,r2,c2;
class MatrixMul {
public static void main(String args[ ])throws IOException {
Test obj1=new Test(2,3,3,2);
Test obj2=new Test(2,3,3,2);
System.out.println("MATRIX-1:");
x=obj1.getArray(2,3); //to get the matrix from user
System.out.println("MATRIX-2:");
y=obj2.getArray(3,2);
Program Statement :
WAJP that reads a line of integers and then displays each integer and the sum of all
integers. (use StringTokenizer class)
Program :
class tokendemo {
public static void main(String args[ ]) {
String s="10,20,30,40,50";
int sum=0;
StringTokenizer a=new StringTokenizer(s,",",false);
System.out.println("integers are ");
while(a.hasMoreTokens()) {
int b=Integer.parseInt(a.nextToken());
sum=sum+b;
System.out.println(" "+b);
}
System.out.println("sum of integers is "+sum);
}
}
class Arguments {
public static void main(String args[ ]) {
int sum=0;
int n=args.length;
System.out.println("length is "+n);
Program Statement :
WAJP that reads on file name from the user, then displays information about
whether the file exists, whether the file is readable, wheteher the file is writable,
the type of file and the length of the file in bytes.
Program :
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
Program Statement :
WAJP that reads a file and displays the file on the screen, with a line number
before each line.
Program :
import java.io.*;
class LineNum{
public static void main(String args[]){
String thisline;
for(int i=0;i<args.length;i++)
{
try{
LineNumberReader br=new LineNumberReader(new
FileReader(args[i]));
while((thisline=br.readLine())!=null)
{
System.out.println(br.getLineNumber()+"."+thisline);
}
}catch(IOException e){
System.out.println("error:"+e);
}
}
}
}
Program Statement :
WAJP that displays the number of characters, lines and words in a text file.
Program :
import java.io.*;
public class FileStat {
public static void main(String args[ ])throws IOException {
long nl=0,nw=0,nc=0;
String line;
BufferedReader br=new BufferedReader(new FileReader(args[0]));
while ((line=br.readLine())!=null) {
nl++;
nc=nc+line.length();
int i=0;
boolean pspace=true;
while (i<line.length()) {
char c=line.charAt(i++);
boolean cspace=Character.isWhitespace(c);
if (pspace&&!cspace)
nw++;
pspace=cspace;
}
}
System.out.println("Number of Characters"+nc);
System.out.println("Number of Characters"+nw);
System.out.println("Number of Characters"+nl);
}}
while ((line=br.readLine())!=null) {
nl++;
nc=nc+line.length();
StringTokenizer st = new StringTokenizer(line);
nw += st.countTokens();
}
System.out.println("Number of Characters"+nc);
System.out.println("Number of Characters"+nw);
System.out.println("Number of Characters"+nl);
}}
Program Statement :
WAJP that:
(a) Implements a Stack ADT
(b) Converts Infix expression to Postfix expression
(c) Evaluates a Postfix expression
Program :
import java.io.*;
interface stack
{
void push(int item);
int pop();
}
class Stackimpl
{
private int stck[];
private int top;
Stackimpl(int size)
{
stck=new int[size];
top=-1;
}
else
stck[++top]=item;
}
int pop()
{
if(top==-1)
{
System.out.println("stack is empty deletion is not possible");
return 0;
}
else
return stck[top--];
}
}
class Stackdemo
{
a=new int[n];
for(int i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
obj1.push(a[i]);
}
}
Program Statement :
Program :
import java.awt.*;
import java.applet.*;
/*
<applet code = “HelloJava” width = 200 height = 60 >
</applet>
*/
Program Statement :
Write an Applet that computes the payment of a loan based on the amount of the
loan, the interest rate and the number of months. It takes one parameter from the
browser: Monthly rate; if true, the interest rate is per month, otherwise the interest
rate is annual.
Program :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
add(amt_l);
add(amt_t);
add(rate_l);
add(rate_t);
add(period_l);
add(period_t);
add(compute);
amt_t.setText("0");
rate_t.setText("0");
period_t.setText("0");
monthlyRate = Boolean.valueOf(getParameter("monthlyRate"));
amt_t.addActionListener(this);
rate_t.addActionListener(this);
period_t.addActionListener(this);
compute.addActionListener(this);
}
g.drawString("Input the Loan Amt, Rate and Period in each box and
press Compute", 50,100);
try {
amt_s = amt_t.getText();
amt = Double.parseDouble(amt_s);
rate_s = rate_t.getText();
rate = Double.parseDouble(rate_s);
period_s = period_t.getText();
period = Double.parseDouble(period_s);
}
catch (Exception e) { }
if (monthlyRate)
payment = amt * period * rate * 12 / 100;
else
payment = amt * period * rate / 100;
payment_s = String.valueOf(payment);
© Copyright cserockz08, 2009 www.cserockz.com Page
43
Object Oriented Programming
LAB MANUAL
Program Statement :
WAJP that works as a simple calculator. Use a grid layout to arrange buttons for
the digits and for the + - x / % operations. Add atext field to display the result.
Program :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet {
public void init() {
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}
public CalculatorPanel() {
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));
n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);
n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);
n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
© Copyright cserockz08, 2009 www.cserockz.com Page
46
Object Oriented Programming
LAB MANUAL
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);
dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==n1) assign("1");
else if(ae.getSource()==n2) assign("2");
else if(ae.getSource()==n3) assign("3");
else if(ae.getSource()==n4) assign("4");
else if(ae.getSource()==n5) assign("5");
else if(ae.getSource()==n6) assign("6");
else if(ae.getSource()==n7) assign("7");
else if(ae.getSource()==n8) assign("8");
else if(ae.getSource()==n9) assign("9");
else if(ae.getSource()==n0) assign("0");
else if(ae.getSource()==dot)
{
© Copyright cserockz08, 2009 www.cserockz.com Page
47
Object Oriented Programming
LAB MANUAL
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
© Copyright cserockz08, 2009 www.cserockz.com Page
48
Object Oriented Programming
LAB MANUAL
lastCommand="+";
result.setText("0");
}
}
}
Input & Output :
Program Statement :
Program :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
Program Statement :
Program :
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
Program Statement :
Program :
class Q {
int n;
boolean valueSet = false;
System.out.println(“Got: “ + n);
valueSet = false;
notify();
return n;
}
this.n = n;
valueSet = true;
System.out.println(“Put: “ + n);
notify();
}
}
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, “Producer”).start();
}
while(true) {
q.put(i++);
}
}
}
Consumer(Q q) {
this.q = q;
new Thread(this, “Consumer”).start();
}
class PC {
public static void main (String args[ ]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
Program Statement :
WAJP that lets users create Pie charts. Design your own user interface (with
Swings & AWT).
Program :
import java.awt.*;
import java.applet.*;
g.setColor(Color.blue);
g.fillOval(50,50,150,150);
g.setColor(Color.white);
g.drawString("40%",130,160);
g.setColor(Color.magenta);
g.fillArc(50,50,150,150,0,90);
g.setColor(Color.white);
g.drawString("25%",140,100);
g.setColor(Color.yellow);
g.fillArc(50,50,150,150,90,120);
g.setColor(Color.black);
g.drawString("35%",90,100);
g.setColor(Color.yellow);
g.fillOval(250,50,150,150);
g.setColor(Color.black);
g.drawString("15%",350,150);
g.setColor(Color.magenta);
g.fillArc(250,50,150,150,0,30);
g.setColor(Color.black);
g.drawString("5%",360,120);
g.setColor(Color.blue);
g.fillArc(250,50,150,150,30,120);
g.setColor(Color.white);
g.drawString("30%",330,100);
g.setColor(Color.black);
g.fillArc(250,50,150,150,120,180);
g.setColor(Color.white);
g.drawString("50%",280,160);
}
}
Program Statement :
WAJP that allows user to draw lines, rectangles and ovals.
Program :
import javax.swing.*;
import java.awt.Graphics;
case 2:{
for(i=1;i<=10;i++)
{
g.drawRect(10*i,10*i,50+10*i,50+10*i);
}
break;
}
case 3:{
for(i=1;i<=10;i++)
{
g.drawOval(10*i,10*i,50+10*i,50+10*i);
}
break;
}}}}
Program Statement :
WAJP that implements a simple client/server application. The client sends data to a
server. The server receives the data, uses it to produce a result and then sends the
result back to the client. The client displays the result on the console. For ex: The
data sent from the client is the radius of a circle and the result produced by the
server is the area of the circle.
Program :
// Server Program
import java.io.*;
import java.net.*;
import java.util.*;
// comput area
double area = radius * radius *Math.PI;
// Client Program
import java.io.*;
import java.net.*;
import java.util.*;
Program Statement :
Program :
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
Program Statement :
WAJP to generate a set of random numbers. Find its sum and average. The
program should also display ‘*’ based on the random numbers generated.
Program :
import java.util.*;
class RandNum {
public static void main(String ax[ ]) {
int a[ ]=new int[5];
int sum=0;
Random r=new Random();
for (int i=0;i<5;i++) {
a[i]=r.nextInt(10);
System.out.print(a[i]);
for(int y=0;y<a[i];y++)
System.out.print(" *");
System.out.println("");
}
for(int i=0;i<5;i++)
sum=sum+a[i];
System.out.println("Sum="+sum);
System.out.println("Avg="+(double)sum/a.length);
}
}
Program Statement :
WAJP to create an abstract class named Shape, that contains an empty method
named numberOfSides(). Provide three classes named Trapezoid, Triangle and
Hexagon, such that each one of the classes contains only the method
numberOfSides(), that contains the number of sides in the given geometrical
figure.
Program :
Program Statement :
WAJP to implement a Queue, using user defined Exception Handling (also make
use of throw, throws).
Program :
import java.util.Scanner;
class Queue {
int front,rear;
int q[ ]=new int[10];
Queue() {
rear=-1;
front=-1;
}
if (front==rear)
front=rear=-1;
else
front++;
return(temp);
}
}
class UseQueue {
public static void main(String args[ ]) {
Queue a=new Queue();
try {
a.enqueue(5);
a.enqueue(20);
} catch (ExcQueue e) {
System.out.println(e.getMessage());
}
try {
System.out.println(a.dequeue());
System.out.println(a.dequeue());
System.out.println(a.dequeue());
} catch(ExcQueue e) {
System.out.println(e.getMessage());
}
}
}
Program Statement :
WAJP that creates 3 threads by extending Thread class. First thread displays
“Good Morning” every 1 sec, the second thread displays “Hello” every 2 seconds
and the third displays “Welcome” every 3 seconds. (Repeat the same by
implementing Runnable)
Program :
}catch(InterruptedException e){}
System.out.println("Welcome");
}
}
}
class MyThread {
public static void main(String args[ ]) {
Thread t = new Thread();
One obj1=new One();
Two obj2=new Two();
Three obj3=new Three();
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
Thread t3=new Thread(obj3);
t1.start();
try{
t.sleep(1000);
}catch(InterruptedException e){}
t2.start();
try{
t.sleep(2000);
}catch(InterruptedException e){}
t3.start();
try{
t.sleep(3000);
}catch(InterruptedException e){}
}
}
One( ) {
new Thread(this, "One").start();
try{
© Copyright cserockz08, 2009 www.cserockz.com Page
80
Object Oriented Programming
LAB MANUAL
Thread.sleep(1000);
}catch(InterruptedException e){}
}
Two( ) {
new Thread(this, "Two").start();
try{
Thread.sleep(2000);
}catch(InterruptedException e){}
}
Three( ) {
new Thread(this, "Three").start();
try{
© Copyright cserockz08, 2009 www.cserockz.com Page
81
Object Oriented Programming
LAB MANUAL
Thread.sleep(3000);
}catch(InterruptedException e){}
}
class MyThread {
public static void main(String args[ ]) {
One obj1=new One();
Two obj2=new Two();
Three obj3=new Three();
}
}
Program Statement :
Program :
System.out.println("Result:"+sum);
}
}
// (b) 1 + 1/2 + 1/ 22 + 1/ 23 + … … + 1/ 2n
import java.util.Scanner;
class Series2 {
public static void main(String arg[ ]) {
int n;
double sum=0,i;
Scanner input= new Scanner(System.in);
System.out.println("enter value of n:");
n=input.nextInt();
for(i=1;i<=n;i++)
sum=sum+(double)(1/Math.pow(2,i-1));
System.out.println("Result:"+sum);
}
}
import java.util.*;
class Series3{
public static void main(String arg[ ]) {
int n,x;
double sum=0,i,d=1;
Scanner input= new Scanner(System.in);
System.out.println("enter value of n:");
n=input.nextInt();
System.out.println("enter value of x:");
x=input.nextInt();
for (i=1;i<=n;i++) {
sum=sum+(double)((Math.pow(x,i-1)/d));
d=d*i;
}
System.out.println("Result :"+sum);
}
© Copyright cserockz08, 2009 www.cserockz.com Page
86
Object Oriented Programming
LAB MANUAL
Program Statement :
Program :
import java.io.*;
class Ask {
public static void main(String a[ ])throws Exception {
String str1,str2;
int count=0;
str1="James Gosling";
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Who is the inventor of Java ?");
while(count!=3) {
str2=br.readLine();
if(str1.equalsIgnoreCase(str2)) {
System.out.println("!!! GOOD !!!");
break;
}
else {
if(count<2)
System.out.println("TRY AGAIN !");
count++;
}
}
if(count==3)
System.out.println("Correct Answer is : "+str1);
}
}
Program Statement :
Program :
class TransMatrix {
public static void main(string args[ ]) {
int i,j,k=0;
int rows,cols,r,c;
int a[ ][ ]={{1,2,3,4},{5,6,7,8}};
rows=a.length;
cols=a[0].length;
int b[ ][ ]=new int[rows*cols];
int s[ ]=new int[rows*cols];
int d[ ]=new int[rows*cols];
for (i=0;i<rows;i++)
for (j=0;j<cols;j++,k++)
s[k]=a[i][j];
i=j=k=r=c=0;
while(r<rows) {
while(c<cols) {
System.arraycopy(s,i,d,i,l);
b[j++][k]=d[i++];
c++;
}
j=c=0;
k++;
t++;
}
System.out.println("a matrix:");
for (i=0;i<rows;i++) {
for(j=0;j<cols;j++)
System.out.print(" "+a[i][j]);
System.out.println();
}
System.out.println("\nb matrix:");
for(i=0;i<cols;i++) {
for(j=0;j<rows;j++)
System.out.print(" "+b[i][j]);
System.out.println();
}
}
}
INPUT :
OUTPUT :
Program Statement :
Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster etc. In the base
class provide methods that are common to all Rodents and override these in the
derived classes to perform different behaviors, depending on the specific type of
Rodent. Create an array of Rodent, fill it with different specific types of Rodents
and call your base class methods.
Program :
import java.util.Random;
class Rodent{
void place() {}
void tail() {}
void eat() {}
public static Rodent randRodent(){
Random rr=new Random();
switch (rr.nextInt(4)) {
case 0: return new Mouse();
case 1: return new Gerbil ();
case 2: return new Hamster ();
case 3: return new Beaver ();
}
return new Rodent();
}
}
Program Statement :
Program :
import java.awt.*;
import java.applet.*;
PART-1
1. Why java is Secured Compare with other Language?
2. What if the main method is declared as private?
3. What if the static modifier is removed from the signature of the main
method?
4. What if I write static public void instead of public static void?
5. What if I do not provide the String array as the argument to the
method?
6. What is the first argument of the String array in main method?
7. If I do not provide any arguments on the command line, then the
String array of Main method will be empty or null?
8. What environment variables do I need to set on my machine in order
to be able to run Java programs?
9. Can an application have multiple classes having main method?
10.In how many Ways we can create a Object in java?
11.Every Application Should ve a main() Method under which class
does
the main() Method come Under?
12.What is Difference Between Static And Dynamic Polymarphism?
13.What happens If public Static void main() is made protected?
14.Can we Override the Main() Method?
15.What is the name of the java Complier used to compile the Source
File to byte code?
16.what is the use of static data member?
17.What does "wrapping" an object mean?
PART -2
1) What is a method? And What is OOPS?
2) What is the signature of a method?
3) What is the difference between an instance variable and a class
variable?
4) What is an abstract method?
5) What is an abstract class?
15) Several applet methods seem special, in that I need to define them
even if my own code doesn't invoke them--what are the methods, and
when (and by whom) are they invoked?
41) . I have several worker threads. I want my main thread to wait for
any of them to complete, and take action as soon as any of them
completes. I don't know which will complete soonest, so I can't just call
Thread.join on that one. How do I do it?
42) How do I do keyboard (interactive) I/O in Java?
43) . Is there a way to read a char from the keyboard without having to
type carriage-return?
44). How do I read a line of input at a time?
45) . How do I read input from the user (or send output) analogous to
using standard input and standard output in C or C++?
46) . Is there a standard way to read in int, long, float, and double values
from a string representation?
47) . How do I read a String/int/boolean/etc from the keyboard?
48) . I try to use "int i = System.in.read();" to read in an int from the
standard input stream. It doesn't work. Why?
49) . I use the following to read an int. It does not work. Why?
50). I'm trying to read in a character from a text file using the
DataInputStream's readChar() method. However, when I print it out, I
get?’s.
57) . Can I write objects to and read objects from a file or other
stream?
70) . How do I delete a directory in Java? 71). How do I tell how much
disk space is free in Java?
71) . How do I get a directory listing of the root directory C:\ on a PC?
72). I did a read from a Buffered stream, and I got fewer bytes than I
specified
73) . How do I redirect the System.err stream to a file?
74) . What are the values for the Unicode encoding schemes?
75) . How do I print from a Java program?
86) Why does the compiler complain about Interrupted Exception when
I try to use Thread's sleep method?
87) What is an exception?
88) I can't seem to change the value of an Integer object once created.
89) How can I safely store particular types in general containers?
90) Why is the String class final? I often want to override it.
116) Can I write objects to and read objects from a file or other stream?
117) Why do I see no output when I run a simple process, such as
r.exec("/usr/bin/ls")?
118) When do I need to flush an output stream?
119) How do I append data to a file?
120) How do I write data to a file?
© Copyright cserockz08, 2009 www.cserockz.com Page
107
Object Oriented Programming
LAB MANUAL
136) What are enumerators? and what are in-line functions? giv ans with
eg.
REFERENCES:
BOOKS:
WEBSITES:
1. www.java.com
2. www.java.sun.com
3. www.roseindia.net
4. www.javalobby.org
5. www.javabeat.net
STEP 1:
First install the java version (1.5/1.6) Ur having..!
STEP 2:
GO TO MY COMPUTER
1. Go to c:drive
2. In PROGRAM FILES
3. GO TO JAVA
4. GO to…jdk (1.5/1.6).0_01
5. Go to bin….
6. Go to lib….
STEP 3:
My computer---Properties
Properties---Advanced
Advanced---Environmental variables
Variable value:
C:\Program Files\Java\jdk1.6.0_01\lib\rt.jre;
EMAIL: cserockz08@gmail.com
srinivas30k@gmail.com
www.cserockz.com
© Copyright cserockz08, 2009 www.cserockz.com Page
125
Object Oriented Programming
LAB MANUAL