Lab Manual (1)
Lab Manual (1)
Institute of Technology
Faculty of Computing and Informatics
Date: 3/29/2023
Jimma, Ethiopia.
Course Objectives
• To enable students, to know the basics of java programming
• To develop skills to design and analyze applications concerning java
programming.
• To strengthen the ability to identify and apply a suitable object-oriented concept for the
given real-world problem.
• Enable students to implement features of object-oriented programming to solve real-world
problems
• To make students familiar with handling exceptions for error-prone programs
Lab-1
Lab objective: To make students familiar with the basics of Java
Environment
Variables PATH:
1. The environment variable is used to locate the compiler.
2. Right-click my computer and find a properties tab, click on t h e properties Tab and
find Advanced Tab, and click on it to see environment variables.
3. In this create a new environment variable called PATH and copy the location of t h e
java compiler as a value to it.
Default location:
$PATH= C:\Program Files\Java\Jdk1.6.0\bin;
➢ You can use IDE like Net Beans, Eclipse, JCreato, IntelliJ
2. Hello java Program
Hint: display the message to the console
class MyFirst{
public static void main(String args[]){
System .out.println(“Hello”);
}
}
Output: Hello
3. Write a java program two add two numbers that prompt the user to inputs from the keyboard.
Hint: Accept the two numbers from the keyboard and perform the addition operation.
import java. util.Scanner;
class Adder {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("please enter the two number");
double k = sc.nextDouble();
double z = sc.nextDouble();
double x =0;
x=k+z;
System. out.println("The Sum of the two numbers is:\n"+x);
}
}
5. Write a program to perform arithmetic operations that prompts the user for inputs.
Hint: Compute arithmetic operations +, -, *, and /, and accept two numbers; you will need a total of
six variables to do all arithmetic operations and display the result to the console.
1. Import java.util.Scanner;
2. class Arithmetic {
3. public static void main (String args[]){
4. Scanner sc = new Scanner (System.in);
5. System.out.println("please enter the two number");
6. float a,b,c,d,e,f;
7. a = sc.nextFloat();
8. b = sc.nextFloat();
9. c=a+b, d=a-b,e=a*b,f=a/b;
10. System. out.println("The Sum of the two numbers is:\n"+c);
11. System. out.println("The difference of the two numbers is:\n"+d);
12. System. out.println("The product of the two numbers is:\n"+e);
13. System. out.println("The quotient of the two numbers is:\n"+f);
14. }
}
6. Write a program to calculate the volume of the sphere that prompts the user for input from the
console.
Hint: to compute the volume you need three variables, and compute with the formula.
1. import java.util.Scanner;
2. class SphereVolume {
3. public static void main(String args[]){
4. Scanner sc = new Scanner(System.in);
5. System.out.println ("please enter the three ….");
6. float a,b,c,d;
7. a = sc.nextFloat();
8. b = sc.nextFloat();
9. C=sc.nextFloat();
10. d=a*b*c;
11. System.out.println("The volume of the sphere is:\n"+d); }}
7. Write a program to check the number is odd/even that prompts the user for input;
Hint: you need only a single integer, check whether it is divisible by two or not.
1. import java.util.Scanner;
2. class EvenOdd{
3. public static void main(String args[]){
4. Scanner sc = new Scanner(System.in);
5. System.out.println("please enter the number");
6. int a;
7. a = sc.nextInt();
8. if(a%2==0)
9. System.out.println(“the number is even”);
10. else
11. System.out.println(“the number is odd”);
12. }}
8. Write a program that displays the greatest of three numbers using an if statement to accept
input from the user.
Hint: accept three numbers, compare them using a nested if statement, and display the highest
number to the console.
1. import java.util.Scanner;
2. class GreatestNum{
3. public static void main(String args[]){
4. Scanner sc = new Scanner(System.in);
5. System.out.println("please enter the number");
6. int a,b,c;
7. a = sc.nextInt();
8. b = sc.nextInt();
9. c= sc.nextInt();
10. if(a>b){
11. if(a>c){
12. System.out.println(“the highest number is:\n”+a) ;}
13. else{
14. System.out.println(“the highest number is:\n”+c) ;}}
15. else if(b>c){
16. System.out.println(“the highest number is:\n”+b) ;}
17. else{
18. System.out.println(“the highest number is:\n”+c) ;}
19. }}
9. Write a program to calculate the sum, and average, and check your grade status, if pass or fail
Hint: accept at least five-course marks then calculate the total, and average of your mark, the status
will be based on the average value. Display the total mark, average, and status.
1. import java.util.Scanner;
2. class GradeStatus{
3. public static void main(String args[]){
4. Scanner sc = new Scanner(System.in);
5. System.out.println("plse enter the mark");
6. int m1,m2,m3,m4,m5,total
7. float ave;
8. m1 = sc.nextInt();
9. m2 = sc.nextInt();
10. m3= sc.nextInt();
11. m4 = sc.nextInt();
12. m5= sc.nextInt();
13. total=m1+m2+m3+m4+m5;
14. ave=total/5;
15. if(ave>=50){
16. System.out.println(“Total mark is:”+” ”+total+””+”average is:” + ” ” + ave +” ”+” ”+”
your status is:”+”pass”);}
17. else{
18. System.out.println(“Total mark is:”+” ”+total+””+”average is:” + ” ” + ave +” ”+” your
status is:”+” ”+”fail”);}
}}
12. A certain shop sells five different products whose retail prices are as follows: product 1, $2.98;
product 2, $4.50; product 3, $9.98; product 4, $4.49; and product 5, $6.87. Write an application
that reads a pair of numbers as follows:
i. Product number
ii. Quantity sold for one day.
Your program should use a switch structure to help determine the retail price for the product. It
should calculate and display the total price of the item taking quantity into consideration.
Hint: here you are expected to use switch statement and know how to validate user inputs using
conditions and loops, your switch statement should consist of five cases, each setting the correct
dollar value, depending on the quantity that the user entered.
1. import java.util.Scanner;
2. class Saless {// calculates sales for 5 products
3. public void calculateSales() {
4. Scanner input = new Scanner(System.in);
5. double product1 = 0;
6. double product2 = 0;
7. double product3 = 0;
8. double product4 = 0;
9. double product5 = 0;
10. System.out.print("Enter product number (1-6) (0 to stop): ");
11. int productId = input.nextInt();
12. // ask user for product number until flag value entered
13. while (productId != 0) {
14. if (productId >= 1 && productId <= 6) {
15. // determine the number sold of the item
16. System.out.print("Enter quantity sold: ");
17. int quantity = input.nextInt();
18. switch (productId) {
19. case 1:
20. product1 += quantity * 2.98;
21. break;
22. case 2:
23. product2 += quantity * 4.50;
24. break;
25. case 3:
26. product3 += quantity * 9.98;
27. break;
28. case 4:
29. product4 += quantity * 4.49;
30. break;
31. case 5:
32. product5 += quantity * 6.87;
33. break;
34. } // end switch
35. } // end if
36. else if (productId != 0) {
37. System.out.println("Product number must be between 1 and 6 or 0 to stop");}
38. System.out.print("Enter product number (1-6) (0 to stop): ");
39. productId = input.nextInt();} // end while loop// print summary
40. System.out.println();
41. System.out.println(" amount sold for Product 1: $" + p1);
42. System.out.println("amount sold for product 2: $" + p2);
43. System.out.println("amount sold for product 3: $" + p3);
44. System.out.println("amount sold for product 4: $" + p4);
45. System.out.println("amount sold for product 5: $" + p5)} // end method calculateSales
46. } // end class Saless
47. public class Sales {
48. public static void main(String args[]) {
49. Saless app = new Saless();
50. app.calculateSales();
51. } }
14. 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 discriminate b2-4ac is negative, display a
message stating that there are no real solutions.
Hint: accept the values of three numbers and compute the formula given in the problem by
applying conditions for non-real solutions
1. import java.util.*;
2. class Quadratic
3. {
4. public static void main(String args[]rt)
5. {
6. double x1,x2,disc,a,b,c;
7. Scanner sc =new Scanner(System.in);
8. System.out.println("enter a,b,c values");
9. a=sc.nextDouble ();
10. b = sc.nextDouble ();
11. c= sc.nextDouble ();
12. disc= (b*b)-(4*a*c);
13. if (disc==0)
14. {
15. System.out.println("roots are real and equal "); x1=x2=b/(2*a);
16. System.out.println("roots are "+x1+","+x2);
17. }
18. else if(disc>0)
19. {
20. System.out.println("roots are real and unequal");
21. x1=(-b+Math.sqrt(disc))/(2*a); x2=(b+Math.sqrt(disc))/(2*a);
22. System.out.println("roots are "+x1+","+x2);
23. }
24. else
25. {
26. System.out.println("roots are imaginary");
27. } }
15. Write a Java program that uses both recursive and non-recursive functions to print the nth
value of the Fibonacci sequence.
Hint: 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.
/*Non Recursive Solution*/
1. import java.util.Scanner;
2. class Fib {
3. public static void main(String args[ ])
4. { Scanner input=new Scanner(System.in);
5. int i, a=1,b=1,c=0,t;
6. System.out.println("Enter value of t:");
7. t=input.nextInt();
8. System.out.print(a);
9. System.out.print(" "+b);
10. for(i=0;i<t-2;i++) {
11. c=a+b;
12. a=b; b=c; System.out.print(" "+c);
13. }
14. System.out.println();
15. System.out.print(t+"th value of the series is: "+c); } }
/* Recursive Solution*/
1. import java.util.*;
2. import java.lang.*;
3. class Demo {
4. int fib(int n)
5. { if(n==1)
6. return (1);
7. else if(n==2)
8. return (1);
9. else
10. return (fib(n-1)+fib(n-2));
11. } }
12. class RecFibDemo
13. { public static void main(String args[])
14. { Scanner sc =new Scanner(System.in);
15. System.out.println("enter last number");
16. int n=sc.nextInt();
17. Demo ob=new Demo();
18. System.out.println("fibonacci series is as follows");
19. int res=0;
20. for(int i=1;i<=n;i++)
21. { res=ob.fib(i);
22. System.out.println(" "+res);
23. }
24. System.out.println();
25. System.out.println(n+"th value of the series is "+res); } }
16. Write a program that produces the following shape. The output produced by this program is
shown here:
Hint: you will have rows and columns variable the outer loop contains the row and the inner loop
contains the column.
1. public class Triangle {
2. static int row;
3. static int column;
4. static int space;
5. public static void main(String[] args) { //first triangle
6. for (row = 10; row >= 1; row--) {
7. for (column = 1; column <= row; column++) {
8. System.out.print("*");}
9. System.out.println(); }
10. System.out.println();//seconed triangle
11. for (row = 1; row <= 10; row++) {
12. for (column = 1; column <= row; column++) {
13. System.out.print("*");
14. } System.out.println(); }
15. System.out.println();//third triangle
16. for (row = 10; row >= 1; row--) {
17. for (space = 10; space > row; space--) {
18. System.out.print(" "); }
19. for (column = 1; column <= row; column++) {
20. System.out.print("*"); } System.out.println();}
21. System.out.println();}}
Exercise
17. Write a recursive mathematical definition for computing xn for a positive integer n and a real
number x.
1. Class Vehicle{
2. Vehicle (){
3. System.out.println("Vehicle is created");}}
4. class Bike extends Vehicle{
5. Bike(){
6. super();//will invoke parent class constructor
7. System.out.println("Bike is created");}
8. public static void main(String args[]){
9. Bike b=new Bike();
10. } }
4. Write a Java Program to define a class, describe its constructor, overload the Constructors and
instantiate its object.
Hint: you will have a class as usual and different constructors like default, parameterized instantiate
using your constructor. You can have methods and overload them with different signatures. Create
an object of your class; you can create n number of objects.
1. import java.lang.*;
2. class student {
3. String name;
4. int regno;
5. int marks1,marks2,marks3; // null constructor
6. student()
7. { name="Nahanium";
8. regno=12345;
9. marks1=56;
10. marks2=47;
11. marks3=78; } // parameterized constructor
12. student(String n,int r,int m1,int m2,int m3)
13. { name=n;
14. regno=r;
15. marks1=m1;
16. marks2=m2;
17. marks3=m3; } // copy constructor
18. student(student s)
19. { name=s.name;
20. regno=s.regno;
21. marks1=s.marks1;
22. marks2=s.marks2;
23. marks3=s.marks3; }
24. void display(){
25. System.out.println(name + "\t" +regno+ "\t" +marks1+ "\t" +marks2+ "\t" + marks3);
26. } }
27. class studentdemo {
28. public static void main(String arg[])
5. Calculate the area of a circle using built-in Math library to get the constant
value PI. Apply constructors, class and object concepts.
Hint: the area of the circle is
1. public class Circle {
2. double radius=1.0;
3. public Circle() { }
4. public Circle(double rad) {
5. radius = rad;}
6. double getArea() {
7. return radius * radius * Math.PI;}
8. public static void main(String[] args) {
9. Scanner sc = new Scanner(System.in);
10. System.out.println("enter the radius");
11. double r = sc.nextDouble();
12. Circle c1 = new Circle(r);
13. System.out.println("the area of the circle with radius" + " " + c1.radius + " " + "is" + " " +
c1.getArea());
14. }
15. }
6. Write a Program to define a class, define instance methods for setting and retrieving values of
instance variables and instantiate its object.
Hint: A class with instance variable, and instance methods create the object of the class to access
the instance method.
1. class Emp {
2. String name;
3. int id;
4. String address;
5. void getdata(String name,int id,String address)
6. { this.name=name;
7. this.id=id; this.address=address; }
8. void putdata() { System.out.println("Employee details are :");
9. System.out.println("Name :" +name);
10. System.out.println("ID :" +id);
11. System.out.println("Address :" +address); }
12. } class EmpDemo
13. { public static void main(String arg[]) {
14. emp e=new emp();
15. e.getdata("ta",76859,"Nathanium");
16. e.putdata(); } }
10. Write a java program that demonstrates the difference between method overloading and
overriding.
Hint: in case of method overloading value changes as well method signature changes, while in
method overriding value will not change method name and signature should be exactly the same.
1. public class OverloadingOverridingTest {
2. public static void main(String[] args) {
3. // Example of method overloading in Java
4. // Loan l = Loan.createLoan("DovtBnak");
5. Loan cl = Loan.createLoan("Combank");
6. // Example of method overriding in Java
7. Loan personalLoan = new PersonalLoan();
8. personalLoan.toString();
9. System.out.println(" loan by ComBank");}}
10. class Loan {
11. private double interestRate;
12. private String customer;
13. private String lender;
14. public static Loan createLoan(String lender) {
15. Loan loan = new Loan();
16. loan.lender = lender;
17. return loan;}
18. public static Loan createLoan(String lender, double interestRate) {
19. Loan loan = new Loan();
20. loan.lender = lender; loan.interestRate =
21. interestRate;
22. return loan;}
23. public String toString() {
24. return "This is Loan by Comank";}}
25. class PersonalLoan extends Loan {
26. public String toString() {
27. return "This is Personal Loan by Combank";}}
11. Write a java program that demonstrates the difference between method overloading and
Constructor overloading.
Hint: In constructor overloading it is uses the same constructor name to exhibit different
behaviors and this depends on the number and type of arguments we are passing to the
constructor.
//Method overloading
1. class MethodOverloading{
2. public void add(int a, int b){
3. int sum=a+b;
4. System.out.println("Sum of two numbers = "+sum);}
5. void add(int a,int b,int c){
6. int sum=a+b+c;
7. System.out.println("Sum of three numbers = "+sum);}
8. public static void main(String args[]){
9. MethodOverloading overloading = new MethodOverloading();
10. double result;
11. overloading.add(5,6);
12. overloading.add(5,6,7);} }
//Constructor overloading
1. class Language {
2. String name;
3. Language() {
4. System.out.println ("Constructor method called.");}
5. Language(String t) {
6. name = t;}
7. public static void main(String[] args) {
8. Language cpp = new Language();
9. Language java = new Language("Java");
10. cpp.setName("C++");
11. java.getName();
12. cpp.getName();}
13. void setName(String t) { name = t;}
14. void getName() {
15. System.out.println("Language name: " + name);}
12. Write a java program that illustrates the multiple inheritances by using interfaces
Hint: An interface is a method without body, to implement an interface method it must be declared
as public access specifier.
1. interface A{
2. void method();}
3. interface B{
4. void method();}
5. class C implements A, B{
6. public void method(){
7. System.out.println(" executed method ");}
8. public static void main(String[] args)
9. { C c = new C();
10. c.method(); //been called and prints message.
11. } }
13. Write a java program that illustrates the concept of abstract classes
Hint: abstract class considered as the class property in which it provides only the structure of a
given abstraction without providing its implementation of every method.
1. abstract class Shape{
2. void display()
3. { }}
4. class Circle extends Shape{
5. void display(){
6. System.out.println("You are using circle class");}}
7. class Rectangle extends Shape{
8. void display(){
9. System.out.println("You are using rectangle class");}}
10. class Triangle extends Shape{
11. void display(){
12. System.out.println("You are using triangle class");}}
13. class AbstractClassDemo{
14. public static void main(String args[]){
15. Shape sobj = new Circle(); sobj.display();
16. sobj = new Rectangle(); sobj.display();
17. sobj = new Triangle(); sobj.display();}}
14. Write a java program that demonstrates String and some of its built-in methods.
Hint: declare an array of string and split using space it traverse over it using loop to list its tokens
or words. You can use methods like substring, replace, comparison etc.
1. public class StringExample {
2. public static void main(String[] args)
3. {
4. String s1 = new String("Welcome to Java");
5. String s2 = "Welcome to Java";
6. String s3 = "Welcome to C++";
7. String [] lines = "java is a powerful programing language over .Net like c# and
VB.Net".split("",0);
8. System.out.println(s1.equals(s2)); // true
9. System.out.println(s1.equals(s3)); // false
10. System.out.println(s1.substring(1));
11. System.out.println(s2.replace("co", "ca"));
12. System.out.println(s1.toUpperCase());
13. System.out.println(s1.length());
14. System.out.println(s1.indexOf("J"));
15. System.out.println(s1.lastIndexOf("me"));
16. for(int i=0;i< lines.length; i++){
17. System.out.println(lines[i]+""); }}}
15. Write a java program that checks whether a string is palindrome or not
Hint: you can use reverse method of the string or. Use the first and last index of the string using
charAt method of the string to compare.
1. import java.util.Scanner;
2. public class Palindrome {
3. public static void main(String[] args) {
4. Scanner input = new Scanner(System.in);
5. System.out.print("Enter a string: ");// Prompt the user to enter a string
6. String s = input.next();
7. if (isPalindrome(s)) {
8. System.out.println(s + " is a palindrome");
9. } else {
10. System.out.println(s + " is not a palindrome");
11. public static boolean isPalindrome(String s) {
12. int low = 0;
13. // The index of the last character in the string
14. int high = s.length() - 1;
15. while (low < high) {
16. if (s.charAt(low) != s.charAt(high)) {
17. return false; // Not a palindrome }
18. low++;
19. high--; }
20. return true; // The string is a palindrome}}
Lab-3: Methods
Lab Objectives: Make students familiar with, concept of methods in java to develop their problem
solving skills through dividing tasks and reuse methods. Method overloading, method overriding.
Differentiate methods and constructors.
2. Write a java program that performs call by value and call by reference
Hint: You will have one method with parameter and value change in the body call that method to
check the local variable value change.
/*Call by value */
1. class ByValue {
2. int data=50;
3. void change(int data)
4. { data=data+100; //changes will be in the local variable only
5. } public static void main(String args[])
6. { ByValue op=new byvalue();
7. System.out.println("before change "+op.data);
8. op.change(500);
9. System.out.println("after change "+op.data); } }
/*Call by reference*/
1. Class Operation2{
2. int data=50;
3. void change(Operation2 op){
4. op.data=op.data+100;//changes will be in the instance variable}
5. public static void main(String args[]){
6. Operation2 op=new Operation2();
7. System.out.println("before change "+op.data);
8. op.change(op);//passing object
9. System.out.println("after change "+op.data);
10. } }
1. Write a program that computes the average of an array element and that display elements
greater than the average of an array.
1. import java.util.*;
2. public class AnalyzeNumbers {
3. public static void main(String[] args) {
4. final int NUMBER_OF_ELEMENTS = 100;
Hint: you will have an array with element, search variable and index now if the array element
equals search element then display the element.
1. public class linear{
2. public static void main(String[] args){
3. int[] array={10,1,28,13,44,5,36,97,18,11};
4. System.out.println(" The contents of the Array are :");
5. for(int i=0;i<array.length;i++)
6. System.out.println("\t\t\t\t\t Array[" + i + "] = " + array[i]);
7. int search_element=44;
8. int find_index=-1;
9. for(int j=0;j<(array.length-1);j++)
10. {if(array[j]==search_element)
11. {find_index=j;
12. break;}}
13. if(find_index!=-1){
14. System.out.println(" The search element is : " + search_element);
15. System.out.println(" It is found in the array at position : " + find_index);}
16. else
17. System.out.println ("\n The search element is not found in the array.");}}
Lab-5: Exceptions
Lab Objectives: to make students familiar with exception handling mechanism
Write a java program that describes the exception handling mechanism
Hint: An exception is an abnormal condition that arises in the code sequence at run time, you will
have try, catch and an optional Finally block, compute the logic which might rise an error inside
the try block.
1. public class Exceptions Example{
2. public static void main(String Args[]){
3. int[] array = new int[3];
4. try{
5. for(int i=0;i<3;++i){ array[i] = i;}
6. array[0] = 2/0;}
7. catch(ArrayIndexOutOfBoundsException e){
8. System.out.println("Oops, we went too far, better go back to 0!");}
9. catch(ArithmeticException e)
10. {System.out.println("Cannot Divide by Zero!");}
11. catch(Exception e){
12. System.out.println("An Unknown Error has Occured"); e.printStackTrace();}
13. Finally{
14. System.out.println(array);
15. } } }
Output:
Cannot divide by zero
[I@3e25a5