0% found this document useful (0 votes)
13 views

Lab Manual (1)

Uploaded by

wabii3179.com
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lab Manual (1)

Uploaded by

wabii3179.com
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Jimma University

Institute of Technology
Faculty of Computing and Informatics

Object Oriented Programming (Java) Lab Exercise


For Information Technology 3rd-year students

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

1. Installation of Java software:


1. Download JDK 11.7 or above from www.java.sun.com/downloads
2. Install JDK by double-clicking on the setup file
3. Follow the installation wizard.
4. Upon successful installation, the default location where java is installed is the
C:\Program Files\Java directory.
5. To compile a java class, we have to use javac (java compiler)
6. To execute a java program, we have to use JVM (java virtual machine).
7. To use javac and JVM we have to configure environment variables.

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);
}
}

4. What will be the output of the following code fragment


class Outputs {
public static void main (String args[]) {
int x = 5, y = 10;
int z = ++x * y--;
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}

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”);}
}}

10. Write a program to find the factorial of a number.


Hint: you will accept one integer and find its factorial using any loop.
1. public class Factorial {
2. public static void main(String[] arg) {
3. Scanner sc = new Scanner(System.in);
4. System.out.println("please enter a number");
5. int x = sc.nextInt();
6. int result = 1;
7. for (int i = 1; i <= x; i++) {
8. result *= i;
9. System.out.println(result);
10. }}}

11. Write a program to check whether a number is prime or not


Hint: you will need one integer as input, if the number is divisible by only one and itself, use a
loop.
import java.util.Scanner;
class Prime{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
System.out.println("enter the number");
int num=scan.nextInt();
int count=0;
for(int i=1;i<=num;i++){
if(num%i==0){
count++;}}
if(count>2){
System.out.println("the number "+num+" is not prime");
}
else{
System.out.println("the number "+num+" is prime");}}}

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. } }

13. Program to find the sum and average of N natural numbers


Hint: you will have three variables, incremental, sum and average, use for loops to iterate over N
numbers, initially the sum is zero.
1. public class Sum {
3. public static void main(String[] args) {
4. int n, i, sum=0;
5. double ave;
6. for(i=1; i<=n; i++)
7. {
8. Sum+=i;
10. }
11. ave=sum/n;
13. System.out.println("the sum is :"+sum);
14. System.out.println("the average is :"+ave);
15. }}

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.

B-2: Java OOP concepts


Lab objectives: To make students familiar with object oriented concepts like: Naming convention,
access level modifiers, class, object, constructor, keywords (static, this, super, final), inheritance,
method overriding and overloading, inner class, anonymous inner class, multilevel inheritances, run
time polymorphism, how to achieve multiple inheritances through interface, interface, abstract class,
polymorphism ,package, string class and its built-in methods.
1. Creating multiple objects by one type only and usage of this keyword, to calculate the area of a
rectangle
Hint: You do have a class and t using comma with new keywords, you can instantiate more than
one objec
1. class Rectangle{
2. int length; //data member/instance variable
3. int width; //data member/instance variable
4. Rectangle(int length)
5. {this.l=length;}
6. Rectangle(int length, int width)
7. {
8. this.length=length;
9. this.width=width;
10. }
11. void insert(int l, int w){
12. length=l;
13. width=w; }
14. void calculateArea(){
15. System.out.println(length*width);}
16. public static void main(String args[]){
17. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
18. r1.insert(11,5);
19. r2.insert(3,15);
20. r1.calculateArea();
21. r2.calculateArea(); } }

2. W rite a java program that implements the usage of super keyword.


Hint: super is used to refer immediate parent class instance variable, you will have instance
variables and methods inside your class then call the data member through the super keyword.
1. class Vehicle {
2. int speed=50; }
3. class Bike extends Vehicle{
4. int speed=100; void display(){
5. System.out.println(super.speed);//will print speed of Vehicle now
6. } public static void main(String args[])
7. { Bike b=new Bike(); b.display(); } }

✓ super() is used to invoke immediate parent class constructor

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. } }

✓ Super is used to invoke immediate parent class method


1. class Person{
2. void message(){
3. System.out.println("welcome");} }
4. class Student extends Person{
5. void message(){
6. System.out.println("welcome to java");}
7. void display(){
8. message();//will invoke current class message() method
9. super.message();//will invoke parent class message() method
10. }
11. public static void main(String args[]){
12. Student s=new Student();
13. s.display();
14. } }

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[])

29. { Student s1=new student();


30. student s2=new student("Nati",34266,58,96,84);
31. student s3=new student(s1);
32. s1.display();
33. s2.display();
34. s3.display(); } }

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(); } }

7. Write a java program that illustrates the simple inheritance.


Hint: you will have super class and sub class, which extends from the supper class, you can have
constructors and/or methods in the supper class and/or sub class, instantiate the object of the two
classes call the methods and look the changes.
1. class A {
2. int i, j;
3. A(int a, int b)
4. { i = a; j = b; }
5. void show()
6. { System.out.println("i and j: " + i + " " + j); } }
7. class B extends A {
8. int k;
9. B(int a, int b, int c)
10. { super(a, b);
11. k= c; }
12. void show(String msg) {
13. System.out.println("k: " + k); } }
14. class Override {
15. public static void main(String args[]) {
16. B subOb = new B(1, 2, 3);
17. subOb.show("This is k");
18. subOb.show(); } }

8. write a java program that shows inner class concepts


1. public class Employee
2. {
3. int age = 0;
4. public String name = "Charles";
5. double rate = 111.34;
6. Address address;
7. Wage wage;
8. public Employee(String aName,int number, String aStreet,
9. String aCity,double ratePerHour,int hours)
10. {
11. name = aName;
12. rate = ratePerHour;
13. address = new Address(number,aStreet,aCity);
14. wage = new Wage(hours);
15. }
16. // inner class
17. class Address
18. {
19. int number = 0;
20. String street = "";
21. String city = "";
22. Address(int num,String aStreet,String aCity)
23. {
24. number = num;
25. street = aStreet;
26. city = aCity;
27. }
28. void printDetails()
29. {
30. 130 CHAPTER 5. INHERITANCE AND ABSTRACT CLASSES

31. System.out.println(number + " " + street + " , " + city);


32. }
33. } // end class Address
34. // inner class
35. class Wage
36. {
37. int hoursWorked = 0;
38. Wage(int hours)
39. {
40. hoursWorked = hours;
41. }
42. void printDetails()
43. {
44. System.out.println("Pay packet = " + hoursWorked*rate);
45. }
46. } // end class Wage
47. public static void main(String[] args)
48. {
49. Employee[] e = new Employee[2];
50. e[0] = new Employee("Bob",33,"Lane Street","Springfield",4.5,56);
51. e[1] = new Employee("Lucky",123,"Pop Street","Lancing",5.7,34);
52. e[0].printInformation();
53. e[1].printInformation();
54. }
55. public void printInformation()
56. {
57. System.out.println("\nFor Employee: " + name);
58. address.printDetails();
59. wage.printDetails();
60. }
61. }

9. Write a java program which illustrates multilevel inheritance


Hint: if the derived class is obtained from a base class and the derived class itself acts as a base
class and derives the further subclass, we call it multilevel inheritance.
1. class student{
2. int rollno;
3. String name;
4. student(int r, String n){
5. rollno = r;
6. name = n;}
7. void dispdatas(){
8. System.out.println("Rollno = " + rollno); System.out.println("Name = " + name);}}
9. class marks extends student{
10. int total;
11. marks(int r, String n, int t){
12. super(r,n);
13. total = t;}
14. void dispdatam(){
15. dispdatas();
16. System.out.println("Total = " + total);}}
17. class percentage extends marks{
18. int per;
19. percentage(int r, String n, int t, int p){
20. super(r,n,t);
21. per = p;}
22. void dispdatap(){
23. dispdatam(); System.out.println("Percentage = " +
24. per);}}
25. class Multilevel{
26. public static void main(String args[]){
27. percentage stu = new percentage(1912, "Nathanium", 350, 50); //call constructor percentage
stu.dispdatap()} }

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.

1. Write a java program which returns maximum of the two number


Hint: declare method that accept two parameter, compare the and return the max
1. public class TestMax {
2. /** Main method */
3. public static void main(String[] args) {
4. Scanner sc =new Scanner(System.in)
5. int i = sc.nextInt();
6. int j = sc.nextInt();
7. int k =max(x ,k) ;
8. System.out.println ("The maximum between " + i +" and " + j + " is " + k);}
9. /** Return the max between two numbers */
10. Public static int max(int num1, int num2){
11. int result;
12. if (num1 > num2)
13. result = num1;
14. else
15. result = num2;
16. return result; }}

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. } }

3. Write a java program that demonstrates method overloading


Hint: methods with the same name and different signatures
public class TestMethodOverloading {
/** Main method */
public static void main(String[] args) {
// Invoke the max method with int parameters
System.out.println("The maximum between 3 and 4 is "+ );
// Invoke the max method with the double parameters
System.out.println("The maximum between 3.0 and 5.4 is "+ );
// Invoke the max method with three double parameters
System.out.println("The maximum between 3.0, 5.4, and 10.14 is "+ );}
/** Return the max between two int values */
public static double max(int num1, int num2){
if (num1 > num2)
return num1;
else
return num2;
}
/** Find the max between two double values */
public static double max(double num1, double num2){
if (num1 > num2)
return num1;
else
return num2;}
/** Return the max among three double values */
public static double max(double num1, double num2,double num3){
return max(max(num1, num2), num3);}}

Lab-4: Arrays, collection framework


Lab Objectives: to know the concepts of array data structures, initialization, methods, one and two
dimensional arrays. Possibly other collection frameworks like list, set, and map.

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;

5. double[] numbers = new double[NUMBER_OF_ELEMENTS];


6. double sum = 0;
7. Scanner input = new Scanner(System.in);
8. for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
9. System.out.println("Enter a new number: ");
10. numbers[i] = input.nextDouble();
11. sum + = numbers[i];}
12. double average = sum / NUMBER_OF_ELEMENTS;
13. int count = 0; // The number of elements above average
14. for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
15. if (numbers[i] > average)
16. count++;
17. System.out.println("Average is " + average);
18. System.out.println("Number of elements above the average "+ count)}}

2. Write a Java program to sort given list of numbers.


Hint: initialize an array number with some numbers with in it, declare and initialize n as number
of length.
1. class sorting{
2. public static void main(String args[]){
3. int number[]={55,40,80,65,71};
4. int n=number. Length;
5. System.out.println("given list");
6. for(int i=0;i<n;i++){
7. System.out.println(""+number[i]);}
8. for(int i=0;i<n;i++){
9. for(int j=i+1;j<n;j++){
10. if(number[i]<number[j]){
11. int temp=number[i];
12. number[i]=number[j];
13. number[j]=temp;} }}
14. System.out.println("sorted list");
15. for(int i=0;i<n;i++){
16. System.out.println(""+number[i]);}
17. System.out.println("");}}

1. Write a Java program to implement linear search.

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.");}}

2. Write a java program to add two given matrices.


Hint: you need two dimensional arrays let’s say and b, accept values of them from the user and
add them.
1. import java.util.*;
2. public class matrixsum {
3. public static void main (String[] args){

4. int i,j,a[][] = new int[10][10],b[][]= new int[10][10];


5. Scanner input = new Scanner(System.in);
6. for(i=0;i<2;i++){
7. for(j=0;j<2;j++){
8. System.out.println("Enter Number :");
9. a[i][j] = input.nextInt();}}
10. System.out.println("Enter Other Matrix");
11. for(i=0;i<2;i++){
12. for(j=0;j<2;j++){
13. System.out.println("Enter Number :");
14. b[i][j] = input.nextInt();} }
15. System.out.println("Sum :-");
16. for(i=0;i<2;i++){
17. for(j=0;j<2;j++)
18. System.out.print(a[i][j]+b[i][j]+" ");
19. } } }
3. Write a java program for sorting a given list of names.
Hint: you will have an array of names; u can use methods which return an array of string and
another method which computes checking and swapping.
1. import java.io.*;
2. class Test {
3. int len , i, j;
4. String arr[ ];
5. Test(int n) {
6. len=n;
7. arr=new String[n];}
8. String[ ] getArray(){
9. Scanner sc=new Scanner(System.in);
10. System.out.println ("Enter the strings U want to sort----");
11. for (int i=0;i<len;i++)
12. arr[i]=sc.nextInt();
13. return arr;}
14. String[ ] check()throws ArrayIndexOutOfBoundsException {

15. for (i=0;i<len-1;i++){


16. for(int j=i+1;j<len;j++){
17. if ((arr[i].compareTo(arr[j]))>0){
18. String s1=arr[i];
19. arr[i]=arr[j];
20. arr[j]=s1;}}}
21. return arr;}
22. void display()throws ArrayIndexOutOfBoundsException{
23. System.out.println ("Sorted list is---");
24. for (i=0;i<len;i++)
25. System.out.println(arr[i]);}}
26. class Ascend{
27. public static void main(String args[ ]) {
28. Test obj1=new Test(4);
29. obj1.getArray();
30. obj1.check();
31. obj1.display();}}

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

You might also like