UNIVERSITY OF GONDAR FACULITY OF NATURAL
AND COMPUTATIONAL SCIENCE DEPARTMENT OF
INFORMATION TECHNOLOGY
Group assignment
at the course code ITEC433
Submitted by:
Name IDNO
1. ZEMENU TADELE 2509/02
2. EMEYE MULU 1360/04
3. TIGIST KALAYU 1548/04
4. HERMELA TESHOME 1405/04
5. ERMIAS HAILU 1367/04
Submitted to: Mr. HAGOS
November/2007
1. Write a program to find the biggest of three numbers entered from keyboard?
package assignment1;
import java.util.Scanner;
class LargestOfThreeNumbers
public static void main(String args[])
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
else
System.out.println("Entered numbers are not distinct.");
2. Write a program to draw a set of concentric circles using graphics class?
package assignment.pkg6;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class Concentric {
private static final JComponent triangleComponent = new JComponent() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.draw(new Line2D.Double(180, 100, 100, 0));
g2.draw(new Line2D.Double(20, 100, 100, 0));
g2.draw(new Line2D.Double(180, 100, 20, 100));
};
private static final JComponent ConcentricCircleMaker = new JComponent() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
double[] circles = {40, 80, 120, 160, 200};
Color[] colors = {Color.red, Color.green, Color.orange, Color.MAGENTA, Color.cyan};
int count = 0;
for (double i : circles) {
g2.setColor(colors[count++]);
g2.draw(Factory.get().makeCircle(200 - i / 2, 200 - i, i));
};
public static void main(String[] args) {
JFrame frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 50, 500, 500);
frame.setVisible(true);
frame.setContentPane(triangleComponent);
JOptionPane.showMessageDialog(null, "Click OK to Continue");
frame.setVisible(false);
frame.setContentPane(ConcentricCircleMaker);
frame.setVisible(true);
private static class Factory {
private static final FactorySingle factory;
static {
factory = new FactorySingle();
static FactorySingle get() {
return factory;
private static class FactorySingle {
public Ellipse2D.Double makeCircle(double x, double y, double length) {
return new Ellipse2D.Double(x, y, length, length);
}
3. Write a program to check whether a given number is odd or even?
import java.util.Scanner;
class OddOrEven
public static void main(String args[])
int x;
System.out.println("Enter an integer to check if it is odd or even ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if ( x % 2 == 0 )
System.out.println("You entered an even number.");
else
System.out.println("You entered an odd number.");
4,write any java program that implements for all access protection of packages
package emu;
class BaseClass {
public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
return x;
public void setX(int x) {
this.x = x;
private int getY() {
return y;
private void setY(int y) {
this.y = y;
protected int getZ() {
return z;
protected void setZ(int z) {
this.z = z;
int getA() {
return a;
void setA(int a) {
this.a = a;
}
class SubclassInSamePackage extends BaseClass {
public static void main(String args[]) {
BaseClass rr = new BaseClass();
rr.z = 0;
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(20);
System.out.println("Value of x is : " + subClassObj.x);
//Access Modifiers - Public
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private
/* System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
System.out.println("Value of z is : " + subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : " + subClassObj.z);
//Access Modifiers - Default
System.out.println("Value of x is : " + subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of x is : " + subClassObj.a);
5. Write a java program that implements interface?
package assignment1;
interface Info {
static final String language = "Java";
public void display();
class Simple implements Info {
public static void main(String []args) {
Simple obj = new Simple();
obj.display();
// Defining method declared in interface
public void display() {
System.out.println(language + " is awesome");
}
6. Write a program for calendar class implementation?
package assignment.pkg6;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CalendarProgram{
static JLabel lblMonth, lblYear;
static JButton btnPrev, btnNext;
static JTable tblCalendar;
static JComboBox cmbYear;
static JFrame frmMain;
static Container pane;
static DefaultTableModel mtblCalendar; //Table model
static JScrollPane stblCalendar; //The scrollpane
static JPanel pnlCalendar;
static int realYear, realMonth, realDay, currentYear, currentMonth;
public static void main (String args[]){
//Look and feel
try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException e) {}
//Prepare frame
frmMain = new JFrame ("Gestionnaire de clients"); //Create frame
frmMain.setSize(330, 375); //Set size to 400x400 pixels
pane = frmMain.getContentPane(); //Get content pane
pane.setLayout(null); //Apply null layout
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close when X is clicked
//Create controls
lblMonth = new JLabel ("January");
lblYear = new JLabel ("Change year:");
cmbYear = new JComboBox();
btnPrev = new JButton ("<<");
btnNext = new JButton (">>");
mtblCalendar = new DefaultTableModel(){@Override
public boolean isCellEditable(int rowIndex, int mColIndex){return false;}};
tblCalendar = new JTable(mtblCalendar);
stblCalendar = new JScrollPane(tblCalendar);
pnlCalendar = new JPanel(null);
//Set border
pnlCalendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
//Register action listeners
btnPrev.addActionListener(new btnPrev_Action());
btnNext.addActionListener(new btnNext_Action());
cmbYear.addActionListener(new cmbYear_Action());
//Add controls to pane
pane.add(pnlCalendar);
pnlCalendar.add(lblMonth);
pnlCalendar.add(lblYear);
pnlCalendar.add(cmbYear);
pnlCalendar.add(btnPrev);
pnlCalendar.add(btnNext);
pnlCalendar.add(stblCalendar);
//Set bounds
pnlCalendar.setBounds(0, 0, 320, 335);
lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 100, 25);
lblYear.setBounds(10, 305, 80, 20);
cmbYear.setBounds(230, 305, 80, 20);
btnPrev.setBounds(10, 25, 50, 25);
btnNext.setBounds(260, 25, 50, 25);
stblCalendar.setBounds(10, 50, 300, 250);
//Make frame visible
frmMain.setResizable(false);
frmMain.setVisible(true);
//Get real month/year
GregorianCalendar cal = new GregorianCalendar(); //Create calendar
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day
realMonth = cal.get(GregorianCalendar.MONTH); //Get month
realYear = cal.get(GregorianCalendar.YEAR); //Get year
currentMonth = realMonth; //Match month and year
currentYear = realYear;
//Add headers
String[] headers = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //All headers
for (int i=0; i<7; i++){
mtblCalendar.addColumn(headers[i]);
tblCalendar.getParent().setBackground(tblCalendar.getBackground()); //Set background
//No resize/reorder
tblCalendar.getTableHeader().setResizingAllowed(false);
tblCalendar.getTableHeader().setReorderingAllowed(false);
//Single cell selection
tblCalendar.setColumnSelectionAllowed(true);
tblCalendar.setRowSelectionAllowed(true);
tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Set row/column count
tblCalendar.setRowHeight(38);
mtblCalendar.setColumnCount(7);
mtblCalendar.setRowCount(6);
//Populate table
for (int i=realYear-100; i<=realYear+100; i++){
cmbYear.addItem(String.valueOf(i));
//Refresh calendar
refreshCalendar (realMonth, realYear); //Refresh calendar
public static void refreshCalendar(int month, int year){
//Variables
String[] months = {"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"};
int nod, som; //Number Of Days, Start Of Month
//Allow/disallow buttons
btnPrev.setEnabled(true);
btnNext.setEnabled(true);
if (month == 0 && year <= realYear-10){btnPrev.setEnabled(false);} //Too early
if (month == 11 && year >= realYear+100){btnNext.setEnabled(false);} //Too late
lblMonth.setText(months[month]); //Refresh the month label (at the top)
lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 180, 25); //Re-align label with
calendar
cmbYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box
//Clear table
for (int i=0; i<6; i++){
for (int j=0; j<7; j++){
mtblCalendar.setValueAt(null, i, j);
//Get first day of month and number of days
GregorianCalendar cal = new GregorianCalendar(year, month, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
//Draw calendar
for (int i=1; i<=nod; i++){
int row = new Integer((i+som-2)/7);
int column = (i+som-2)%7;
mtblCalendar.setValueAt(i, row, column);
//Apply renderers
tblCalendar.setDefaultRenderer(tblCalendar.getColumnClass(0), new tblCalendarRenderer());
static class tblCalendarRenderer extends DefaultTableCellRenderer{
@Override
public Component getTableCellRendererComponent (JTable table, Object value, boolean selected,
boolean focused, int row, int column){
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
if (column == 0 || column == 6){ //Week-end
setBackground(new Color(255, 220, 220));
else{ //Week
setBackground(new Color(255, 255, 255));
if (value != null){
if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth &&
currentYear == realYear){ //Today
setBackground(new Color(220, 220, 255));
setBorder(null);
setForeground(Color.black);
return this;
static class btnPrev_Action implements ActionListener{
@Override
public void actionPerformed (ActionEvent e){
if (currentMonth == 0){ //Back one year
currentMonth = 11;
currentYear -= 1;
else{ //Back one month
currentMonth -= 1;
}
refreshCalendar(currentMonth, currentYear);
static class btnNext_Action implements ActionListener{
@Override
public void actionPerformed (ActionEvent e){
if (currentMonth == 11){ //Foward one year
currentMonth = 0;
currentYear += 1;
else{ //Foward one month
currentMonth += 1;
refreshCalendar(currentMonth, currentYear);
static class cmbYear_Action implements ActionListener{
@Override
public void actionPerformed (ActionEvent e){
if (cmbYear.getSelectedItem() != null){
String b = cmbYear.getSelectedItem().toString();
currentYear = Integer.parseInt(b);
refreshCalendar(currentMonth, currentYear);
}
}
7. Write a program to find the area and perimeter of a circle for a given radius using
buffered reader class?
package assignment1;
//Write a java program to Calculate Circle Perimeter
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class assignment7 {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter radius of a circle: ");
int radius = Integer.parseInt(br.readLine());
double perimeter = 2 * Math.PI * radius;
System.out.println("Perimeter of a circle : " + perimeter);
}
8. Write a program to convert Centigrade to Fahrenheit?
package assignment1;
import java.util.Scanner;
public class assignment8{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double celsius, fahrenheit;
System.out.print("Enter a temperature in Celsius: ");
celsius = sc.nextDouble();
fahrenheit = 32 + (celsius * 9 / 5);
System.out.println(celsius +" ºC = " + fahrenheit + " ºF");
9. Write a program for dialogues and Menus using swing classes?
Dialogue using swing class
package assignment.pkg6;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.Icon;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.lang.reflect.Field;
public class Assignment92 extends JFrame{
private JTextArea tracker;
//Using a standard Java icon
private Icon optionIcon = UIManager.getIcon("FileView.computerIcon");
//Application start point
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
public void run()
//create GUI frame
new Assignment92().setVisible(true);
});
public Assignment92()
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Dialog Box Example");
setSize(500,300);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Using JTextArea to show clicks and responses
tracker = new JTextArea("Click tracker:");
add(tracker);
setVisible(true);
//Options for the combo box dialog
String[] choices = {"Monday", "Tuesday"
,"Wednesday", "Thursday", "Friday"};
//Options for the list dialog
//There are more than 20 entries to make the showInputDialog method
//choose to use a list box
String[] jumboChoices = {"Abe", "Billy", "Colin", "Dexter"
, "Edward", "Fred", "Gus", "Harry", "Ira", "Jeff"
, "Kirk", "Larry", "Monty", "Nigel", "Orville", "Paul"
, "Quint", "Richard", "Steve", "Tony", "Umberto", "Vinnie"
, "Wade", "Xavier", "Yogi", "Zigmund"};
//Input dialog with a text field
String input = JOptionPane.showInputDialog(this
,"Enter in some text:");
TrackResponse(input);
//Input dialog with default text in the text field
String defaultText = JOptionPane.showInputDialog(this
,"Enter in some text:","some text..");
TrackResponse(defaultText);
//Input dialog with a textfield, a message type and title
String warningText = JOptionPane.showInputDialog(this
,"Erm, enter in a warning:" ,"Warning Message"
,JOptionPane.WARNING_MESSAGE);
TrackResponse(warningText);
//If an icon is used then it overrides the icon from the
//message type. Likewise if a null is entered for the selection values
//the dialog box will use a text field
String entered = (String)JOptionPane.showInputDialog(this
, "Enter a Day of the week:"
, "Text Field Dialog", JOptionPane.QUESTION_MESSAGE
, optionIcon, null, null);
TrackResponse(entered);
//If the String Array has more than 20 entries a JList is used
//as the method the user gets to select a value
String boyNames = (String)JOptionPane.showInputDialog(this, "Pick a Name:"
, "ComboBox Dialog", JOptionPane.QUESTION_MESSAGE
, optionIcon, jumboChoices, jumboChoices[0]);
TrackResponse(boyNames);
//Input dialog with a combo box created by
//using a String array for the object message. Note how
//a null icon for the icon results in the QUESTION_MESSAGE
//message type being used.
String picked = (String)JOptionPane.showInputDialog(this, "Pick a Day:"
, "ComboBox Dialog", JOptionPane.QUESTION_MESSAGE
, null, choices, choices[0]);
TrackResponse(picked);
//Append the picked choice to the tracker JTextArea
public void TrackResponse(String response)
//showInputDialog method returns null if the dialog is exited
//without an option being chosen
if (response == null)
tracker.append("\nYou closed the dialog without any input..");
else
tracker.append("\nYou picked " + response + "..");
Menus using swing class
package assignment.pkg6;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Menus91 extends JFrame{
JLabel menuLabel = new JLabel ("This is my Menu!");
Menus91() {
//------Setup of simple menu
JMenuBar menuBar = new JMenuBar(); //set up of JMenuBar, this is the final element that
the menu itself will be displayed in, similiar to a container.
ImageIcon exitIcon = new ImageIcon ("close.gif"); //stores our Image for the exit command
of the menu.
ImageIcon hideIcon = new ImageIcon ("hide.gif");
ImageIcon showIcon = new ImageIcon ("show.gif");
JMenu menu = new JMenu("Menu"); //sets up the JMenu
JMenu exitMenu = new JMenu("Label"); //creation of our submenu
menu.setMnemonic(KeyEvent.VK_M); //allows our menu to be accessed when we click
ALT + M, you can do this for individual menu items aswell.
JMenuItem exitItem = new JMenuItem ("Exit Program", exitIcon);//create our first
command (menu item)
JMenuItem hidelblItem = new JMenuItem ("Hide Label", hideIcon);
JMenuItem showlblItem = new JMenuItem("Show Label", showIcon);
menu.add(exitItem); //add the command (menu item) to our menu
exitMenu.add(hidelblItem); //add our JMenuItem's to our submenu --
exitMenu.add(showlblItem); //--
menu.addSeparator(); //visual element that seemingly splits our two menu's, you can
comment this out, it just makes the program look nicer :)/>
menu.add(exitMenu); //Add our submenu to our original menu.
menuBar.add(menu); //add the JMenu to the JMenuBar
setJMenuBar(menuBar); //set the default JMenuBar of the Swing application
//------Setup of JFrame
// FlowLayout layout = new FlowLayout();
setSize(650,450); //set the size of the application (350 pixels width, 175 pixels high)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set what occurs when the "X"
button at the top right of the application is clicked
setTitle("Menu in Java"); //set the title of our Swing application
menuLabel.setText("This is my Menu Comment!");
// setLayout(layout);
add(menuLabel); //adds the label to our form using the defaul FlowLayout.
setVisible(true); //set the graphical elements of our Swing application to visible, so they can
be seen.
exitItem.addActionListener(new ActionListener() { //adds an ActionListener interface for our
exitItem
public void actionPerformed(ActionEvent e) {
System.exit(0); //exit our application
});
//--Add actionListeners for our submenu items and the functionality code:
showlblItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuLabel.setVisible(true); //hide our menuLabel
});
hidelblItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuLabel.setVisible(false); //show our menuLabel
});
} //end of class
public static void main(String[] args) {
new Menus91();
10. Write a java program that implements multithreading concepts?
package assignment.pkg6;
class RunnableDemo implements Runnable {
private Thread t;
private final String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
@Override
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
System.out.println("Thread " + threadName + " exiting.");
public void start ()
System.out.println("Starting " + threadName );
if (t == null)
t = new Thread (this, threadName);
t.start ();
public class Assignment10 {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
11. Write a java program to implement inheritance of classes?
animal.java
package assignment11;
public class Animal {
public Animal() {
System.out.println("A new animal has been created!");
public void sleep() {
System.out.println("An animal sleeps...");
public void eat() {
System.out.println("An animal eats...");
Bird.java
import assignment11.Animal;
public class Bird extends Animal {
public Bird() {
super();
System.out.println("A new bird has been created!");
@Override
public void sleep() {
System.out.println("A bird sleeps...");
@Override
public void eat() {
System.out.println("A bird eats...");
}
}
Dod.java
package assignment11;
public class Dog extends Animal {
public Dog() {
super();
System.out.println("A new dog has been created!");
@Override
public void sleep() {
System.out.println("A dog sleeps...");
@Override
public void eat() {
System.out.println("A dog eats...");
MainClass.java
package assignment11;
public class MainClass {
public static void main(String[] args) {
Animal animal = new Animal();
Bird bird;
bird = new Bird();
Dog dog = new Dog();
System.out.println();
animal.sleep();
animal.eat();
bird.sleep();
bird.eat();
dog.sleep();
dog.eat();