0% found this document useful (0 votes)
134 views62 pages

IET - 4 OOP Lab Manual Updated

This document appears to be a lab manual for an introductory course on object-oriented programming in Java. It includes 14 experiments covering topics like control structures, loops, and object-oriented programming concepts. It provides instructions for students on maintaining the manual, contains sections for marking experiments and projects, and lists the experiments to be covered over the course of the semester.

Uploaded by

Syed Kamran Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views62 pages

IET - 4 OOP Lab Manual Updated

This document appears to be a lab manual for an introductory course on object-oriented programming in Java. It includes 14 experiments covering topics like control structures, loops, and object-oriented programming concepts. It provides instructions for students on maintaining the manual, contains sections for marking experiments and projects, and lists the experiments to be covered over the course of the semester.

Uploaded by

Syed Kamran Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

LAB MANUAL

CSC 1012L
OBJECT ORIENTED PROGRAMMING
(v. 1.1)

Student Name:
Class & Section:
Roll Number:
CGPA:
Email ID:

DEPARTMENT OF SOFTWARE ENGINEERING


Foundation University Rawalpindi Campus (FURC)
New Lalazar, Rawalpindi, Pakistan
www.fui.edu.pk

1 CSC 1012L OOP


PREFACE

This lab manual has been prepared to facilitate the students of Information engineering
Technology in studying and analyzing object orientation. Object Orientation is a technique
used extensively in software engineering and IT Projects to build software products as a
bottom-up method. The object orientation allows us to view the world as objects having
attributes and methods. To perform a task objects, communicate with other objects by
invoking methods.

PREPARED BY
Lab manual is prepared by Mr.Waqas Ahmed under the supervision of Head of Department
Dr. Shariq Hussain in the year 2021.

GENERAL INSTRUCTIONS
a. Students are required to maintain the lab manual with them till the end of the semester.
b. All readings, answers to questions and illustrations must be solved on the place
provided. If more space is required then additional sheets may be attached.
c. It is the responsibility of the student to have the manual graded before deadlines as given
by the instructor
d. Loss of manual will result in re-submission of the complete manual.
e. Students are required to go through the experiment before coming to the lab session. Lab
session details will be given in training schedule.
f. Students must bring the manual in each lab.
g. Keep the manual neat clean and presentable.
h. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarised and
no re submission will be entertained.
i. Marks will be deducted for late submission.
j. Error handling in a program is the responsibility of the Student.

VERSION HISTORY

Date Update By Details


April 2021 Waqas Ahmed First Version Created

2 CSC 1012L OOP


MARKS

Exp Date Experiment Title Max. Marks Instructor


# Conducted Marks Obtained Sign
1 INTRODUCTION TO 10
JAVA
2 CONTROL 10
STRUCTURES AND
LOOPS
3 10

4 10

5 10

6 10

7 10

8 10

9 10

10 10

11 10

12 10

13 10

14 10
SESSIONAL TOTAL

PROJECT PHASE - I 10

PROJECT PHASE - II 20

PROJECT TOTAL 30

GRAND TOTAL (100) 100

3 CSC 1012L OOP


LIST OF EXPERIMENTS

EXPERIMENT 1 – INTRODUCTION TO JAVA..........................................................................................


EXPERIMENT 2 – CONTROL STRUCTURES AND LOOPS.....................................................................
EXPERIMENT 3 –...........................................................................................................................................
EXPERIMENT 4 –...........................................................................................................................................
EXPERIMENT 5 –...........................................................................................................................................
EXPERIMENT 6 –...........................................................................................................................................
EXPERIMENT 7 –...........................................................................................................................................
EXPERIMENT 8 –...........................................................................................................................................
EXPERIMENT 9 – ..........................................................................................................................................
EXPERIMENT 10 ...........................................................................................................................................
EXPERIMENT 11 –.........................................................................................................................................
EXPERIMENT 12 –.........................................................................................................................................
EXPERIMENT 13 –.........................................................................................................................................
EXPERIMENT 14 –.........................................................................................................................................
PROJECT –OBJECT ORIENTED PROGRAMMING - PHASE - I...............................................................
PROJECT –OBJECT ORIENTED PROGRAMMING - PHASE - II.............................................................

4 CSC 1012L OOP


EXPERIMENT 1 – INTRODUCTION TO JAVA

1. Objec
t
ives:
Learning Java Language

(a).
(b). Difference between C++ and Java

(c). Writing Programs in Java

(d). Executing Java programs

(e). Java variables

(f). Arithmetic Expressions

(g). Control Structures and Loops

2. Time Required: 6 hrs

3. Programming Language: Java

4. Software Required:
(a). Windows OS
(b). NetBeans / Eclipse Kepler

5. Java Compiler is software that compiles the Java code into Bytecode. Bytecode is a set
of commands that the java virtual machine understands.

6. Java Runtime Environment (JRE) is the virtual machine over which the java code is
executed. This virtual machine executes the java code. The JRE must be provided before
executing a Java program.

7. Java/NetBeans Download Links:

1 CSC 103L – Introduction to Java


5
1. https://netbeans.org/downloads/
2. https://www.oracle.com/java/technologies/javase-downloads.html

8.

Java naming rules and guidelines

An identifier is a word that can be used to name a class, method, variable, or


constant. Java has rules for choosing a legal identifier. If a rule is not obeyed, the
code will not compile. Recall that Java is case sensitive.

Java Rules for Choosing Identifiers

1. An identifier may use all letters, a – z and A – Z, all digits, 0 – 9, the underscore (_)
and $.
2. An identifier may not begin with a digit.

3. An identifier may not be a Java reserved word. Reserved words, or key words are
words that have a special meaning in Java.

Reserved words Examples:

abstact boolean break byte case char class const continue default double else
extends final finally for goto if implements import int interface long native new
private protected public return short
strictfp super switch synchronized this throws transient try void volatile

Java Naming Guidelines

1 CSC 103L – Introduction to Java


5
In addition to the naming rules, there are also guidelines, or conventions, that were
established by the authors of the Java API. If a guideline is not obeyed, your code will
compile, but it will be more difficult for you and others to read. Knowing these
guidelines, will help you understand code that uses Java API classes.

1. Identifiers: Choosing names that indicate the purpose of the class, method or
data value is known as self – documentation.

2. Class Names: begin with a capital letter, additional words are capitalized.
Examples: FirstClass, HelloWorld, JFrame, JOptionPane.

3. Variable Names: begin with a lower case letter, additional words are
capitalized. Examples: myWindow, visible, width, height, interestRate € Note:
no parentheses

4. Method Names: begin with a lower case letter, additional words are
capitalized. Examples: setTitle(),setSize(), showMessageDialog() € Note:
always parentheses

5. CONSTANTS: are completely capitalized, additional words are separated with


an underscore character _. Examples: PI,MAX_VALUE, INTEREST_RATE

At all times, you are expected to follow the Java guidelines for choosing
identifiers. Failure to do so will result in points being deducted.

1 CSC 103L – Introduction to Java


5
1 Syntax difference Between C++ and Java
0.

1 Program 01: “ Printing Hello World ” (1)


0 Class “MyFirstJavaProgram” has a function main. The main function calls a utility in
System class that displays the string ‘Hello World’

Execute this code and show the Output:

1 CSC 103L – Introduction to Java


5
1 Variables are constructs that allocate a memory location in RAM and place values in it. The
1 capability of a variable is the ability to vary.
.

eneral format is:

Data types in java are given here:


http://www.tutorialspoint.com/java/java_basic_datatypes.htm

1 CSC 103L – Introduction to Java


5
Program 02: Declaring and Initializing Variables in Java

1 CSC 103L – Introduction to Java


5
Execute this code and show the Output:

1 Program 03: Getting Input from User Using Scanner Class


2.

1 CSC 103L – Introduction to Java


5
Execute this code and show the Output:

1 Program 04: Instance Variables Declaration/Initialization


3.

1 CSC 103L – Introduction to Java


5
Execute this code and show the Output:

1 CSC 103L – Introduction to Java


5
1 Program 05: Write a Java program to display default value of all primitive data types (5)
4. of Java. Code:

package kamran;

public class Primitivevalues {


public static void main(String[] args) {

double v1 = 7; boolean
v2 = false;
int v3 = 9; float
v4 = 11; long v5
= 0; String v6 =
null;

System.out.println("values");
System.out.println("Val1 = " + v1);
System.out.println("Val2 = " + v2);
System.out.println("Val3 = " + v3);
System.out.println("Val4 = " + v4);
System.out.println("Val5 = " + v5);
System.out.println("Val6 = " + v6);
}

Output:

1 CSC 103L – Introduction to Java


5
1 Program 06: Write a Java program check if two strings are equal or not.
5. Code:

package kamran;

public class Comparestrings {


public static void main(String[] args) {

String style = "kami";


String style2 = "kami";

if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}

Output:

1 CSC 103L – Introduction to Java


5
1 Arithmetic Expressions are a construct made up of variables and operators which are
6. constructed according to the syntax of the language that evaluates to a single value.
int result = 1 + 2; // result is now 3

The expressions are same as in C/C++.


Java arithmetic operators are:

1 CSC 103L – Introduction to Java


5
The Relational operators are :

The logical operators are: -

1 CSC 103L – Introduction to Java


6
Program 07: Write javaprograms to give your ownexamples ofeach operator
given below:(Copied code will get you Zero Marks
)

1. Increment and decrement operators.


2. Bitwise Complement Operator.
3. Arithmetic operator.
4. Relational Operator
5. Bitwise operator.
6. Conditional Operator.

Code 01:
package kamran;

public class IncrementDecrement {


public static void main(String[] args)
{
int number = 100;
System.out.println("Numberis " + number);
number++;
System.out.println("Now, number after increment is " + number);
number--;
System.out.println("Now, number after decrement is " + number);
}
}

Output:

1 CSC 103L – Introduction to Java


8
Output:

Code 02:

package kamran;

public class Bitwiseoperators {


public static void main(String[] args)
{
int a = 3;
int b = 5;

System.out.println("a&b = " + (a & b));

System.out.println("a|b = " + (a | b));

System.out.println("a^b = " + (a ^ b));

Code 03:
System.out.println("~a = " + ~a);
package kamran;

public class Arithmaticoperator {


a &=static
public b; void main(String[] args) {
System.out.print ln("a= " + a);
} number1 = 10, number2 = 5;
int
}

int sum = number1 + number2;


System.out.println("Sum is: " + sum);

int difference = number1 - number2;


System.out.println("Difference is : " + difference);

int multiplication = number1 * number2;


System.out.println("Multiplied value is : " + multiplication);

int div = number1 / number2;


System.out.println("Quotient is : " + div);

int remainder = number1 % number2;


System.out.println("Remainder is : " + remainder);
21 CSC 103L – Introduction to Java
}

Output:

Code 04:

package kamran;

public class Relationaloperator {


public static void main(String[] args) {

int a = 51, b = 63;

System.out.println("a is " + a + " and b is " + b);


System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
}
}

21 CSC 103L – Introduction to Java


Output:

Code 05:

package kamran;

public class Bitwiseoperators {


public static void main(String[] args)
{
int a = 3;
int b = 5;

System.out.println("a&b = " + (a & b));

System.out.println("a|b = " + (a | b));

System.out.println("a^b = " + (a ^ b));

System.out.println("~a = " + ~a);

a &= b;
System.out.print ln("a= " + a);
}
21 CSC 103L – Introduction to Java
}

Output:

Code 06:

package kamran;

public class Conditionaloperators {


public static void main(String args[])
{
int x=4, y=8, z=3;
System.out.println(x>y && x>z || y<z);
System.out.println((x<z || y>z) && x<y);
}
}

Output:

2 CSC 103L – Introduction to Java


4
1 Control Structures and Loops
7.
1. Control statements/Conditional Branches

These are used to choose the path for execution. There are some types of control
statements:
• If statement
• If-else statement
• If-else if statement/ ladder if statements
• Switch statement

2. Loops in Java

These are used to iterate the instruction for multiple times.


• For loop
• While loop
• Do-while loop

3. Branching Statements in Java

These are used to alter the flow of control in loops.


• Break
• Continue

Reference Material Sources:

2 CSC 103L – Introduction to Java


4

Program 08: IF -Else Example

Execute and Show output of this Program:

Program 09: Nested If Statement

2 CSC 103L – Introduction to Java


4
Program 10 : Do -While Loop

Execute and Show output of this Program:

Execute and Show output of this Program:

Program 11 : Break Statement using For Loop

2 CSC 103L – Introduction to Java


8
Execute and Show output of this Program:

Program 12 : Write a java program to find the Cube of an integer number.

Code Here:

package kamran;

import java.util.*;

public class Cube {


public static void main(String args[]){
2 CSC 103L – Introduction to Java
8
System.out.println("Enter a number ::");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("Cube of the given number is "+(num*num*num));
}
}
OUTPUT:

Program 13: Write a java program to display the first 20 odd numbers.

Code Here:

package kamran;

public class Oddnumbers {


public static void main(String args[])
{
int n=40;
System.out.println(" first 20 odd numbers are" );
for(int a=0;a<=n;a++){
if(a%2!=0){
System.out.println(a+" ");
}
}
2 CSC 103L – Introduction to Java
8
}

}
OUTPUT

Program 13 : Write a java Program to check the input number is Prime or not

Code Here:

package kamran;

public class Primenumber {


public static void main(String[] args) {

int num = 29;


boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {

if (num % i == 0) {
flag = true;
break;
}
}

2 CSC 103L – Introduction to Java


8
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Output

Program 14 : Write a java Program to generate a Ladder of numbers.

Code Here:

package kamran;

public class Ladder {


public static void main(String args[])
{
int N=5;

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

System.out.println("3 3");
if(i<N){
System.out.println("3333333");
}
}
}
}
2 CSC 103L – Introduction to Java
8
Output

3 CSC 103L – Introduction to Java


4

Program 15: Write a program to give your own examples of control statements.

1. Nested for loop.


2. Nested If-else Statements
3. Do statements

Code Here:
1 nested for
Code
package kamran;

3 CSC 103L – Introduction to Java


4

if(marks>50){
System.out.println("pass");
public class Nestedfor {
if(marks<50){
public static void main(String args[])
System.out.println("fail");
} {
} int class1=1;
int students=10;
for(int i=1;i<=class1;i++){
Output System.out.println("class="+i);
for(int j=1;j<=students;++j){
System.out.println("student no"+j);
}
}
}
Output

3
Do statement
Code

package kamran;

public class Dostatement {


public static void main(String args[])
{
int i=0;
do
{
2 nested if System.out.println(i+" \n");
Code Web Resources
i++;
https://netbeans.org/downloads/
} kamran;
http://www.oracle.com/technetwork/java/javase/downloads/jdk
package -7-
netbeanswhile(i<=10);
download-432126.html http://www.learnjavaonline.org/
}
http://docs.oracle.com/javase/tutorial/
public class Nestedif {
} Video Resource
public http://www.youtube.com/watch?v=KheL6umdW
static void main(String args[]) -s
Output
http://www.youtube.com/watch?v=3MZIkY55fS0
{
http://www.learnerstv.com/Free
int marks=55; -Computers-Video-lectures-ltv006-Page1.htm
http://www.youtube.com/watch?v=Hv2yvXTVTVo

Summary: This is the basic tutorial of Java that allows the student to create basic Java
programs similar to C++/C. The programs include variables, arithmetic statements and
Operators , Control Structures – Loops.

32 CSC 103L – Introduction to Java


3/24/2021

Week 03 IET-OOP Lab

Java Arrays

Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, the elements of an
array are stored in a contiguous memory location. 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 0th index, and 2nd element is
stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
size of operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimensional or multidimensional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

Random access: We can get any data located at an index position.


3/24/2021
Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.

IET -OOP Lab 1012L 1/14

Types of Array in java

There are two types of array.

Single Dimensional Array

Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in


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

Instantiation of an Array in
Java
arrayRefVar=newdatatype[size];

Example of Java Array

Let's see the simple example of java array, here we are going to declare, instantiate, initialize and traverse
an array.

4/14
3/24/2021

//Java Program to illustrate how to declare, instantiate,


initialize
//and traverse the Java array.

class Testarray{
public static void main(String args[]){
int a[]= new int[ 5 ] ; //declaration and instantiation

a[ 0 ]= 10 ; //initialization
a[ 1 ]= 20 ;

a[ 2 ]= 70 ;

a[ 3 ]= 40 ;
a[ 4 ]= 50 ;
//traversing array

for( int i= 0 ;i<a.length;i++) //length is the property of

array System.out .println(a[i]);


}}

IET-OOP Lab 1012L 2/14

Code Output:

5/14
3/24/2021

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

inta[]={ 33,3,4,5} ; //declaration, instantiation and initialization

Let's see the simple example to print this array.

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
inta[]={ 33,3,4,5} ;//declaration, instantiation and initialization
//printing array
fo (inti=0;i<a.length;i++)//length is the property of array
rSystem.out.println(a[i]);
}}

Code
Output:

6/14
3/24/2021

For-each Loop for Java Array

7/14
3/24/2021
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one
by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

Let us see the example of print the elements of Java array using the for-each loop.

for( data_type variable:array ){


//body of the loop
}

//Java Program to print the array elements using-each


for loop
class Testarray1{
public static voidmain(String args[]){
in arr[]={ 33,3,4,5} ;
t//printing array using for
-each loop
fo (int i:arr)
rSystem.out.println(i);
}}

Code
Output:

8/14
3/24/2021

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

//Java Program to demonstrate the way of passing an array


//to method.
classTestarray2{
//creating a method which receives an array as a parameter
static voidmin(intarr[]){
intmin=arr[0];
fo (inti=1;i< arr.length;i++)
ri (min>arr[i])
fmin=arr[i];

System.out.println(min);
}

public static void main(String args[]){


inta[]={ 33,3,4,5} ; //declaring and initializing an array
min(a);//passing array to method
}}

Code Output:

9/14
3/24/2021

10/14
3/24/2021

Returning Array from the Method

11/14
3/24/2021
We can also return an array from the method in Java.

//Java Program to return an array from the method


classTestReturnArray{
//creating method which returns an array
static [] get(){
int
return new[]{ 10,30,50,90,60} ;
}int

public static void


main(String args[]){
//calling method which returns an array
intarr[]=get();
//printing the values of
an array
fo (inti=0;i<arr.length;i++)
r
System.out.println(arr[i]);
}}

CodeOutput
:

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

12/1
4
3/24/2021
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
in [][] arr= new [3][3];//3 row and 3 column
t int
Example to initialize Multidimensional Array in
Java
arr[0][0]= 1;
arr[0][1]= 2;
arr[0][2]= 3;
arr[1][0]= 4;
arr[1][1]= 5;
arr[1][2]= 6;
arr[2][0]= 7;
arr[2][1]= 8;
arr[2][2]= 9;

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

13/1
4
3/24/2021

//Java Program to illustrate the use of multidimensional array


classTestarray3{
public static voidmain(String args[]){
//declaring and initializing 2D array
intarr[][]={{ 1,2,3} ,{ 2,4,5} ,{ 4,4,5}} ;
//printing 2D array
fo (inti=0;i< 3;i++){
r (intj=0;j< 3;j++){
fo
r System.out.print(arr[i][j]+
" ");
}
System.out.println();
}
}}

Code Output:

Jagged Array in Java

If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is
an array of arrays with different number of columns.

14/1
4
3/24/2021

//Java Program to illustrate the jagged array


class TestJaggedArray{
public static void
main(String[] args){
//declaring a 2D array with odd columns
intarr[][] = newin[3][];
arr[0] = new [3t];
arr[1] = int
new [4];
int in [2];
arr[2] = ne
w at jagged array
//initializing
intcount = 0;
for(inti=0; i<arr.length; i++)
fo (intj= 0; j<arr[i].length; j++)
r arr[i][j] = count++;

//printing the data of a jagged array


for(inti=0; i<arr.length; i++){

for(intj=0; j<arr[i].length; j++){


System.out.print(arr[i][j]+" ");
}
System.out.println();
//new line
}
}
}

Code
Outpt
u :

15/1
4
3/24/2021

Copying a Java Array

We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method

public static voidarraycopy(


Object src,intsrcPos,Object dest,intdestPos, intlength
)

Example of Copying an Array in Java

16/1
4
3/24/2021

//Java Program to copy a source array into a destination array in Java


class TestArrayCopyDemo {
public static void
main(String[] args) {
//declaring a source array
cha[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
r 'i', 'n', 'a', 't', 'e', 'd' } ;
//declaring a destination array
cha[] copyTo = new [7];
r
//copying array char
using System.arraycopy() method
System.arraycopy(copyFrom,
2, copyTo,0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}

Code Output:

Cloning an Array in Java

Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we
create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will
copy the actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of
the Java array which means it copies the references.

17/1
4
3/24/2021

//Java Program to clone the array


class Testarray1{
public static oidmain(String args[]){
v arr[]={ 33,3,4,5} ;
int
System.out.println(
"Printing original array:"
);
fo (inti:arr)
rSystem.out.println(i);

System.out.println(
"Printing clone of the array:"
);
intcarr[]=arr.clone();
fo (inti:carr)
r
System.out.println(i);

System.out.println(
"Are both equal?"
);
System.out.println(arr==carr);

}}

Code Output:

18/1
4
3/24/2021

Addition of 2 Matrices in Java

19/1
4
3/24/2021
Let's see a simple example that adds two matrices.

//Java Program to demonstrate the addition of two matrices in Java


classTestarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{ 1,3,4} ,{ 3,4,5}} ;
int b[][]={{ 1,3,4} ,{ 3,4,5}} ;

//creating another matrix to store the sum of two matrices


int c[][]= new int [2][ 3];

//adding and printing addition of 2 matrices


for(int i= 0;i< 2;i++) {
for(int j= 0;j< 3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+ " ");
}
System.out.println(); //new line
}

}}

Code Output:

20/1
4
3/24/2021
Multiplication of 2 Matrices in Java

In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns
of the second matrix which can be understood by the image given below.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

21/1
4
3/24/2021

//Java Program to multiply two matrices


public class MatrixMultiplicationExample{
public static voidmain(String args[]){
//creating two matrices
in a[][]={{ 1,1,1} ,{ 2,2,2} ,{ 3,4,3}} ;
tin b[][]={{ 1,1,1} ,{ 2,2,2} ,{ 3,4,3}} ;
t
//creating another matrix to store the multiplication of two matrices
intc[][]= new [3][3]; //3 rows and 3 columns
int
//multiplying and printing multiplication
of 2 matrices
fo (int i=0;i< 3;i++){
r (intj=0;j< 3;j++){
fo
r
c[i][j]= 0;
fo (intk=0;k< 3;k++)
r{
c[i][j]+=a[i][k]*b[k][j];
} //end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
} //end of j loop
System.out.println();
//new line
}
}}

Code Output:

22/1
4
3/24/2021

Lab Exercise:

1. Declare three arrays of two dimensional of size m and n that is a[][],b[][] and c[][].

2. Read the values into a[][] array and b[][] array.

3. Compute multiplication and store the product in c[][] array by using c[i][j]=c[i][j]+a[i][k]*b[k][j];

4. Print the result.

public class Exercise {

public static void main(String args[]){

23/1
4
3/24/2021

int a[][]={{3,2,1},{4,1,3},{1,2,1}}; int b[][]={{3,6,8},{2,5,2},{2,3,4}};

int c[][]=new int[3][3];

for(int m=0;m<3;m++){ for(int n=0;n<3;n++){ c[m][n]=0; for(int k=0;k<3;k++)

c[m][n]+=a[m][k]*b[k][n];

System.out.print(c[m][n]+" ");

System.out.println();

}}

Output

24/1
4
3/24/2021

PROJECT –OBJECT ORIENTED PROGRAMMING - PHASE – I

MAXIMUM MARKS: 10
DEADLINE: After OHT - I
Instructions
 This is a project assignment and is based on some of the lab experiments
carried out by you.
 Plagiarism is strictly forbidden.
 You have to create the project for the given language specification.
 You have to show the working project for evaluation before deadline.

25/1
4
3/24/2021
 The evaluation is based on project demonstration, working of the project
for different test patterns and associated viva.
 Project will be graded as a syndicate effort.
1. Objectives:
(a). Syndicate formation
(b). Project proposal
2. Programming Language: Java
3. Software Required: NetBeans/Kawa/Eclipse/JCreator
4. TASK
You are required to create a project proposal identifying what kind of project
you are going to develop. The project proposal must have the following
(a). Abstract statement
(b). Some functional requirements i.e., what the project will do
(c). A snapshot of how will the GUI look like
(d). Hard copy of proposal

26/1
4
3/24/2021
PROJECT –OBJECT ORIENTED PROGRAMMING - PHASE – II

OOP Term Project Details


MAXIMUM MARKS: 20
DEADLINE: Before final lab
Programming Language Java
Software Required: NetBeans/Kawa/Eclipse/JCreator

Goal: In this course our main goal is to learn how to build and evolve small to large-scale programs using object-
oriented programming, and work in teams learning from each other.

Topics: In exploring object-oriented programming, we investigate three questions:

1. Design
2. Primitives
3. Implementation

In Design, how do we think about a program in terms of objects? To answer this question, we explore CRC
cards, UML, and design patterns.

In Primitives, how do we express object orientation in terms of encapsulation, abstraction, inheritance and
polymorphism? To answer this question, we explore classes, interfaces, method dispatch, method overriding,
generics, operator overloading, and reflection, etc.

In Implementation, how do we realize object-oriented primitives? To answer this question, we explore dynamic
method dispatch, garbage collection and automatic memory management in detail.

Design and primitives matter because they represent the essence of object-oriented programming.
Implementation matters because it enables us to debug object-oriented programs and tune their performance.

General Rules:

1. A group can be formed from 3 or 4 students per project.


2. Groups are not allowed to repeat ideas.
3. Groups can select projects from the given list or they are welcome to bring with their own ideas.

27/1
4
3/24/2021
Submission Method:

All project files are zipped and submitted named as “proj_LeaderStudentID.zip”, where “LeaderStudentID” is
replaced by a leader team member chosen by all team members. The zip file should contain:

1. All source code used to develop the project, either as a rar file, or a folder of the project packages and
files.
2. A Design document contains a class diagram describing the project classes, and associations, and one
paragraph describing the methods, one paragraph as a user manual, and one paragraph describing team
member’s individual contributions.

Grading Criteria:

The project is worth 20% of your final mark. These marks are graded individually by asking each student in the
presentation for their contribution and testing their understanding.

These are broken into:

1. 10 marks for correctness (no compilation or run-time errors).


2. 8 marks for the application of course concepts, where feasible, (such as: modularity, inheritance,
polymorphism, method overriding and overloading, abstract classes & interfaces)
3. 2 marks for GUI interfaces, presentation, documentation, and teamwork.
4. 10 bonus marks for all other concepts you self-study outside the learning objectives of the course.

List of Sample Projects


Serial # Name of Project

1 Course Registration Application


2 Chess Game
3 Text Editor
4 Online Quiz Application
5 Document Management Application
6 Bank Management Application
7 Library Management Application
8 Cafe Management Application
28/1
4
3/24/2021
9 Cyber Cafe Management Application
10 Project Management Application
11 Graphics Editor Application
12 Staff Management Application
13 Brick Game
14 Soft piano
15 Paranoid Game

29/1
4
3/24/2021
Sample Project Details
1. Bank Management System:

Develop an application to help a bank manager manage customer accounts. The bank offer several bank
accounts types. Each customer can have one or more accounts. The customer can go to the operations
permitted by the account type, such as deposit, withdraw, or balance enquire. The bank manages the account
by debiting the fees, or crediting the profits. Both the bank employees and the customers can print reports
about the current account details.

Design:

Basic Classes: Account, CheckingAccount, SavingAccount, Loan, Customer:

A. The Account is a general account class that contains balance as instance variable, deposit,
withdraw, and balanceEnquiry as instance methods.
B. Checking Account is a subclass from the Account class that allows overdraft while withdrawing
(making the balance go below zero up to the specified credit limit), by debiting the account
balance with an overdraft fee. It has a creditlimit as an instance variable.
C. The Saving Account is a subclass from the Account class that has an interest rate as an instance
variable. The system credit the balance with monthly interest based on the account balance and
the interest rate.
D. The loan account is a subclass from the Account class that has principal amount, interest rate,
loan duration in months as instance variables. The loan balance is debited by monthly interest
each month based on the interest rate and the loan balance.
E. Each customer can have any number of accounts of any type.
F. The banking system provide the customer with an interface to access all banking operations
described above and review reports about transactions and current balance.
G. A banking administrator can print a report about all customers and their current balances.

Provides an interface for the user to:

1. Adding/editing/deleting GUI to each class,


2. GUI for Customers to open a new account
3. GUI for Customers to view transactions and balance for all their accounts.
4. GUI for a administrator to view all customer balances.

30/1
4
3/24/2021
Sample data include:

customers.txt

Customer ID Name Address Phone Email


1 Mohamed … … …
2 Ahmed … … …
3 Mostafa … … …

accounts.txt

Loan
Account ID Customer ID Type Balance CreditLimit or Principal Duration

Interest Rate Amount

1 1 Saving …

2 1 Loan …
Checking
3 2 Account …

accountTransactions.txt

Account ID Date Time Transaction Type Amount Transaction Type


1 9/1/2013 Withdraw … Withdraw
1 … Deposit … Rowing machine
2 … Interest … Ab Rolller

3 … Fees …

31/1
4
3/24/2021

“I hear and I forget,


I see and I remember,
I do and I understand”

Confucius

“A scientist in his laboratory is not a mere


technician: he is also a child confronting natural
phenomena that impress him as though they were
fairy tales.”

Marie Curie

32/1
4

You might also like