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

Lab Manual OOP-1

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

Lab Manual OOP-1

Lab manual
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Faculty of Computer

Science & Information


Technology
Benazir Bhutto Shaheed University,
Lyari Karachi

COURSE DESCRIPTION
Course Title: Object Oriented Programming

Offered to: BS (cs) 2nd Semester Section (A)

Credit Hours: (4) 3+1

Pre-requisite: none

Instructor: * Mr. Abdullah

Office Location: * Faculty, CS& IT

Email Address: * [email protected]


Reference:
1. An Introduction to Object-Oriented Programming with Java, C. Thomas Wu (2010).
5th Edition. McGraw-Hill. ISBN: 9780073523309

2. Java: How to Program, 5/e, Deitel and Deitel, Prentice Hall, 0131016210/
0131202367 International Edition.

Week Lab Topic

1 Task 1 Basic Installation of java, guide for choosing IDE


(Basic programs)

2 Task 2 OOP Operators

5 Task 5 Function/Method

6 Task 6 Constructor/Destructor

7 Task 7 Abstraction

8 Task 8 Encapsulation

9 Task 9 Polymorphism

10 Task Inheritance
10

12 Task Overloading
12

13 Task Overriding
13

Final Exam
Installing Java Extension Pack in VS
Code:
 Install VS Code:
 Download and install Visual Studio Code from https://code.visualstudio.com/.
 Open VS Code:
 Open VS Code on your computer.
 Install Java Extension Pack:
 Go to the Extensions view by clicking on the Extensions icon in the Activity
Bar on the side of the window (or use Ctrl+Shift+X).
 Search for "Java Extension Pack" and install it.
 Install Java Development Kit (JDK):
 Ensure that you have a JDK installed on your system.
 Set the JAVA_HOME environment variable to point to the JDK installation
directory.
 Create a Java Project:
 Open the Command Palette (Ctrl+Shift+P) and type "Java: Create Java
Project."
 Follow the prompts to create a new Java project.
 Write a Basic Java Program:
 Open the created project.
 Inside the src folder, create a new Java file (e.g., HelloWorld.java).
 Write a simple "Hello World" program.

SOURCE CODE:
OUTPUT :
Hello World

ffjjjf
}

Data Types in Java:


 byte:
 A byte is a data type that can store whole numbers from -128 to 127.int:
 An int is a data type that can store whole numbers from -2^31 to 2^31 - 1.
 short:
 A short is a data type that can store whole numbers from -32,768 to 32,767.
 long:
 A long is a data type that can store whole numbers from -2^63 to 2^63 - 1.
 char:
 A char is a data type that can store a single 16-bit Unicode character
 float:
 A float is a data type that can store fractional numbers.
 (Note: f at the end indicates it's a float.)
 double:
 A double is a data type that can store larger fractional numbers with more
precision.
 (Note: d at the end indicates it's a double, though it's optional.)
SOURCE CODE :

OUTPUT:
1010010100010001000.111100111011011011011
1010010100010001000.1111001110110
11011011

This Java program is similar to the previous one, but instead of using
System.out.print(), it uses System.out.println() for each variable. The println
method appends a newline character after printing, so each value will be on a new
line

SOURCE CODE:
10

100

10

1000

Dividing each by 8 gives the size in bytes. The program then prints these sizes with
appropriate labels.

SOURCE CODE :

the size of byte is1byte

the size of short is2byte

the size of integer is4byte

the size of float is4byte

the size of long is8byte

the size of character is2byte


SCANNER :

Importing Scanner: Importing the


Scanner class for user input.
 Main Method: The entry point of the program.
 Creating a Scanner Object: Creating a Scanner object to read user input.
 User Input: Prompting the user to enter values for variables 'a' and 'b' and
reading the input.
 Calculation: Calculating the sum of 'a' and 'b'.
 Output: Printing the calculated sum to the console.
 Closing Scanner: Closing the Scanner object to release resources

SOURCE CODE:
Enter the value of a:

10

Enter the value of b:

20

30

SOURCE CODE:
Enter the value of a:

10

Enter the value of b:

20

200
Enter the value of a:

10

Enter the value of b:

20

SOURCE CODE :

:
Enter the value of a:

10

Enter the value of b:

20

10

SOURCE CODE :

Enter the value of a:

10

Enter the value of b:

20

0
Enter the value of a:

10

Enter the value of b:

Sum: 13

Difference: 7

Product: 30

Quotient: 3

1. Assignment Operators:
 = (Assignment): Assigns the value on the right to the variable on the left.
 +=, -=, *=, /=, %= (Compound Assignment): Performs the operation and
assigns the result to the left operand.

SOURCE CODE :

Output 10
OUTPUT : 2

OUTPUT :
The value of X is 10
OUTPUT = 2

Source code :

Output = 30
Output =10

Output =200
Output = 2

Output = 0

AIRTHMATIC OPERATOR :
Output 10 .

Source code

s Output : 200

Output 2 .
Output : 0 .

2. Relational Operators:
 == (Equal to): Checks if two values are equal.
 != (Not equal to): Checks if two values are not equal.
 > (Greater than): Checks if the left operand is greater than the right
operand.

 < (Less than): Checks if the left operand is less than the right operand.
 >= (Greater than or equal to): Checks if the left operand is greater than
or equal to the right operand.
 <= (Less than or equal to): Checks if the left operand is less than or equal
to the right operand.
Output : The a is greater
OUTPUT =

3. Logical Operators:
 && (Logical AND): Returns true if both conditions are true.
 || (Logical OR): Returns true if at least one of the conditions is true.
 ! (Logical NOT): Returns true if the condition is false, and vice versa
Output =

Output = login

Output = logout

5. Increment and Decrement Operators:


 ++ (Increment): Increases the value of a variable by 1.
 -- (Decrement): Decreases the value of a variable by 1.
Output =11

Output = 9
TERNARY OPERATOR :

OUTPUT = b is greater

OUTPUT =

STRING:
In Java, a String is a class that represents a sequence of characters. It is one of the
built-in classes in Java, and it is widely used to manipulate and represent textual
data. Strings in Java are immutable, meaning that their values cannot be changed
after they are created. This immutability property makes strings safe for use in
various applications, such as multithreading.
Output= humna

Different string value

Output = humnaallauddin
Output = Enter a string Humna

Humna

Output =

enter string

Hello, Java!

12

 . The trim() method removes those spaces, and the program then prints the
modified string,
Output = enter
string

Hello, Java!

Hello, Java!

Output = Enter string:

Hello, Java!

hello, java!
Output= enter string

Hello, Java!

HELLO, JAVA!

Output= enter string

Java Programming

1
Output =

FUNCTION / METHOD

returnType: The data type of the value the method returns. It can be a
primitive type, an object, or void if the method does not return anything.
 methodName: The name of the method, which is used to call it.
 parameterType1, parameterType2, ...: The data types of the parameters
that the method accepts (if any).
 parameterName1, parameterName2, ...: The names of the parameters
used within the method body.
 Method body: The block of code that defines the behavior of the method.
 return returnValue;: The return statement is used to return a value from
the method. The data type of the value must match the method's declared
return type.
 main method: The main method is the entry point of a Java program. It is
called when the program starts executing
Output:

Square of 5 is: 25

Output =

Before swapping: num1 = 5, num2 = 10

Swapped values: num1 = 10, num2 = 5

After swapping: num1 = 10, num2 = 5


Output = Maximum number between 5 and 10 is: 10

Output = 10
Ambiguous Bcz ssme name

Output= error: method max(int,int) is already defined in class Code57

SCOPE OF LOCAL VARIABLE :

Output = Value of x: 46
Value of y: 46

GLOBAL VARIABLE :
Output = The value of x after the loop: 56

ARRAY:

Output = 20
Output = 20

Output =

3
4

10

11

12

13

14

15

CONSTRUCTOR AND DESTRUCTOR


CONSTRUCTOR :
Constructors:
In object-oriented programming, a constructor is a special method or function that
is automatically called when an object is created. It is used to initialize the object's
state. The purpose of a constructor is to set up the initial values for the object's
attributes or properties. Constructors have the same name as the class and do not
have a return type.

There are different types of constructors:

 Default Constructor:
 Automatically generated if no constructor is defined.
 Takes no parameters.
 Initializes the object with default values.

Output = Constructor is called

Parameterized Constructor:
 Takes parameters to initialize the object with specific values.
Output = Make: Toyota

Model: Camry

Year: 2022

Overloading Constructor :

Constructor overloading is a concept in object-oriented programming where a class


can have multiple constructors with different parameter lists. Each constructor
provides a different way to initialize an object of the class. The choice of which
constructor to use depends on the number and types of arguments provided when
creating an instance of the class.
Output =

10

12

DESTRUCTORS:
A destructor is another special method or function that is called when an object
goes out of scope or is explicitly deleted. It is used to release resources, such as
memory, that were allocated for the object during its lifetime. Destructors have the
same name as the class preceded by a tilde (~), and they do not take any
parameters.
ABSTRACTION :
bstraction is one of the four fundamental Object-Oriented Programming
(OOP) principles, along with encapsulation, inheritance, and polymorphism.
Abstraction refers to the concept of hiding the complex implementation
details and showing only the essential features of an object. In Java,
abstraction can be achieved through abstract classes and interfaces.

 Abstract Classes:
 An abstract class is a class that cannot be instantiated on its own and
may contain abstract methods.
 Abstract methods are declared without providing an implementation in
the abstract class.
 Abstract classes can also have concrete methods (methods with an
implementation).
 To declare an abstract class, you use the abstract keyword.

Source code :
Output = running safely

(Abstraction without good programming)

Output = Bike Constructor


Honda Constructor
running safely
Head lights are ON

Output : welcome to the portal of Employee management


welcome Employee

Output = welcome to the portal of Employee management


welcome Employee
 Encapsulation:
 Encapsulation is one of the four fundamental principles of Object-
Oriented Programming (OOP), along with abstraction, inheritance, and
polymorphism. It refers to the bundling of data (attributes) and
methods that operate on the data into a single unit called a class.
Encapsulation helps in hiding the internal implementation details of an
object and allows access to the object's state only through public
methods (getters and setters). In Java, encapsulation is achieved
through the use of access modifiers and getter and setter methods.
 Here's a breakdown of how encapsulation is implemented in Java:
 Access Modifiers:
 Java provides three access modifiers: public, private, and protected.
 These access modifiers control the visibility of variables and methods
in a class.
 private members are only accessible within the same class, while
public members can be accessed from any class.
 Private Variables:
 Encapsulation involves declaring the class variables (fields) as private
to restrict direct access.
 Access to these private variables is provided through public methods,
typically getter and setter methods.
Output = welcome to BBSUL Student portal
1234
Zaid
Output = the area square is:25

Output =
Welcome to Campus Management Solution Portal
The UserName is :Zaid

Code no # 85 (fully encapsulation class for bank management )


class Bankmanagement {
private long acc;
private String name,email;
private int pin;
Bankmanagement()
{
System.out.println("Welcome to the bank management portal"); }
public void setAcc(long a) {
this.acc = a; }
public long getAcc() {
return acc; }
public void setName(String n) {
this.name = n; }
public String getName() {
return name; }
public void setEmail(String e) {
this.email = e; }
public String getEmail(){
return email;
}
public void setPin(int p)
{
this.pin=p;
}
public int getPin(){
return pin;
}
}
public class Encapsulation
{
public static void main(String agrs[])
{
Bankmanagement BM1 = new
Bankmanagement();
BM1.setAcc(12400121);
BM1.setName("Zaid");
BM1.setEmail("[email protected]");
BM1.setPin(1234);
System.out.println(BM1.getAcc());
System.out.println(BM1.getName());
System.out.println(BM1.getEmail());
System.out.println(BM1.getPin());
} }
Output =
Welcome to the bank management portal
12400121
Zaid
[email protected]
1234

Inheritence :
Inheritance is a fundamental concept in object-oriented programming
(OOP) that allows a class (subclass/child class) to inherit properties and
behaviors from another class (superclass/parent class). In Java, inheritance is
implemented using the extends keyword.

Key Points:

 Syntax:
Types of Inheritance:
 Java supports both single and multilevel inheritance.
 Single Inheritance: A class can inherit from only one superclass.
 Multilevel Inheritance: A class can inherit from a superclass, and
another class can inherit from the derived class.

Output = This animal eats food.


The dog barks.

Polymorphism
Polymorphism in Java is a fundamental concept in object-oriented
programming (OOP) that allows objects to be treated as instances of their
parent class rather than their actual class. Polymorphism can be achieved
through method overloading and method overriding.

Types of Polymorphism in Java:


 Compile-Time Polymorphism (Static Binding or Method
Overloading):
 Occurs at compile time.
 Multiple methods with the same name but different parameters in the
same class or different classes in the same inheritance hierarchy.
 Resolved during the compilation phase.
 Also known as method overloading.

Output =

Run-Time Polymorphism (Dynamic Binding or Method Overriding):


 Occurs at runtime.
 The same method signature in both parent and child classes, where
the child class provides a specific implementation.
 Resolved during the runtime phase.
 Also known as method overriding.

Example code :

Output = Woof! Woof!

Overloading:
Explanation:

 This code snippet demonstrates method overloading, where multiple


methods have the same name but a different number or type of
parameters.
 Polymorphism in the form of method overloading allows methods with
the same name to handle different types or numbers of parameters.
 The output will be: 6 8 10

Overriding :
Explanation:

 This code snippet demonstrates method overriding, where a child class


provides a specific implementation for a method that is already defined
in its parent class.
 Polymorphism in the form of method overriding allows a subclass to
provide a specific implementation of a method defined in its
superclass.
 The output will be: I'm method of child class

THE END

You might also like