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

Final - OOPJ Lab Manual

The aim of the experiment is to implement a Java program to perform basic arithmetic operations. The theory discusses the key features of Java including that it is simple, object-oriented, robust, secure, high-performance, and multithreaded. The program allows the user to choose an arithmetic operation and enter two numbers, and displays the result.

Uploaded by

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

Final - OOPJ Lab Manual

The aim of the experiment is to implement a Java program to perform basic arithmetic operations. The theory discusses the key features of Java including that it is simple, object-oriented, robust, secure, high-performance, and multithreaded. The program allows the user to choose an arithmetic operation and enter two numbers, and displays the result.

Uploaded by

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

EXPERIMENT NO: 1

Aim: Implementation C++ program to perform basic arithmetic operation.


Theory:
Object oriented programming – As the name suggests uses objects in programming. Object
oriented programming aims to implement real world entities like inheritance, hiding,
polymorphism etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of code can access this data except that
function.
The Pillars of Object oriented Programming are:
Object: Objects are basic run-time entities in an object oriented system, objects are instances of
a class these are defined user defined data types.
Class: Class is a blueprint of data and functions or methods. Class does not take any space.
Encapsulation and Data abstraction: Wrapping up(combing) of data and functions into a
single unit is known as encapsulation. The data is not accessible to the outside world and only
those functions which are wrapping in the class can access it. This insulation of the data from
direct access by the program is called data hiding or information hiding.
Data abstraction refers to, providing only needed information to the outside world and hiding
implementation details. For example, consider a class Complex with public functions as
getReal() and getImag(). We may implement the class as an array of size 2 or as two variables.
The advantage of abstractions is, we can change implementation at any point, users of Complex
class wont’t be affected as out method interface remains same. Had our implementation be
public, we would not have been able to change it.

Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
Polymorphism: polymorphism means ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends upon the types of data
used in the operation.
Structure of C++ program
/ my first program in C++
#include <iostream>
int main()
{
std::cout << "Hello World!";
}
Output: Hello World!
1
Line 1: // my first program in C++
Two slash signs indicate that the rest of the line is a comment inserted by the programmer but
which has no effect on the behavior of the program. Programmers use them to include short
explanations or observations concerning the code or program. In this case, it is a brief introductory
description of the program.

Line 2: #include <iostream>


Lines beginning with a hash sign (#) are directives read and interpreted by what is known as
the preprocessor. They are special lines interpreted before the compilation of the program itself
begins. In this case, the directive #include <iostream>, instructs the preprocessor to include a
section of standard C++ code, known as header iostream, that allows to perform standard input and
output operations, such as writing the output of this program (Hello World) to the screen.

Line 3: A blank line.


Blank lines have no effect on a program. They simply improve readability of the code.

Line 4: int main ()


This line initiates the declaration of a function. Essentially, a function is a group of code statements
which are given a name: in this case, this gives the name "main" to the group of code statements
that follow. Functions will be discussed in detail in a later chapter, but essentially, their definition
is introduced with a succession of a type (int).
The function named main is a special function in all C++ programs; it is the function called when
the program is run. The execution of all C++ programs begins with the main function, regardless of
where the function is actually located within the code.

Lines 5 and 7: { and }


The open brace ({) at line 5 indicates the beginning of main's function definition, and the closing
brace (}) at line 7, indicates its end. Everything between these braces is the function's body that
defines what happens when main is called. All functions use braces to indicate the beginning and
end of their definitions.

Line 6: std::cout << "Hello World!";


This line is a C++ statement. A statement is an expression that can actually produce some effect. It
is the meat of a program, specifying its actual behavior. Statements are executed in the same order
that they appear within a function's body.

This statement has three parts: First, std::cout, which identifies the standard character output device
(usually, this is the computer screen). Second, the insertion operator (<<), which indicates that
what follows is inserted into std::cout. Finally, a sentence within quotes ("Hello world!"), is the
content inserted into the standard output.

2
Experiment_No:1

a)Program: Simple calculator using C++.


#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
float a, b, res;
char choice, ch;
do
{
cout<<"1.Addition\n";
cout<<"2.Subtraction\n";
cout<<"3.Multiplication\n";
cout<<"4.Division\n";
cout<<"5.Exit\n\n";
cout<<"Enter Your Choice : ";
cin>>choice;
switch(choice)
{
case '1' : cout<<"Enter two number : ";
cin>>a>>b;
res=a+b;
cout<<"Result = "<<res;
break;
case '2' : cout<<"Enter two number : ";
cin>>a>>b;
res=a-b;
cout<<"Result = "<<res;
break;
case '3' : cout<<"Enter two number : ";
cin>>a>>b;
res=a*b;
cout<<"Result = "<<res;
break;
case '4' : cout<<"Enter two number : ";
cin>>a>>b;
res=a/b;
cout<<"Result = "<<res;
break;
case '5' : exit(0);
break;
default : cout<<"Wrong Choice..!!";
break;
}
cout<<"\n------------------------------------\n";
}while(choice!=5 && choice!=getchar());

3
OUTPUT:

Conclusion: Thus we have studied addition of numbers using C++ Programming in DOS platform.

4
b) Program on factorial numbers using C++ and virtual lab. Go to Problem Solving Lab →List Of
Experiments on http://ps-iiith.vlabs.ac.in/
We shall try to calculate the factorial of a number and then find out the number of digits in it.
1! = 1
2! = 1*2 = 2
3! = 1*2*3 = 6
4! = 1*2*3*4 = 24.
10! = 3628800
So n! means multiplying all the numbers from 1 to n. For the sample input, 52, we can see from the
sample output that the factorial of 52 is 68 digits and this cannot fit in long long data type in C. You
may now attempt to store the answer in a string and do multiplication operation on strings(by
multiplying each digit of the string individually). Now, let us see how many operations do we need
for multiplying 2 strings. Consider 11!, 11! = 11*10!, assume we already have 10! stored in a string
and 11 stored in a string. Now, to calculate 11! from 10! we need to multiply each digit of 11 with
each digit of 10!, i.e it would take No_digits(11) * No_digits(3628800) = 2*7 = 14 operations. We
consider only multiplication operations(we also have to consider addition operations for each of the
biproducts and carries).
Similarly 53! would take 2*68=136 operations from 52!.
52! would take 2*67 = 134 operations from 51!
51! would take 2*65 = 130 operations from 50!.
We can see that there would be a operations required for calculating 53! (No_operations =
136+134+130+...+1). Also in 1000000! the number of digits is 5565709, so we would require large
amount of storage and both these difficulties make calculation of N! hard.
Let us observe the zeroes in the factorial of a few numbers.
4!=24 (0 zeroes)
5!=120 (1 zeroes)
6!=720 (1 zeroes)
7!=5040 (1 zeroes)
8!=40320 (1 zeroes)
9!=362880 (1 zeroes)
10!=3628800 (2 zeroes)
11!-14! (2 zeroes)
15! (3 zeroes)

We can observe that for every multiple of 5, we have a zero being added to the product. This is due
to the multiplication of 5 with an even number in the product. So, our problem simplifies to counting
the number of 5's in the factors of the number to be calculated. Let us formalize the proof.
Conclusion: Thus we have studied Factorials in virtual lab.

5
EXPERIMENT NO: 2

Aim: Implementation of java program to perform basic arithmetic operation.


Theory:
Features of java:

Simple: Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:

Object-Oriented: Unlike C++ which is semi object-oriented, Java is a fully object-oriented


programming language. It has all OOP features such as abstraction, encapsulation, inheritance
and polymorphism.

Robust: With automatic garbage collection and simple memory management model (no
pointers like C/C++), plus language features like generics, try-with-resources, Java guides
programmer toward reliable programming habits for creating highly reliable applications.

Secure: The Java platform is designed with security features built into the language and runtime
system such as static type-checking at compile time and runtime checking (security manager),
which let you creating applications that can’t be invaded from outside. You never hear about
viruses attacking Java applications.

High Performance: Java code is compiled into bytecode which is highly optimized by the Java
compiler, so that the Java virtual machine (JVM) can execute Java applications at full speed. In
addition, compute-intensive code can be re-written in native code and interfaced with Java
platform via Java Native Interface (JNI) thus improve the performance.

Multithreaded: The Java platform is designed with multithreading capabilities built into the
language. That means you can build applications with many concurrent threads of activity,
resulting in highly interactive and responsive applications.

Platform Independence: Java code is compiled into intermediate format (byte code), which
can be executed on any systems for which Java virtual machine is ported. That means you can
write a Java program once and run it on Windows, Mac, Linux or Solaris without re-compiling.
Thus the slogan “Write once, run anywhere” of Java.

6
Java Scanner Class
Java Scanner class comes under the java.util package. Java has various ways to read input from
the keyboard, the java.util.Scanner class is one of them.
1 String next() It is used to get the next complete token from the
scanner which is in use.
2 boolean nextBoolean() It scans the next token of the input into a boolean
value and returns that value.
3 byte nextByte() It scans the next token of the input as a byte.
4 double nextDouble() It scans the next token of the input as a double.
5 float nextFloat() It scans the next token of the input as a float.
6 int nextInt() It scans the next token of the input as an Int.
7 String nextLine() It is used to get the input string that was skipped
of the Scanner object.
8 long nextLong() It scans the next token of the input as a long.
9 short nextShort() It scans the next token of the input as a short.
Structure of a JAVA program
class Simple
{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main method is executed by the JVM, so it doesn't require to create an object to
invoke the main method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class. We will learn about the internal
working of System.out.println statement later.

7
Experiment_No:2
Program.Simple calculator using java.
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
double num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");

num1 = scanner.nextDouble();
System.out.print("Enter second number:");
num2 = scanner.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");


char operator = scanner.next().charAt(0);
scanner.close();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
default:
System.out.printf("You have entered wrong operator");
return;
}
System.out.println(num1+" "+operator+" "+num2+": "+output);
}
}

8
Conclusion:
Here we have studied object oriented features and implemented simple java program.

9
EXPERIMENT NO: 3

Aim: Implementation Java Program to define a class defines instance methods for setting and
getting values of instance variables and instantiate its object.
Theory:
Class: A class is a user defined blueprint or prototype from which objects are created.
Syntax of the class:
class <class_name>{
field;
method; }

There are 3 ways to initialize object in java.

Object: It is a basic unit of Object Oriented Programming and represents the real life entities.
Object is instance of the class.
1.Initialization through Reference: Initializing an object means storing data into the object.
class Student{
}
public static void main(String args[]){
Student s1=new Student(); }
2.Initialization through method: In this example, we are creating the objects of Student class
and initializing the value to these objects by invoking the insertRecord method.

class Student{

void insertRecord(int r, String n){


rollno=r;
name=n;
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
s1.insertRecord(111,"Karan"); }}}

3. Initialization through Constructor:


class Example3 {
public static void main(String[] args) {
// Create an empty cup
CoffeeCup cup1 = new CoffeeCup();
// Create a cup with 355 ml of coffee in it
CoffeeCup cup2 = new CoffeeCup(355);
}
}

Types of variables:
1. Local Variables: A variable defined within a block or method or constructor is called local
variable. These variable are created when the block in entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
10
2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.
3. Static Variables: Static variables are also known as Class variables.
These variables are declared similarly as instance variables, the difference is that static variables
are declared using the static keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective
of how many objects we create
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
GET AND SET METHODS IN JAVA:
get and set are technically called getters & setters. getters/setters provide public access to
private data.
why they are better?
setters prevents direct exposing your class variables to other objects. You can keep your class
variable private and provide a setter to assign its value.
Public void setName ( String n ) {
name = n;
}
getter have same advantage as setter it can format the class variable and return.

public String getName() {


return name;

11
Experiment_No:3
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package com.javatpoint;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}

/A Java class to test the encapsulated class.


package com.javatpoint;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}
Output :Vijay

Conclusion: Here we have studied class, instantiating object, Get and Set methods.

12
EXPERIMENT NO: 04

Aim: Implementation of Method Overloading (Static Polymorphism) in Java.

a) Addition of numbers

b) Calculate monthly salary

Method Overloading is a feature that allows a class to have more than one method having the same
name, if their argument lists are different.
Three ways to overload a method

In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)

2. Data type of parameters.


For example:
add(int, int)
add(int, float)

3. Sequence of Data type of parameters.


For example:
add(int, float)
add(float, int)

Invalid case of method overloading:


for example if two methods have same name, same parameters and have different return type, then
this is not a valid method overloading example. This will throw compilation error.
int add(int, int)
float add(int, int)

Method overloading is an example of Static Polymorphism.


Static Polymorphism: Polymorphism that is resolved during compiler time is known as static
polymorphism.

13
a) Addition of numbers
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
OUTPUT:
30
60
31.0

14
b)Calculate monthly salary

class Savingaccount {
static double annualinterestrate;
private double savingbalance;
double monthlyinterest;
Savingaccount(double balance) {
savingbalance=balance;
} //Constructor close
void interest() {
System.out.println("Saving Balance ="+savingbalance);
monthlyinterest=((savingbalance*annualinterestrate)/12);
System.out.println("Monthly Interest ="+monthlyinterest);
savingbalance=savingbalance+monthlyinterest;
System.out.println("Saving Balance ="+savingbalance);
} //Method close
void interest(double newannualinterestrate){
annualinterestrate=newannualinterestrate;
System.out.println("Annual interest rate ="
+annualinterestrate);
} //overloaded method close
} //class close
public class Methodover {
public static void main(String[] args){
Savingaccount s=new Savingaccount(2000.0);
s.interest(0.05);
s.interest();
Savingaccount s1=new Savingaccount(3000.0);
s1.interest(0.05);
s1.interest();
} //main close
} //Main class close
OUTPUT:
Annual interest rate =0.05
Saving Balance =2000.0
Monthly Interest =8.333333333333334
Saving Balance =2008.3333333333333
Annual interest rate =0.05
Saving Balance =3000.0
Monthly Interest =12.5
Saving Balance =3012.5

Conclusion-

Here we have studied method overloading in java.

15
EXPERIMENT NO: 05
Aim : Implementation Constructor in java.
Theory:
A constructor initializes an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit return type.
Rules for writing Constructor:
 Constructor(s) of a class must has same name as the class name in which it resides.
 A constructor in Java can not be abstract, final, static and Synchronized.

 When you set a method as final it means: "You don't want any class override it." But the
constructor (according to the Java Language Specification) can't be overridden, so it is clean.
 When you set a method as abstract it means: "The method doesn't have a body and it should be
implemented in a child class." But the constructor is called implicitly when the new keyword is
used so it can't lack a body. Constructor needs to have a body and implementation, so there is no
sense in making them abstract.

 When you set a method as static it means: "The method belongs to the class, not a particular
object." But the constructor is implicitly called to initialize an object, so there is no purpose in
having a static constructor.

 As far as synchronization is concerned, again it cannot be implemented on constructors. The


concept of synchronization is to prevent multiple threads from accessing a method, at one time.
Only the thread that creates an object needs to have access to it, while constructor is invoked, so
you can’t switch out to another thread.

 Access modifiers can be used in constructor declaration to control its access i.e which other class
can call the constructor.

Following is the syntax of a constructor −


class ClassName {
ClassName() {
}
}

java allows two types of constructors namely −

1. No argument Constructors: A constructor that has no parameter is known as default


constructor. If we don’t define a constructor in a class, then compiler creates default
constructor(with no arguments) for the class. And if we write a constructor with arguments or
no-argument then compiler does not create default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the
type. Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
16
}
}
You would call constructor to initialize objects as follows
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}
2. Parameterized Constructors
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of
the class with your own values, then use parameterized constructor.
Example
Here is a simple example that uses a constructor −
// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows −
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}

17
Experiment_No:5
class ConsMain {
private int x;
// Default constructor
private ConsMain(){
System.out.println("Constructor is called!");
x = 139;
} //constructor close
public static void main(String[] args){
ConsMain obj = new ConsMain();
System.out.println("Value of x = " + obj.x);
} //main close
} //class close
OUTPUT:
Constructor is called!
Value of x = 139
Title2: Java Program for Parameterized Constructor.
class Vehicles {
int wheels;
private Vehicles(int wheel)
{
wheels = wheel;
System.out.println(wheels + " wheeler vehicle created.");
} //Parameterized constructor
public static void main(String[] args)
{
Vehicles v1 = new Vehicles(2);
Vehicles v2 = new Vehicles(3);
Vehicles v3 = new Vehicles(4);
}
}
OUTPUT:
2 wheeler vehicle created.
3 wheeler vehicle created.
4 wheeler vehicle created.
Conclusion: Here we have studied constructor concepts.

18
EXPERIMENT NO: 06

Aim: Implementation of constructor overloading in java.


Theory:
Constructor Overloading:
Just like method overloading, constructors also can be overloaded. Same constructor declared with different
parameters in the same class is known as constructor overloading. Compiler differentiates which constructor
is to be called depending upon the number of parameters and their sequence of data types.

this() with Constructors:


Suppose by accessing one constructor, the programmer may require the functionality of other constructors
also but by creating one object only. For this, Java comes with this(). "this()" is used to access one
constructor from another "within the same class". Depending on the parameters supplied, the suitable
constructor is accessed.

public class Perimeter


{
public Perimeter() // I
{
System.out.println("From default");
}
public Perimeter(int x) // II
{
this();
System.out.println("Circle perimeter: " + 2*Math.PI*x);
}
public Perimeter(int x, int y) // III
{
this(100);
System.out.println("Rectangle perimeter: " +2*(x+y));
}
public static void main(String args[])
{
Perimeter p3 = new Perimeter(10, 20); // III
}
}

In the code, creating object p3, the III constructor is accessed. From III, with "this(100)" statement, the II
constructor is accessed. Again from II, the I is accessed without the statement "this()". As per the parameter
supplied to this(), the appropriate or corresponding constructor is accessed.
ules of using this()
A few restrictions exist for the usage of this().
If included, this() statement must be the first one in the constructor. You cannot write anything before this()
in the constructor.
With the above rule, there cannot be two this() statements in the same constructor (because both cannot be
the first).
this() must be used with constructors only, that too to call the same class constructor (but not super class
constructor).

19
Experiment_6: Java Program for Constructor Overloading.
class Company {
String domainName;
public Company(){
this.domainName = "DefaultConstuctor.com";
} //Default constructor close
public Company(String dName){
this.domainName = dName;
} //parameterized constructor close
public void getName(){
System.out.println(this.domainName);
}
public static void main(String[] args) {
Company defaultObj = new Company();
Company programizObj = new Company("ByateWorld.com");
defaultObj.getName();
programizObj.getName();
} //main close
} //class close
OUTPUT:
DefaultConstuctor.com
ByateWorld.com

Conclusion- Here we have studied constructor overloading in java.

20
EXPERIMENT_NO : 07

Aim: Implementation of class grade book using 2 Dimensional array


Theory:
An array is a collection of similar type of elements that have a contiguous memory location.
Java array is an object which contains elements of a similar data type. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.
Array in java is index-based, the first element of the array is stored at the 0 index.

Types of Array in java


Single Dimensional Array
Multidimensional Array

Syntax to Declare an Array in Java


dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column

21
Experiment_No:7 Implementation of class grade book using two-dimensional array.

import java.util.Scanner;

public class Gradebook


{
public static void main(String args[])
{
int i, j;
int add;
int arr[][]=new int [5][3];
System.out.println("**********Grade Book Of Students************");
Scanner s=new Scanner(System.in);
for(i=0;i<5;i++)
{
System.out.println("Enter the Marks for student "+(i+1));
for(j=0;j<3;j++)
{
System.out.print("test "+(j+1)+":");
arr[i][j]=s.nextInt();
}//for j close
}//for i close

//Display the data


System.out.print("\n Marks \tTest 1\tTest 2\tTest 3\tTotal");
System.out.print("\n__________________________________________");
for(i=0;i<5;i++)
{
add=0;
System.out.print("\nStudent "+(i+1)+"\t");
for(j=0;j<3;j++)
{
System.out.print(" "+arr[i][j]+"\t");
add=add+arr[i][j];
}
System.out.print(" "+add+"\t");
}
}//main close
}//class close

OUTPUT:

**********Grade Book Of Students************


Enter the Marks for student 1
test 1:23
test 2:45
test 3:45
Enter the Marks for student 2
test 1:54
test 2:67
test 3:37
Enter the Marks for student 3
test 1:95
test 2:96
test 3:99
Enter the Marks for student 4
test 1:90
22
test 2:98
test 3:99
Enter the Marks for student 5
test 1:79
test 2:89
test 3:87

Marks Test 1 Test 2 Test 3 Total


_________________________________________________________
Student 1 23 45 45 113
Student 2 54 67 37 158
Student 3 95 96 99 290
Student 4 90 98 99 287
Student 5 79 89 87 255

Conclusion- Here we have studies array implementation.

23
EXPERIMENT NO: 08

Aim: Implementing the concept of package.


Theory:
Java provides a mechanism for partitioning the class name space into more manageable chunks. This
mechanism is the package. The package is both a naming and a visibility control mechanism. You can
define classes inside a package that are not accessible by code outside that package. You can also define
class members that are only exposed to other members of the same package.
Defining a Package
To create a package is quite easy: simply include a package command as the first statement in a Java
source file. Any classes declared within that file will belong to the specified package. The package
statement defines a name space in which classes are stored. If you omit the package statement, the class
names are put into the default package, which has no name. While the default package is fine for short,
sample programs, it is inadequate for real applications. Most of the time, you will define a package for
your code.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package.
More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong. It does not exclude other classes in
other files from being part of that same package. Most real-world packages are spread across many files.
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];

For example, a package declared as


package java.awt.image;
needs to be stored in java/awt/image, java\awt\image, or java:awt:image on your UNIX, Windows, or
Macintosh file system, respectively. Be sure to choose your
package names carefully. You cannot rename a package without renaming the
directory in which the classes are stored.
How to access package from another package?
There are three ways to access the package from outside the package.
1 Using packagename.*

1. //save by A.java 1. //save by B.java


2. package pack; 2. package mypack;
3. public class A{ 3. import pack.*;
4. public void msg(){Syste 4.
m.out.println("Hello");} 5. class B{
5. } 6. public static void main(String args[]){

7. A obj = new A();


8. obj.msg(); }
9. }

24
2.Using packagename.classname

/save by A.java 1. /save by B.java


Import package.*;
package pack; 2. package mypack;
public class A{ 3. import pack.A;
public void msg(){System.out.println("Hel class B{
lo");} public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

. 3.Using fully qualified name

1. //save by A.java 1. //save by B.java


2. package pack; 2. package mypack;
3. public class A{ 3. class B{
4. public void msg(){System.out.prin 4. public static void main(String args[]){
tln("Hello");} 5. pack.A obj = new pack.A();//using fully qu
5. } alified name
6. obj.msg();
7. }

25
Experiment_No:08

package myPack;
public class car
{
String c_name;
engine e;
tyre t;
door d;
public car(String cn,engine e1,tyre t1,door d1 )
{
c_name=cn;
e=e1;
t=t1;
d=d1;
}
public void display()
{
System.out.println("Car name"+c_name);
System.out.println("Engine type:”+e.e_type);
System.out.println("Door color:"+d.color);}
package myPack;
public class tyre
{
int size;
public void set(int size)
{
this.size=size;

26
System.out.println("Tyre Size:"+size);
}
}
package myPack;
public class engine {
String e_type;
public engine(String e_type)
{
this.e_type=e_type;
}
}
package myPack;
public class door {
String color;
public door (String c)
{
color=c;
}
}
Calling Classes from Packages
import myPack.*;
public class CarInfo {
public static void main(String[] args) {
engine e=new engine("Petrol");
tyre t=new tyre();
door d=new door("Black");
car c=new car("Lamborghini",e,t,d);
t.set(30);
c.display();
}
}

27
OUTPUT:
Tyre Size:30
Car name: Lamborghini
Engine type: Petrol
Door color: Black

Conclusion-
Thus we have studied how to create our own package and import it.

28
EXPERIMENT NO.9
Aim: Implementing the concept of Inheritance.
Theory:

Inheritance Basics
Inheritance is a major component of object-oriented programming. Inheritance will allow
you to define a very general class, and then later define more specialized classes by simply
adding some new details to the older more general class definition. This saves work, because the
more specialized class inherits all the properties of the general class and you, the programmer,
need only program the new features. i.e Inheritance in java is a mechanism in which one object
acquires all the properties and behaviors of parent object. The idea behind inheritance in java is
that you can create new classes that are built upon existing classes. When you inherit from an
existing class, you can reuse methods and fields of parent class, and you can add new methods
and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java


 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class.In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.Understanding the simple example of inheritance

29
displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.

Types of inheritance in java:

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

When to use Inheritance?

When you need to use and modify property and behavior of a class inside your class, its best to
use Inheritance.

30
Experiment_No:9 Implementing the concept of Inheritance.
package myPack;

class Employee{
protected int emp_no;
protected String name;
protected int salary;

//constructor
public Employee(int empno,String nam,int sal){
emp_no=empno;
name=nam;
salary=sal;
}

public void emplo_data(){


System.out.println("\nEmployee No: "+emp_no);
System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
}
}//class Employee

class Manager extends Employee{


int reward;

//constructor
public Manager(int empno,String nam,int sal,int p){
super(empno,nam,sal);
reward=p;
}

public void managerdata(){


System.out.println("\nEmployee No: "+emp_no);
System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
System.out.println("Reward: "+reward);
}
}//class Manager

class Scientist extends Employee{


int perks;

//constructor
public Scientist(int empno,String nam,int sal,int s){
super(empno,nam,sal);
perks=s;
}

public void scientistdata(){


System.out.println("\nEmployee no: "+emp_no);
System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
31
System.out.println("Perks: "+perks);
}
}//class Scientist

//Main Class
class Inheritance{
public static void main(String args[])
{
Employee emp= new Employee(1,"Priyanka",45000);
emp.emplo_data();

Manager man= new Manager(2,"Rohit",50000,3000);


man.managerdata();

Scientist scient= new Scientist(3,"Pratiksha",48000,5000);


scient.scientistdata();
}
}

OUTPUT:

Employee No: 1

Name: Priyanka

Salary: 45000

Employee No: 2

Name: Rohit

Salary: 50000

Reward: 3000

Employee no: 3

Name: Pratiksha

Salary: 48000

Perks: 5000

Conclusion: Thus we have studied the concept of inheritance and implemented it.

32
Experiment No.10

Aim: Implementing the concept of Polymorphism.


Theory:

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here,

we will focus on runtime polymorphism in java.

Types of polymorphism:

1.Method Overloading in Java – This is an example of compile time (or static polymorphism)

Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different. It is similar to constructor overloading in Java,
that allows a class to have more than one constructor having different argument lists.

2. Method Overriding in Java – This is an example of runtime time (or dynamic


polymorphism

Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class. In this case the method in parent class is called
overridden method and the method in child class is called overriding method. In this guide, we
will see what is method overriding in Java and why we use it.

class Human{

//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
33
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

class A{}

class B extends A{}

A a=new B();//upcasting

Java Runtime Polymorphism Example: Bank

Consider a scenario where Bank is a class that provides a method to get the rate of interest.
However, the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS
banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

34
Experiment_10
a)Bank details polymorphism
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

OUTPUT:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

b)Animal class polymorphism


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
class Cat extends Animal{
void eat(){System.out.println("eating rat...");}
}
class Lion extends Animal{
void eat(){System.out.println("eating meat...");}
}
class TestPolymorphism3{
public static void main(String[] args){
Animal a;
a=new Dog();
35
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();

OUTPUT:
eating bread...
eating rat...
eating meat...

Conclusion: Thus we have studied the concept of polymorphism and implemented it.

36

You might also like