Next section covers basic concepts programs like quadratic equation, Fibonacci
series.
Next section covers how to implement stack ADT and to convert infix expression
into Postfix form.
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 fist two values in the
sequence are 1and 1. Every subsequent value is the run of the two values preceding it.
Write a Java program that uses both recursive and non recursive functions to print the nth
value in the Fibonacci sequence.
3. Write a Java program that prompts the user for an integer and then prints out all prime
numbers up to that Integer.
4. Write a Java program that checks whether a given string is a palindrome or not. Ex:
MADAM is a palindrome.
5. Write a Java program for sorting a given list of names in ascending order.
6. Write a Java program to multiply two given matrices.
7. Write a Java Program that reads a line of integers, and then displays each integers, and
the sum of all the integers (use stringTokenizer class)
8. Write a Java program 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. Write a Java program that reads a file and displays a file and displays the file on the
screen, with a line number before each line.
10. Write a Java program that displays the number of characters, lines and words in a text
file.
11. Write a Java program that:
a) Implements stack ADT. b) Converts infix expression into Postfix form.
12. Write an applet that displays a simple message.
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; Other wise the interest rate is annual.
14. Write a Java program 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.
15. Write a Java program for handling mouse events.
16. Write a Java program for creating multiple threads
17. Write a Java program that correctly implements producer consumer problem using
the concept of inter thread communication.
18. Write a Java program that lets users create Pie charts. Design your own user interface
(with swings& AWT)
19. Write a Java program that allows the user to draw lines, rectangles and OU.als.
Program:1
} // end class A
{
public static void main(String[] args)
{
A a=new A();
System.out.println( "The square of integer 7 is " + a.square( 7 ) + "\nThe
square of double 7.5 is " + a.square( 7.5 ) );
}
}
Sample Output:
// Fact.java
class Fact
{
private int x;
public fact(int n)
{
x=n;
}
public int calfac()
{
int f=1;
for(int i=x;i>0;i--)
{
f=f*i;
}
return f;
}
}
// Factorial.java
class Factorial
{
public static void main(String[] args)
{
Fact p=new Fact(5);
int res=p.calfac();
System.out.println("Factorial of "+p.x+" is "+res);
}
}
To execute the above program, the Fact.java should be compiled first as Factorial.java is
trying to create object of the above class.
When compiling the second module, the compiler will return an error as the private
variable of the class is not accessible beyond the class. In order to access the private
variable, the class should have a public method.
/** Class that has a constructor and two methods for calculating factorial
*/
class Fact
{
private int x;
/**
* Constructor to initialize
* @param n the number for which factorial is to be found
*/
public Fact(int n)
{
x=n;
}
/**
* Method to calculate the factorial
* @return f the factorial of the number
*/
public int calfac()
{
int f=1;
for(int i=x;i>0;i--)
{
f=f*i;
}
return f;
}
/**
* Method to display the result
* @param n the factorial
*/
public void print(int r)
{
System.out.println("Factorial of "+this.x+" is "+r);
}
/**
* The class that accesses the Fact class and creates an object
class Fact
{
public static void main(String[] args)
{
System.out.println(“ Execution: java Factorial [number]“);
int x= Integer.parseInt(args[0]);
Fact p=new Fact(x);
int res=p.calfac();
p.print(res);
}
}
Compilation:
C:\javac Fact.java
C:\javac Factorial.java
Interpretation:
C:\java Factorial 8
Sample Output:
Execution: java Factorial [number]
Factorial of 8 is 40320
Documentation:
C:\javadoc Fact.java
C:\javadoc Factorial.java
Class that has a constructor and two methods for calculating factorial
Constructor Summary
Fact(int n)
Constructor to initialize
Constructor Detail
Fact
public Fact(int n)
Constructor to initialize
Parameters:
n - the number for which factorial is to be found
Method Detail
calfac
public int calfac()
Method to calculate the factorial
Returns:
f the factorial of the number
class A
{
int a;
public A(int m)
{
a=m;
System.out.println("super class variable "+this.a);
}
}
class B extends A
{
double b;
public B(int m,double n)
{
super(m);
b=n;
System.out.println("sub class, variables"+this.b+" "+super.a);
}
}
class C extends B
{
char c;
public C2(int m, double n, char ch)
{
super(m,n);
c=ch;
System.out.println("sub-sub class, variables "+this.c+"
"+super.b+""+super.a);
}
}
Note:
class Array
{
public static void main(String[] args)
{
int[] data=new int[10];
for(int i=0;i<data.length;i++)
data[i]=i+1;
System.out.println("elements of data ");
for(int i=0;i<data.length;i++)
System.out.print(" "+data[i]);
int[] prices=data.clone();
for(int i=0;i<prices.length;i++)
System.out.print(" "+prices[i]);
for(int i=0;i<copy.length;i++)
System.out.print(" "+copy[i]);
}
}
Sample output:
elements of data
1 2 3 4 5 6 7 8 9 10
elements of prices
1 2 3 4 5 6 7 8 9 10
elements copied
0 3 4 5 6 7 0 0 0 0
import java.util.ArrayList;
class BankAcc
{
private double bal;
public BankAcc()
{
bal=0;
}
public BankAcc(double inbal )
{
bal=inbal;
}
public void deposit(double am)
{
bal=bal+am;
}
public void withdraw(double am)
{
bal-=am;
}
public double getbal()
{
return bal;
}
}
class BankAccount1
{
public static void main(String[] arr)
{
ArrayList<BankAcc> accounts=new ArrayList<BankAcc>();
accounts.add(new BankAcc(1000));
accounts.add(new BankAcc(2000));
System.out.println("Initial Accounts");
for(BankAcc e:accounts)
System.out.println("balance: "+e.getbal());
for(BankAcc e:accounts)
System.out.println("balance: "+e.getbal());
int n=accounts.size();
BankAcc samp=accounts.get(0);
System.out.println("balance in first account: "+samp.getbal());
for(BankAcc e:accounts)
System.out.println("balance: "+e.getbal());
}
}
Sample output:
Initial Accounts
balance: 1000.0
balance: 2000.0
Accounts After Modification
balance: 6670.0
balance: 4000.0
balance in first account: 6670.0
balance: 6670.0
balance: 4000.0
// demonstrate try/catch/finally
public static void throwException() throws Exception
{
// throw an exception and immediately catch it
try
{
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
}
// catch exception thrown in try block
catch ( Exception exception )
{
System.out.println("Exception handled in method
throwException");
throw exception; // rethrow for further processing
// any code here would not be reached
}
Sample Output:
Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException
import java.lang.Thread;
for(int i=0;i<7;i++)
System.out.println(“ThreadB :”+p[i]);
try
{
Thread.sleep(500);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(“End of threadB”);
}
}
b.setPriority(Thread.MIN_PRIORITY);
a.setPriority(Thread.NORM_PRIORITY);
b.start();
a.start();
Sample Output:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=KeyEvents width=300 height=100> </applet>
*/
public class KeyEvents extends Applet implements KeyListener
{
String msg=" ";
int X=10,Y=20;
if(key==KeyEvent.VK_LEFT)
{
msg+="<Left Arrow>";
repaint();
}
if(key==KeyEvent.VK_RIGHT)
{
msg+="<Right Arrow>";
repaint();
}
if(key==KeyEvent.VK_CAPS_LOCK)
{
msg+="<Caps Lock is On>";
repaint();
}
import java.applet.*;
import java.awt.*;
/*
<applet code=ManualLayout width=100 height=100>
</applet>
*/
public class ManualLayout extends Applet
{
Button b;
TextField tf;
public void init()
{
b=new Button("ok");
add(b);
tf=new TextField(“”,20);
}
public void paint(Graphics g)
{
setLayout(null);
b.setLocation(25,30);
b.setSize(30,40);
tf.setLocation(20,80);
}
}
This shows the usage of manual layout which does not change the size of components in
scale to the size of applet.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=ColorEx width=300 height=300> </applet>
*/
public class ColorEx extends Applet implements AdjustmentListener
{
Scrollbar red,blue,green;
Color c;
add(red);
add(blue);
add(green);
red.addAdjustmentListener(this);
blue.addAdjustmentListener(this);
green.addAdjustmentListener(this);
c=new Color(r,g,b);
repaint();
}
import java.awt.*;
import javax.swing.*;
g.setColor( Color.RED );
g.drawLine( 5, 30, 350, 30 );
g.setColor( Color.BLUE );
g.drawRect( 5, 40, 90, 55 );
g.fillRect( 100, 40, 90, 55 );
g.setColor( Color.CYAN );
g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
g.setColor( Color.YELLOW );
g.draw3DRect( 5, 100, 90, 55, true );
g.fill3DRect( 100, 100, 90, 55, false );
g.setColor( Color.MAGENTA );
g.drawOval( 195, 100, 90, 55 );
g.fillOval( 290, 100, 90, 55 );
import java.util.*;
import java.awt.*;
import java.applet.*;
import java.text.*;
/*
<applet code=Clock width=200 height=200> </applet>
*/
public class Clock extends Applet implements Runnable {
private volatile Thread timer; // The thread that displays clock
private int lastxs, lastys, lastxm, lastym, lastxh, lastyh; // Dimensions to draw hands
private SimpleDateFormat formatter; // Formats the date displayed
private String lastdate; // String to hold date displayed
private Font clockFaceFont; // Font for number display on clock
private Date currentDate; // Used to get date to display
private Color handColor; // Color of main hands and dial
private Color numberColor; // Color of second hand and numbers
private int xcenter = 80, ycenter = 55; // Center position
try
{
setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),16)));
}
catch (NullPointerException e) { }
catch (NumberFormatException e) { }
try
{
handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),16));
}
catch (NullPointerException e) { }
catch (NumberFormatException e) { }
formatter.applyPattern("s");
try
{
s = Integer.parseInt(formatter.format(currentDate));
}
catch (NumberFormatException n) {
s = 0;
}
formatter.applyPattern("m");
try
{
m = Integer.parseInt(formatter.format(currentDate));
} catch (NumberFormatException n) {
m = 10;
}
formatter.applyPattern("h");
try {
h = Integer.parseInt(formatter.format(currentDate));
} catch (NumberFormatException n) {
h = 10;
}
g.setFont(clockFaceFont);
// Erase if necessary
g.setColor(getBackground());
if (xs != lastxs || ys != lastys) {
g.drawLine(xcenter, ycenter, lastxs, lastys);
g.drawString(lastdate, 5, 125);
}
if (xm != lastxm || ym != lastym) {
g.drawLine(xcenter, ycenter-1, lastxm, lastym);
g.drawLine(xcenter-1, ycenter, lastxm, lastym);
}
if (xh != lastxh || yh != lastyh) {
g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
g.drawLine(xcenter-1, ycenter, lastxh, lastyh);
}