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

Oop in Java Lab Manualdr.rahk

This laboratory manual outlines the guidelines, rules, and procedures for the Object Oriented Programming in Java course at the School of Computer Science and Engineering for the academic year 2024-25. It includes instructions for attendance, report submissions, and a list of experiments with specific programming tasks such as creating an employee class, performing mathematical operations, and calculating the area of a circle. Each experiment includes objectives, theory, procedures, and expected results to guide students in their practical learning.

Uploaded by

Keshav Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Oop in Java Lab Manualdr.rahk

This laboratory manual outlines the guidelines, rules, and procedures for the Object Oriented Programming in Java course at the School of Computer Science and Engineering for the academic year 2024-25. It includes instructions for attendance, report submissions, and a list of experiments with specific programming tasks such as creating an employee class, performing mathematical operations, and calculating the area of a circle. Each experiment includes objectives, theory, procedures, and expected results to guide students in their practical learning.

Uploaded by

Keshav Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Dr.

Rais Abdul Hamid Khan

Laboratory Manual

Name of the School: School of Computer Science


and Engineering
Name of the Department: Computer Science and engineering

Name of the Programme: Object Oriented Programming in Java

Name Of Faculty Dr. Rais Abdul Hamid khan


Qualification P.H.D(Computer Science &Engineering)

Designation Professor

Class: SE (Second Year) CSE

Course/ Course Code: 17YCS411

Academic Year: 2024-25


1
Dr.Rais Abdul Hamid Khan

Guidelines
Laboratory rules

Attendance is required for all lab classes. Students who do not attend lab will not
receive credit.

Ensure that you are aware of the test and its procedure before each lab class. You will NOT
be allowed to attend the class if you are not prepared!

Personal safety is top priority. Do not use equipment that is not assigned to you.

Allaccidentsmustbereportedtoyourinstructororlaboratorysupervisor.

Thesurroundingsneartheequipmentmustbecleanedbeforeleavingeachlab class. Ensure

that readings are checked and marked by your TA for each lab period.

Laboratory report
1. Each student has to submit the report for each experiment.
2. Your report is to be written only in the space provided in the manual
3. Please write your number and, batch and group number.
4. Your report must be neat, well organized, and make a professional impact. Label all
axes and include proper units.
5. Your reports should be submitted within 7 days and before the beginning of the lab
class of the next batch.
6. Your reports will be as per rubrics provided at the end of each experiment
7. Anyone caught plagiarizing work in the laboratory report, from a current or past
student's notebook, will receive 0 on the grading scale.
Dr.Rais Abdul Hamid Khan

NAME OF STUDENT

ACADEMIC
2024-25
YEAR

B.TECH
PROGRAMME

CLASS / DIV /ROLL.NO

PRN.NO
Dr.Rais Abdul Hamid Khan

CERTIFICTAE

This is to certify that


Mr./Miss…………… ………………
Roll no…………….. PRN No…………
of class……… …………..has satisfactorily/unsatisfactorily
completed the Term Work of Course ………JAVA……………. in
this School during academic year …2024-25……
Dr.Rais Abdul Hamid Khan

Table of contents

Sr. Title of Experiment Page Date Remark Sign


No. No
Write a java program for employee class to
1. display basic information.
Design a class in java to perform various
2. mathematical operations on given numbers.
Write a java program for calculating area of
3. circle.
Write a program for implementing single
4. inheritance for student class.
Write a program for implementing multilevel
5. inheritance for employee class
Implement java program to display content of
6. array.
Write a java program to find the prime
7. number from 1 to 20.
Write a java program to display Fibonacci
8. series of any number.
Implement a java program to perform addition
9. of two numbers, accept numbers
Write a java program to find.
A Length of given string.
10. b Reverse the string.
c Palindrome.

Implement a java program to count number of


11. vowels from given string.

Design a calculator using AWT.


12.

Course Teacher Head of Department Dean Academics


Dr.Rais Abdul Hamid Khan

EXPERIMENT NO…..1…….

Title Write a java program for employee class to display basic information.

This program demonstrates you the array of objects. Array of object is the collection
of objects of the same class. The given syntax will define an array of reference
Aim therefore assign object to individual reference in the array to declare th array of
object. .
Objective: Demonstrate the use of array of objects
Theory:
The syntax to define array of object is:

<class-name><array-name> [size];

For example, the following statement will define an array of object having size
6 references to the class Box.
Box b[6];
For creating an array of objects (allocating memory) you have to write
down the following statements for (int i=0; i<6; i++) { b[i] = new Box();
// assigning object to individual reference in the array.
}

Procedure: import java.util.Scanner;

public class Employee {

int empid;
Stringname;
float salary;
Dr.Rais Abdul Hamid Khan

public void getInput()


{

Scanner in = new Scanner(System.in);


System.out.print("Enter the empid ::
"); empid = in.nextInt();
System.out.print("Enter the name :: ");
name = in.next();
System.out.print("Enter the salary ::");
salary = in.nextFloat(); }

public void display() {

System.out.println("Employee id = " + empid);


System.out.println("Employee name = " + name);
System.out.println("Employee salary = " + salary);
}

public static void main(String[] args)

{ Employee e[] = new Employee[5];

for(int i=0; i<5; i++) {

e[i] = new
Employee();
e[i].getInput(); }

System.out.println("**** Data Entered as below ****");


for(int i=0; i<5; i++)
{

e[i].display();
}
}
}
Dr.Rais Abdul Hamid Khan

Results:

Conclusion:
Thus, We have learnt java program for employee class to display basic information.
Dr.Rais Abdul Hamid Khan

EXPERIMENT NO: 2

Title Design a class in java to perform various mathematical operations on given


numbers.
Aim Java Program for Calculator - This program will read two integer numbers and
calculate the arithmetic operators, in this example we used switch case and if
else statement. User will enter a choice after entering two numbers and based
on user choice program will return the result.
Objective 1. Demonstrate use of arithmetic operators
2. Demonstrate use of functions

Theory:

Arithmetic Operators
The Java programming language supports various arithmetic operators for all floating-point
and integer numbers. These operators are + (addition), - (subtraction), * (multiplication), /
(division), and % (modulo). The following table summarizes the binary arithmetic operations
in the Java programming language.

Operator Use Description


Adds op1 and op2; also used to concatenate
+ op1 + op2 strings

- op1 - op2 Subtracts op2 from op1


* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Computes the remainder of dividing op1 by op2

Procedure:
import java.util.*;

public class Calculator{


Dr.Rais Abdul Hamid Khan

public static void main(String


[]args){ int a,b,choice; float
result=0;
/*scanner class object to read values*/
Scanner buf=new Scanner(System.in);
System.out.print("Enter first number: ");
a=buf.nextInt();
System.out.print("Enter second number: ");
b=buf.nextInt();

System.out.print("\n1: Addition.\n2: Subtraction."); System.out.print("\n3:


Multiplication.\n4: Divide.");
System.out.print("\n5: Remainder.\n6: Exit.");
System.out.print("\nEnter your choice: ");
choice=buf.nextInt();

switch(choice)
{ case 1: result=(a+b);
break;
case 2: result=(a-b);
break;
case 3: result=(a*b);
break;
case 4: result=(float)((float)a/(float)b);
break;
case 5: result=(a%b);
break;
default:
System.out.println("An Invalid Choice!!!\n");
}
if(choice>=1 && choice<=5)
System.out.println("Result is: " + result);

}
}
Dr.Rais Abdul Hamid Khan

* Java Program Example -

Four Mathematical Operations */ import java.util.Scanner;

public class JavaProgram


{ public static void main(String args[])
{ int a, b,
res; char
ch;
Scanner scan = new Scanner(System.in);

System.out.print("Enter First Number : ");


a = scan.nextInt();
System.out.print("Enter Second Number : ");
b = scan.nextInt();
System.out.print("Enter Operator (+, -, *, /) : ");
ch = scan.next().charAt(0);

if(ch == '+')
{ res = a + b;
System.out.print("Result = " +res);
}
else if(ch == '-')
{ res = a - b;
System.out.print("Result = " +res);
}
else if(ch == '*')
{ res = a * b;
System.out.print("Result = " +res);
} else if(ch ==
'/')
{ res = a / b;
System.o
ut.print("
Result = "
+res);
}
else
Dr.Rais Abdul Hamid Khan

{
System.out.print("Wrong Operator !!!");
}
}

Results:
Dr.Rais Abdul Hamid Khan

Conclusion:

Thus , We have studied use of operators and switch case in java.


Dr.Rais Abdul Hamid Khan

Experiment No:…3……

Title Write a java program for calculating area of circle.

Aim Calculate area of circle


Objective To learn use of static methods and constructors.
.
Theory:
Java program to calculate or to print area of a circle in a simple method.
The following Java program to print the area of a circle has been written in five simple
different ways, static method, using constructor, Interface, inheritance with sample outputs
for each program.

Sr.No Different Ways


1 Static Method
2 Using Interface
3 Using Inheritance
4 Using Method
Table of contents: 5 Simple ways to print AOC

# Below is the online execution tool, for the following program

Print Area Of Circle 5 Different Ways With Examples


Below is the program to calculate the AOC in java, if you were new to java coding then we
can also share the complete step by steps with detailed explanation on how this java program
works, just below this code check it out.

1. Static Method

import java.util.Scanner;
class AreaOfCircle
{ public static void main(String args[])
{

Scanner s= new Scanner(System.in);


Dr.Rais Abdul Hamid Khan

System.out.println("Enter the radius:");


double r= s.nextDouble();
double area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}
}
Output:
1
2
3
Enter the radius :
7
Area of circle :154.0
As we know that formula in math is :

But, if you were written like that, then the system won‘t understand, until and unless
you assign the value of ―PIE‖ is 22/7. As usual , you always represent the values in binary
numbers.
The system can‘t able to understand whether the given number is a number, or given letter is
a letter. All it understood as ‖ Character ‖ or just a ― Symbol ―. Here goes the complete step
by step explanation of the above code and how it works.

Step – 1:

1
import java.util.Scanner;
( here ‗import‘ is a keyword in java used to get features from inbuilt packages. here we using
a package called until it consists of many classes and we using one of the class Scanner to get
command over console which is the interface between user and program. )

Step – 2:

1
public static void main(String args[])
( The main function, where the execution of program start from here onwards )

Step – 3:

1
Dr.Rais Abdul Hamid Khan

Scanner s= new Scanner(System.in);

( 1. The scanner is a class used to scan the input data which was given by the user through a
console.

so to get access on a console we want to create an object Syntax:new Scanner(); after creating
an object that reference will store in variable ‗s‘ )

Step – 4:

1
System.out.println("Enter the radius:");
( above code is giving instructions for the user to give the input for radius)

Step – 5:

1
double r= s.nextDouble();
( here above instruction is get input in the required format. first we want to know about
nextDouble() method it takes a token(collection of symbols divide by white space
example:‖ABC‖, ―DEF‖ , ―GHI‖,‖10″,‖20″)

which is given by user.when user give 10 as input actually in user perspective it is number
but any number or string which entered on console by default those are strings, 1o as string
but we want 10 as number format for that we have method to convert string to number(Int,
Double, Float, Long…..) some of those method are:

1.nextDouble() ,

2 nextFloat(),

3.nextInt(),

4.nextLong()

5.nextShort()

6.next() or nextString() ).

Step – 6:
Dr.Rais Abdul Hamid Khan

1
double area=(22*r*r)/7 ;
Step – 7: System.out.println(―Area of Circle is: ‖ + area); ( Once, you entered the radius , the
value stored in a particular function ( nextDouble(); ) and read those values with the help of a
scanner and display the output for a given value.

A : The major difference is where double can represent the output even after the decimal
point , whereas in ‖ Int ‖ only the numbers before decimal point will take into consideration.

area of circle java program


The second method for the above program #sample method – 2, with online compile using
command line arguments method :

Here is the sample line for an integer :

let arg[0]=‖10″;

int r=Integer.parseInt(args[0]);//r=10;

The purpose of using the ―Double ‖ is , whenever you enter the radius of a particular number
like ―7‖ , the answer is 153.86 , numbers after decimal points will also be displayed on the
screen. Whereas if you use the ―int‖ , the digits after the decimal point will be loss.

If you have any doubts related to this program , do comment here. We are glad to help you
out.

2. Using Interface There you go another program using the interface


with sample outputs.

import java.util.*; interface


AreaCal
{ void circle();
}
class AreaOfCircle implements AreaCal
{ double area; public void
circle(double r)
{
area= (22*r*r)/7;
Dr.Rais Abdul Hamid Khan

} public static void


main(String args[])
{
AreaOfCircle x;
Scanner s= new Scanner(System.in);
System.out.println("Enter the
radius:"); double rad= s.nextDouble();
x=new AreaOfCircle(); x.circle(rad);
System.out.println("Area of Circle is: " + x.area);
}
}
3. Java Program Using Inheritance
Another program to print AOC using inheritance with sample example output.
import java.util.Scanner; class
AreaCalculation
{ double area; void
circle(double r)
{ area=
(22*r*r)/7;
}
}
class AreaOfCircle extends AreaCalculation
{ public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the
radius:"); double rad= s.nextDouble();
AreaOfCircle a=new AreaOfCircle();
a.circle(rad);
System.out.println("Area of Circle is: " + a.area);
}
}
Output:
1
2
3
Enter the radius:
63
Area of Circle is: 12474.0
Dr.Rais Abdul Hamid Khan

4. Using Constructor Using constructor to


print AOC with outputs.

java.util.Scanner;
class Area
{ double area;
Area(double
r)
{ area=
(22*r*r)/7;

}
}
class AreaOfCircle
{ public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the
radius:"); double rad= s.nextDouble();
Area a=new Area(rad);
System.out.println("Area of Circle is: " + a.area);
}
}
Output:
Enter the radius:
15
Area of Circle is: 707.1428571428571

Procedure:
Using Method

import java.util.Scanner;
class AreaOfCircle
{ public static void main(String args[])
Dr.Rais Abdul Hamid Khan

Scanner s= new Scanner(System.in);


System.out.println("Enter the

radius:"); double rad= s.nextDouble();


double a=area(rad);
System.out.println("Area of Circle is: " + a);
}
static double area(double r)
{ return (22*r*r)/7;
}
}

Results:
OUTPUT:

Conclusion:
Thus we learned about java program for calculating area of circle.
Dr.Rais Abdul Hamid Khan

Experiment No:…4……

Title Write a program for implementing single inheritance for student class.
Aim To Learn about interface in java.
Objective To implement concept of inheritance in java.

Theory:
Interface in java with example programs

What is an interface in Java?


Interface looks like a class but it is not a class. An interface can have methods and variables
just like the class but the methods declared in interface are by default abstract (only method
signature, no body, see: Java abstract method). Also, the variables declared in an interface are
public, static & final by default. We will cover this in detail, later in this guide.

What is the use of interface in Java?


As mentioned above they are used for full abstraction. Since methods in interfaces do not
have body, they have to be implemented by the class before you can access them. The class
that implements interface must implement all the methods of that interface. Also, java
programming language does not allow you to extend more than one class, However you can
implement more than one interfaces in your class.

Syntax:
Interfaces are declared by specifying a keyword ―interface‖. E.g.:

interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/ public void
method1(); public
void method2();
}
Dr.Rais Abdul Hamid Khan

Procedure:
Display 1—A Base Class

public class Person

private String name;

public Person()

name = "No name yet.";

public Person(String initialName)

name = initialName;

}
public void setName(String newName)
Dr.Rais Abdul Hamid Khan

name = newName;

public String getName()

{ return

name;

public void writeOutput()

System.out.println("Name: " + name);

public boolean sameName(Person otherPerson)

return (this.name.equalsIgnoreCase(otherPerson.name));

}
Dr.Rais Abdul Hamid Khan

Display 2—A Derived Class

public class Student extends Person

private int studentNumber;

public Student()

super();//super is explained in a later section. studentNumber = 0;//Indicating no number yet

public Student(String initialName, int initialStudentNumber)

super(initialName);

studentNumber = initialStudentNumber;
Dr.Rais Abdul Hamid Khan

public void reset(String newName, int newStudentNumber)

setName(newName); studentNumber

= newStudentNumber;

public int getStudentNumber()

{ return

studentNumber;

} public void setStudentNumber(int

newStudentNumber)

{ studentNumber =

newStudentNumber;

public void writeOutput()


Dr.Rais Abdul Hamid Khan

System.out.println("Name: " + getName());

System.out.println("Student Number : " + studentNumber);

public boolean equals(Student otherStudent)

return (this.sameName(otherStudent)

&& (this.studentNumber == otherStudent.studentNumber));

Display 3—Demonstrating Inheritance

public class InheritanceDemo

public static void main(String[] args)

{
Dr.Rais Abdul Hamid Khan

Student s = new Student();

s.setName("Warren Peace");

//setName is inherited from the class Person.

s.setStudentNumber(2001);

s.writeOutput();

Results:
Screen Output
Name: Warren Peace
Student Number: 2001

Conclusion:
Thus, we learnt the implementationof single inheritance for student class using interface.
Dr.Rais Abdul Hamid Khan

Experiment No:…5……

Title Write a program for implementing multilevel inheritance for employee class.
Aim To demonstrate the concept of multilevel inheritance. Objective To
learn the structure of multilevel inheritance.

Theory:
C++ Multilevel Inheritance

If a class is derived from another derived class then it is called multilevel inheritance. So in
C++ multilevel inheritance, a class has more than one parent class.
For example, if we take animals as a base class then mammals are the derived class which
has features of animals and then humans are the also derived class that is derived from sub-
class mammals which inherit all the features of mammals.
C++ Multilevel Inheritance Block Diagram
Here is the block diagram of C++ multilevel inheritance to make it clear.
Dr.Rais Abdul Hamid Khan
Dr.Rais Abdul Hamid Khan

As shown in above block diagram, class C has class


B and class A as parent classes. Depending on the relation the level of inheritance can be
extended to any level.
As in other inheritance, based on the visibility mode used or access specifier used while
deriving, the properties of the base class are derived. Access specifier can be private,
protected or public.
C++ Programming Multilevel Inheritance
Syntax class A // base class {
...........
};
class B : acess_specifier A // derived class {
...........
};
class C : access_specifier B // derived from derived class B
{
...........
};
C++ Multilevel Inheritance Example
Here is a simple example to illustrate the concept of c++ multilevel inheritance.
// inheritance.cpp
#include <iostream>
using namespace std; class
base //single base class
{ public: int x; void
getdata() {
cout << "Enter value of x= "; cin >> x;
} };
class derive1 : public base // derived class from base class
{ public: int y; void
readdata()
{ cout << "\nEnter value of y= "; cin >> y;
} };
class derive2 : public derive1 // derived from class derive1
{ private: int z;
public: void
indata() {
cout << "\nEnter value of z= "; cin >> z;
} void
product()
{ cout << "\nProduct= " << x * y * z;
}
}; int
main()
{ derive2 a; //object of derived class
a.getdata();
Dr.Rais Abdul Hamid Khan

a.readdata();
a.indata();
a.product();
return 0;
} //end of program
Output
Enter value of x= 2

Enter value of y= 3

Enter value of z= 3
Product= 18

Procedure:
class person
{ private String name;
person(String s)
{ setName(s);
}
public void setName(String s)
{ name =
s; }
public String getName()
{ return
name;
}
public void display()
{
System.out.println("Name = " + name);
}
} class Employee extends person
{ private int empid;
Employee(String sname,int id) //Constructor Method
{
super(sname);
setEmpid(id);
} public void setEmpid(int
id)
Dr.Rais Abdul Hamid Khan

{ empid =
id; }

public int getEmpid()


{ return
empid;
} public void
display()
{
super.display();
System.out.println("Empid = " + empid);
}
};
class HourlyEmployee extends Employee
{ private double hourlyRate;
private int hoursWorked;
HourlyEmployee(String sname,int id,double hr,int hw)
{
super(sname,id)
; hourlyRate =
hr;
hoursWorked = hw;
}
public double GetGrosspay()
{ return (hourlyRate *
hoursWorked);
}
public void display()
{
super.display();
System.out.println("Hourly Rate = " + hourlyRate);
System.out.println("Hours Worked = " + hoursWorked);
System.out.println("Gross pay = " + GetGrosspay()); }
}; class
MultilevelInheritance
{ public static void main(String[] args)
{
HourlyEmployee emp = new HourlyEmployee("Dinesh Thakur",1,15,1800);
emp.display();
}
}
Dr.Rais Abdul Hamid Khan

Conclusion:

Thus, we have studied concepts and program for implementing multilevel inheritance for
employee class.
Dr.Rais Abdul Hamid Khan

Experiment No:…6……

Title Implement java program to display content of array.


Aim To study use of array in java programming Objective
To demonstrate Concept of Array

Theory:
Java Print Array Examples
Arrays are usually useful when working with arbitrarily large number of data having the
same
type. It is usually convenient if we can print the contents of an array. Below are some
examples on how to print the contents of an Array in Java.

All classes in Java has the toString() method. If we use the toString() method of an
array
Print array in object for printing, the result is not good. Here is an example:
java using default to string()

/**
* A Simple Program That Prints An Array In Java.
*/
publicclassPrintArrayInJava{
privatestaticvoid printArray(int[]
anArray){
System.out.println(anArray.toString());
} publicstaticvoid main(String[]
args){ int[] testArray
={1,2,3,4,5,6,7,8,9,10};
printArray(testArray);
}
}

Procedure:

To fix the problem, we can always use our own logic/implementation to display each item
of
Dr.Rais Abdul Hamid Khan

an array in Java. Below is an example:

Print Array In Java Using Own Implementation

/**
* A Simple Program That Prints An Array In Java using Own logic.
*/ public
classPrintArrayInJava{

private static void printArray(int[] anArray){


for(int i =0; i < anArray.length; i++){
if(i >0){
System.out.print(", ");
}
System.out.print(anArray[i]);
} } public static void main(String[]
args){ int[] testArray
={1,2,3,4,5,6,7,8,9,10};
printArray(testArray);
}
}
The output will be:

1,2,3,4,5,6,7,8,9,10
Which reflects the contents of the array. Below is another implementation
using
StringBuilder instead of displaying on screen one item at a time:

/**
* A Simple Program That Prints An Array In Java using Own logic.
*/ public class PrintArrayInJava{ private
static void printArray(int[] anArray){
StringBuilder sb =newStringBuilder();
for(int i =0; i < anArray.length; i++){ if(i
>0){ sb.append(", ");
} sb.append(anArray[i]);
}
System.out.println(sb.toString());
} public static void main(String[]
args){ int[] testArray
={1,2,3,4,5,6,7,8,9,10};
printArray(testArray);
}
}
Print Array In Java Using Arrays.toString()
Dr.Rais Abdul Hamid Khan

The java.util.Arrays class has some nice utility


functions for our use case. Below is an example on how to use the class in printing the
contents of a Java Array:

import java.util.Arrays;
/**
* A Simple Program That Prints An Array In Java using Arrays.toString().
*/ public class
PrintArrayInJava{
private static void printArray(int[] anArray){
System.out.println(Arrays.toString(anArray));
}

public static void main(String[] args){


int[] testArray ={1,2,3,4,5,6,7,8,9,10};
printArray(testArray);
}
}
First, we need to import the Arrays class to our
program: import java.util.Arrays; We can then invoke:
Arrays.toString(anArray)
To convert the array to it's String representation. The resulting String is passed to the println
method to display on the screen. The output is below. Notice the square brackets on the
output, in addition to the elements separated with commas.
[1,2,3,4,5,6,7,8,9,10]
The Arrays.toString() method can't be used with a arrays with dimension two or greater. Here
is a simple illustration, this code: import java.util.Arrays;
/**
* A Simple Program That Prints An Array In Java using Arrays.toString().
*/ public class PrintArrayInJava{ private
static void printArray(int[][] anArray){
System.out.println(Arrays.toString(anArray));
} public static void main(String[] args){
int[][] testArray
={{1,2,3},{4,5,6},{7,8,9}};
printArray(testArray);
}
}
Will output this result on screen:
Because the method will not do a deep conversion. It will only iterate on the first
dimension
and call the toString() method of each items. Resulting in unpleasant result.

Print Array In Java Using Arrays.deepToString()


For multi-dimensional arrays, the method Arrays.deepToString() is more appropriate. It will
do a deep String representation of an array, that reflects the dimension using square brackets.
Dr.Rais Abdul Hamid Khan

Below is a simple example using two dimensional array:

import java.util.Arrays;
/**
* A Simple Program That Prints An Array In Java using Arrays.deepToString().
*/
publicclassPrintArrayInJava{
privatestaticvoid printArray(int[][] anArray){
System.out.println(Arrays.deepToString(anArray));
}
publicstaticvoid main(String[] args){ int[][]
testArray ={{1,2,3},{4,5,6},{7,8,9}};
printArray(testArray);
}
}

The output is below. Notice how the square brackets denotes the level of dimension.
[[1,2,3],[4,5,6],[7,8,9]]
Here is another example using three dimensional array:
import java.util.Arrays;
/**
* A Simple Program That Prints An Array In Java using Arrays.deepToString().
*/ publicclassPrintArrayInJava{ privatestaticvoid
printArray(int[][][] anArray){
System.out.println(Arrays.deepToString(anArray))
;
}
publicstaticvoid main(String[] args){ int[][][]
testArray ={{{1,2},{4,5}},{{5,6},{7,8}}};
printArray(testArray);
}
}

Results:
Print the elements
Dr.Rais Abdul Hamid Khan

Conclusion:
Thus,We Learned to Implement java program to display content of array.
Dr.Rais Abdul Hamid Khan

Experiment No:……7…

Title Write a java program to find the prime number from 1 to 20.
Aim To find out prime no. using JAVA programming
Objective To demonstrate use of loop in JAVA Programming
.

Theory:
The for statement provides a compact way to iterate over a range of values. The general form
of the for statement can be expressed like this:

for (initialization; termination;


increment) {
statement(s) }
The initialization is an expression that initializes the loop—it's executed once at the beginning
of the loop. The termination expression determines when to terminate the loop. When the
expression evaluates to false, the loop terminates. Finally, increment is an expression that gets
invoked after each iteration through the loop. All these components are optional. In fact, to
write an infinite loop, you omit all three expressions:

for ( ; ; ) { // infinite loop


...
}

Procedure:
class PrimeNumbers
{ public static void main (String[] args)
{ int i =0; int
num =0;
//Empty
String String
primeNumber
s = "";

for (i = 1; i <= 20; i++)


{ int
counter=0;
Dr.Rais Abdul Hamid Khan

for(num =i; num>=1; num--)


{
if(i%num==0)
{ counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " "; }
}
System.out.println("Prime numbers from 1 to 20 are
:"); System.out.println(primeNumbers); }
}
Result
Prime numbers from 1 to 20 are :

2 3 5 7 11 13 17 19

Conclusion:
Thus we studied java program to find the prime number from 1 to 20.
Dr.Rais Abdul Hamid Khan

Experiment No:…8……..

Title Write a java program to display Fibonacci series of any number.


Aim To learn concept of swapping
Objective To implement program for Fibonacci series

Theory:

The Fibonacci sequence is a set of numbers that starts with a one or a zero, followed by a
one, and proceeds based on the rule that each number (called a Fibonacci number) is equal to
the sum of the preceding two numbers. If the Fibonacci sequence is denoted F (n), where n is
the first term in the sequence, the following equation obtains for n = 0, where the first two
terms are defined as 0 and 1 by convention:

F (0) = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Procedure:

Example 1: Display Fibonacci series using for


loop public class Fibonacci { public static void
main(String[] args) {

int n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");

for (int i = 1; i <= n; ++i)


{
System.out.print(t1 + " + ");
Dr.Rais Abdul Hamid Khan

int sum = t1 +
t2; t1 = t2; t2 =
sum;

}
}
}
Results:
When you run the program, the output will be:

0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +

Conclusion:
Thus we have implemented java program to display Fibonacci series of any number.
Dr.Rais Abdul Hamid Khan

Experiment No:…9…….

Title Implement a java program to perform addition of two numbers, accept numbers form
user.
Aim To Learn the concept of Input from the user Objective
To Accept the input from the user
.

Theory:
There are several ways to get input from the user in Java.

For that, you need to import Scanner class using:

import java.util.Scanner;
Then, we will create an object of Scanner class which will be used to get input from the
user.

Scanner input = new


Scanner(System.in);
int number = input.nextInt();

Procedure:
import java.util.Scanner;

class AddNumbers
{ public static void main(String args[])
{ int x, y, z;

System.out.println("Enter two integers to calculate their sum");


Scanner in = new Scanner(System.in);
Dr.Rais Abdul Hamid Khan

x = in.nextInt();
y = in.nextInt();
z=x+y;

System.out.println(―Sum of the
intergers =‖+z);

Thus we have implemented java program to accept input from user and add numbers.
Dr.Rais Abdul Hamid Khan

Experiment No:…10……

Title Write a java program to find.


a. Length of given string.
b. Reverse the string.
c. Palindrome.
Aim To learn string functions in java
Objective To demonstrate string operations in java program.
Theory:

The String is probably the most commonly used class in Java's class library. The reason for
this is that strings are a very important part of programming.

The first thing to understand about strings is that every string you create is actually an object
of the type String. Even string constants are actually the String objects. For example, in the
following statement

System.out.println("This is a String");

the string "This is a String" is a String object.

The second thing to understand about strings is that objects of the type String are immutable,
once a String object is created, its contents cannot be altered. While this may seem like a
serious restriction, it is not, for the following two reasons :

1. If you need to change a string, you can always create a new one that contains the
modifications.
2. Java defines peer classes of String, called the StringBuffer and the StringBuilder,
which allow strings to be altered, so all of the normal string manipulations are string
available in Java.
Procedure:
Java programming code to reverse a string

import java.util.*;

class ReverseString
{ public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
Dr.Rais Abdul Hamid Khan

System.out.println("Enter a string to reverse");


original = in.nextLine();

int length = original.length();


for (int i = length - 1 ; i >= 0 ; i--)
reverse = reverse + original.charAt(i);

System.out.println("Reverse of the string: " + reverse);


}
}
Palindrome program in Java
import java.util.*;

class Palindrome
{ public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);

System.out.println("Enter a string to check if it is a


palindrome"); original = in.nextLine(); int length =
original.length();

for (int i = length - 1; i >= 0; i--)


reverse = reverse + original.charAt(i);

if (original.equals(reverse))
System.out.println("The string is a palindrome.");
else
System.out.println("The string isn't a palindrome.");

}
}
Lenth of String public class
Sample_String { public static void
main(String[] args) {
//declare the String as an object S1 S2

String S1 = "Hello Java String Method";


String S2 = "RockStar";

//length() method of String returns the length of a String S1.


int length = S1.length();
Dr.Rais Abdul Hamid Khan

System.out.println("Length of a String is: " + length);


//8 Length of a String RockStar

System.out.println("Length of a String is: " + S2.length());


}
}
Results:

Conclusion:
Dr.Rais Abdul Hamid Khan

Thus ,We learned various string operations in JAVA

Experiment No:…11……

Title Implement a java program to count number of vowels from given string.
Aim To Study Boolean Operators in JAVA
Objective To implement Java Program using || operator.
.

Theory:

The Boolean logical operators operates only on boolean operands. All of the binary logical
operators combine two boolean values to form a resultant boolean value.

Boolean Logical Operators List


Here, the table given below, lists the boolean operators available in Java:

Operator Name
& Logical AND | Logical
OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

Procedure:
import java.util.Scanner; public
class Exercise4 {
public static void main(String[] args)
Dr.Rais Abdul Hamid Khan

{
Scanner in = new Scanner(System.in);

System.out.print("Input the string: ");


String str = in.nextLine();

System.out.print("Number of Vowels in the string: " + count_Vowels(str)+"\n");


} public static int count_Vowels(String
str)
{ int count = 0;
for (int i = 0; i < str.length(); i++)
{ if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
{ count++;
}}
return count;
}
}

Results: Sample Output:

Input the string: w3resource


Number of Vowels in the string: 4

Conclusion:
Dr.Rais Abdul Hamid Khan

Thus we have implemented Java


Program using || operator to count number of vowels in a string.

Experiment No:…12……

Title Design a calculator using AWT

Aim: To learn the Concept of Abstract window Toolkit

Objective: To demonstrate the Calculator

Theory:

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.
Java AWT components are platform-dependent i.e. components are displayed according
to
the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Dr.Rais Abdul Hamid Khan

Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Dr.Rais Abdul Hamid Khan

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Procedure:
import java.awt.*; import
java.awt.event.*;
public class calculator implements ActionListener
{ int c,n;
String
s1,s2,s
3,s4,s5
;
Frame f;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextField tf;
GridLayout
g;
calculator()
{ f = new Frame("My calculator");
p = new Panel();
f.setLayout(new
FlowLayout()); b1 = new
Button("0");
b1.addActionListener(this); b2

= new Button("1");
b2.addActionListener(this); b3
= new Button("2");
b3.addActionListener(this); b4
= new Button("3");
b4.addActionListener(this); b5
= new Button("4");
b5.addActionListener(this); b6
= new Button("5");
b6.addActionListener(this); b7
Dr.Rais Abdul Hamid Khan

= new Button("6");
b7.addActionListener(this); b8
= new Button("7");
b8.addActionListener(this); b9
= new Button("8");
b9.addActionListener(this); b10
= new Button("9");
b10.addActionListener(this);
b11 = new Button("+");
b11.addActionListener(this);
b12 = new Button("-");
b12.addActionListener(this);
b13 = new Button("*");
b13.addActionListener(this);
b14 = new Button("/");
b14.addActionListener(this);
b15 = new Button("%");
b15.addActionListener(this);
b16 = new Button("=");
b16.addActionListener(this);
b17 = new Button("C");
b17.addActionListener(this); tf
= new TextField(20); f.add(tf);
g = new GridLayout(4,4,10,20);
p.setLayout(g);

p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);p.add(b6);p.add(b7);p.add(b8);p.add(b9);

p.add(b10);p.add(b11);p.add(b12);p.add(b13);p.add(b14);p.add(b15);p.add(b16);p.add(b17);
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==b1)

{
s3 = tf.getText();
s4 = "0";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
Dr.Rais Abdul Hamid Khan

s4 = "1";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==
b7)
{
s3 = tf.getText();

s4 = "6";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8
)
{
s3 = tf.getText();
s4 = "7";
Dr.Rais Abdul Hamid Khan

s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9
)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;

tf.setText(s5);
}
if(e.getSource()==b10
)
{
s3 = tf.getText();
s4 = "9";
s5=s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11
)
{
s1 = tf.getText();
tf.setText("");
c=1;

}
if(e.getSource()==b12)
{
s1 = tf.getText();
tf.setText("");
c=2;

}
if(e.getSource()==b13)
{

s1 = tf.getText();
tf.setText("");
c=3;

}
if(e.getSource()==b14)
{
Dr.Rais Abdul Hamid Khan

s1 = tf.getText();
tf.setText("");
c=4;

}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;

}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2
)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3
)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{

int p=Integer.parseInt(s2);
if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
Dr.Rais Abdul Hamid Khan

}
else
tf.setText("infinite");
}
catch(Exception i){}
}
if(c==5)
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{ tf.setText("");
}
}

public static void main(String[] abc)


{
calculator v = new calculator();
}
}

Results:
OUTPUT:

1. Compile: javac calculator.java


Dr.Rais Abdul Hamid Khan

Run: java calculator

Conclusion:
Thus we designed Calculator by using AWT Java programming

You might also like