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

OOP_Lab.docx

The document outlines a series of Java programming experiments focusing on user input, conditional statements, loops, arrays, class mechanisms, constructors, and inheritance. Each experiment includes code examples, expected results, and explanations of key concepts such as the Scanner class for input, array usage, class definitions, and constructor types. The content is structured to provide practical programming exercises for learning Java fundamentals.

Uploaded by

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

OOP_Lab.docx

The document outlines a series of Java programming experiments focusing on user input, conditional statements, loops, arrays, class mechanisms, constructors, and inheritance. Each experiment includes code examples, expected results, and explanations of key concepts such as the Scanner class for input, array usage, class definitions, and constructor types. The content is structured to provide practical programming exercises for learning Java fundamentals.

Uploaded by

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

Experiment No.

01:

Experiment Name / Title: Write a Java program to print Text on screen and Assigned
variables to perform basic operation.

Java User Input (Scanner): The Scanner class is used to get user input, and it is found in
the java.util package. To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read Strings:

Input Types:
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:

Method​ Description
nextBoolean()​Reads a boolean value from the user
nextByte()​ Reads a byte value from the user
nextDouble()​ Reads a double value from the user
nextFloat()​ Reads a float value from the user
nextInt()​ Reads a int value from the user
nextLine()​ Reads a String value from the user
nextLong()​ Reads a long value from the user
nextShort()​ Reads a short value from the user

Code: Ex-1
public class Exercise1 {
public static void main(String[] args) {
// Print a greeting message to the console
System.out.println("Hello\nAlexandra Abramov!");
}
}
Result: Hello
Alexandra Abramov!

Ex-2:
Sample solution using input from the user:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner input = new Scanner(System.in);
// Prompt the user to input their first name
System.out.print("Input your first name: ");
String fname = input.next();
// Prompt the user to input their last name
System.out.print("Input your last name: ");
String lname = input.next();
// Output a greeting message with the user's full name
System.out.println();
System.out.println("Hello \n" + fname + " " + lname);
}
}
Result:
Input your first name: James
Input your last name: Smith

Hello
James Smith
Ex-3: A Java program to print the sum of two numbers:

public class Exercise2 {


public static void main(String[] args) {
// Calculate the sum of 24 and 26
int sum = 24 + 26;
// Print the result of the addition
System.out.println(“Sum=”+sum);
}
}

Sum: 50.
Ex- 4: Write a Java program that takes a number as input and prints its multiplication table up to
10.
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);
// Prompt the user to input a number
System.out.println("Input the Number: ");

// Read and store the input number


int n = in.nextInt();

// Use a loop to generate and print the multiplication table for the input number
for (int i = 1; i <= 10; i++) {
// Calculate and print the result of n multiplied by i
System.out.println(n + "*" + i + " = " + (n * i));
}
}
}
Results: Input the Number:
6
6*1 = 6
6*2 = 12
6*3 = 18
6*4 = 24
6*5 = 30
6*6 = 36
6*7 = 42
6*8 = 48
6*9 = 54
6*10 = 60
Ex- 5: Write a Java program to print the area and perimeter of a rectangle.
public class Exercise13 {
public static void main(String[] strings) {
// Define constants for the width and height of the rectangle
final double width = 5.6;
final double height = 8.5;

// Calculate the perimeter of the rectangle


double perimeter = 2 * (height + width);
​ ​
// Calculate the area of the rectangle
double area = width * height;​ ​ ​
// Print the calculated perimeter using placeholders for values
System.out.printf("Perimeter is 2*(%.1f + %.1f) = %.2f \n", height, width, perimeter);

// Print the calculated area using placeholders for values


System.out.printf("Area is %.1f * %.1f = %.2f \n", width, height, area);
}
}
Result: Perimeter is 2*(8.5 + 5.6) = 28.20
Area is 5.6 * 8.5 = 47.60

Experiment No. 02:


Experiment Name / Title: Write a program to implement Conditional statement, loop and
array in Java.

Array:

An array is a group of similar typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an array is
accessed by its index. The array is a simple type of data structure which can store primitive
variables or objects. For example, imagine if you had to store the result of six subjects we can do
it using an array. To create an array value in Java, you use the new keyword, just as you do to
create an object.
Defining and constructing one dimensional array

Code: Ex-1: Write a Java program to get a number and print whether it is greater .

public class Main {

public static void main(String[] args) {


int x = 20;

int y = 18;

if (x > y) {

System.out.println("x is greater than y");

Result:

x is greater than y

Code: Ex-2: Write a Java program to get a number from the user and print whether it is positive
or negative.

Test Data​
Input number: 35​
Expected Output :​
Number is positive

import java.util.Scanner;
public class Exercise1 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int input = in.nextInt();

if (input > 0)
{
System.out.println("Number is positive");
}
else if (input < 0)
{
System.out.println("Number is negative");
}
else
{
System.out.println("Number is zero");
}
}
}

Result:

Input number: 35

Number is positive

Ex-3: Write a Java program that takes a number from the user and generates an integer between
1 and 7. It displays the weekday name.
import java.util.Scanner;
public class Exercise5 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int day = in.nextInt();

System.out.println(getDayName(day));
}

// Get the name for the Week


public static String getDayName(int day) {
String dayName = "";
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default:dayName = "Invalid day range";
}

return dayName;
}
}
Sample Output:
Input number: 3
Wednesday

Ex-4: Java Program to demonstrate the example of for loop which prints 1 to 10.
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);

}
}
}
Result: 1 2 3 4 5 6 7 8 9 10
Ex-5: This program will help to understand initializing and accessing specific array elements:
import java.util.Arrays;
public class ResultListDemo {
​ public static void main(String[] args) {
​ ​ //Array Declaration
​ ​ int resultArray[] = new int[6];
​ ​ //Array Initialization​ ​
​ ​ ​ ​ resultArray[0]=69;
​ ​ ​ ​ resultArray[1]=75;
​ ​ ​ ​ resultArray[2]=43;
​ ​ ​ ​ resultArray[3]=55;
​ ​ ​ ​ resultArray[4]=35;
​ ​ ​ ​ resultArray[5]=87;
​ ​ //Array elements access​
​ ​ System.out.println("Marks of First Subject- "+ resultArray[0]);
​ ​ System.out.println("Marks of Second Subject- "+ resultArray[1]);
​ ​ System.out.println("Marks of Third Subject- "+ resultArray[2]);
​ ​ System.out.println("Marks of Fourth Subject- "+ resultArray[3]);
​ ​ System.out.println("Marks of Fifth Subject- "+ resultArray[4]);
​ ​ System.out.println("Marks of Sixth Subject- "+ resultArray[5]);
​ }
}
Experiment No. 03:
Experiment Name / Title: To write a JAVA program to implement class mechanism.
Create a class, methods and invoke them inside main method
class:
a class describes the contents of the objects that belong to it: it describes an aggregate of
data fields (called instance variables), and defines the operations (called methods).
object:
an object is an element (or instance) of a class; objects have the behaviors of their class.
The object is the actual component of programs, while the class specifies how instances
are created and how they behave.
method:
a method is an action which an object is able to perform.
sending a message
sending a message to an object means asking the object to execute or invoke one of its
methods.

Ex-1:

class A
{
int l=10,b=20;
void display()
{
System.out.println(l);
System.out.println(b);
}
}
class method demo{
public static void main(String args[]){
A a1=new A();
a1.display();
}
}
Output:
10
20

Ex-2: Print Volume of a box by creating a ‘Box’ name class in Java.


public class Box {
double h;
double w;
double l;
void volume()
{
System.out.println("Volume is ");
System.out.println(w*h*l);
}
}
public class Javalab52c5a {
public static void main(String[] args) {
Box myBox1=new Box();
myBox1.w=10;
myBox1.h=20;
myBox1.l=15;
myBox1.volume();
}
}
Result: Volume is: 3000

Ex-3: Print Area of a circle and a rectangle by creating a ‘test’ class in Java.
package javalab52c5b;
public class test {
double pi;
double r;
double l;
void Circle()
{
System.out.print("Area of Circle is:");
System.out.println(pi*r*r);
}
void Rectangle()
{
System.out.print("Area of Rectangle is: ");
System.out.println(r*l);
}
}

package javalab52c5b;
public class Javalab52c5b {
public static void main(String[] args) {
test mytest1=new test();
test mytest2=new test();
mytest1.pi=3.14;
mytest1.r=5;
mytest2.r=5;
mytest2.l=4.5;
mytest1.Circle();
mytest2.Rectangle();
}
}
Ex-4: An example of parameterized method in Java

class Main {

// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}

public static void main(String[] args) {

int num1 = 25;


int num2 = 15;

// create an object of Main


Main obj = new Main();
// calling method
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result);
}
}

Ex-5: An example of parameterized method with return type in Java.


class Main {

// create a method
public static int square(int num) {

// return statement
return num * num;
}

public static void main(String[] args) {


int result;

// call the method


// store returned value to result
result = square(10);

System.out.println("Squared value of 10 is: " + result);


}
}

Experiment No. 04:

Experiment Name / Title: Implementation of Constructor Method in Java.


Theory: In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory. It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called. It
calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

Rules for creating Java constructor:


There are three rules defined for the constructor.

1.​ Constructor name must be the same as its class name


2.​ A Constructor must have no explicit return type
3.​ A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors:


There are two types of constructors in Java:

1.​ Default constructor (no-arg constructor)


2.​ Parameterized constructor

Code:
Ex-1: Example of default constructor: In this example, we are creating the no-arg constructor in
the Bike class. It will be invoked at the time of object creation.

class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

OutPut:

Bike is created

Ex-2: The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type:

class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
OutPut:

0 null
0 null
Ex-3: Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Ayan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

OutPut:
111 Ayan
222 Aryan

Experiment No. 05:

Experiment Name / Title: Implementation of Inheritance in Java

Theory:
Inheritance:
1.​ Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
2.​ The class which inherits the properties of other is known as subclass
(derived class, child class) and the class whose properties are inherited is
known as superclass (base class, parent class).

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


child relationship.

4.​ extends is the keyword used to inherit the properties of a class.


It indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
5.​ Child class share property and behavior from parent.

Code:

Ex-1: Single Inheritance Example


Print Name,Age,ID and Department by creating class “Human” and “Student” in java. Here class
Human contain Name and age variable and Student class contain Department and ID .Where
Human is parent class.​
Class Human:
package javalab52c6aa;
public class Human {
String Name;
int Age;
}
Class Student:
package javalab52c6aa;
public class Student extends Human{
String Department;
int ID;
public void printInfo()
{ System.out.println("Name :"+Name);
System.out.println("Age :"+Age);
System.out.println("Department:"+Department);
System.out.println("ID :"+ID);
}}
Main method:
package javalab52c6aa;
public class Javalab52c6aa {
public static void main(String[] args) {
Human h1=new Human();
Student s1=new Student();
s1.Name="Arpa";
s1.Age=20;
s1.Department="CSE";
s1.ID=1102;
s1.printInfo();
}
}​
Result:
Name:
Age:
ID:
Depertment:
Ex-2: Multilevel Inheritance Example

class Animal
{
void eat()
{
System.out.println("eating...");
}

}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}

Ex-3: Hierarchical Inheritance:


class Animal
{
void eat()
{
System.out.println("eating...");
}
}

class Dog extends Animal


{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
}
}
Ex-4: Implement this example:

public class Shape {


private int location;
public Shape(int location) {
this.location = location;
}
public void display() {
System.out.println("Location: "+location);
}
}
public class Rectangle extends Shape {
private int height;
private int width;
public Rectangle(int height, int width, int location) {
super(location);
this.height = height;
this.width = width;
}
public void display() {
super.display();
System.out.println("Height " + height + " width " + width);
}
public static void main(String[] args) {
Rectangle r = new Rectangle(10, 5, 5);
r.display();
}
}

Experiment No. 06:

Experiment Name / Title: Implementation of Abstraction in Java.

Theory:
Abstraction:
- Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
- It shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.

There are two ways to achieve abstraction in java


1. Abstract class.
2. Interface.

a)​ Abstract Class:


• An abstract class is a class that is declared “abstract” keyword.
• It can have abstract and non-abstract methods (method with body).
• Class can’t be used to create object.
• Abstract classes cannot be instantiated.
• It needs to be extended and its method implemented.

NB. Any class having abstract method must be declared as abstract class.
b)​ Abstract Method:

• Method declared using “abstract”.


• Can’t have body.
• Must be defined by the child class

Code:
Ex-1: Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract
method run. It implementation is provided by the Honda class.

abstract class Bike


{
abstract void run(); //abstract method
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

Output:
running safely.

Ex-2:
Understanding the real scenario of abstract class
In this example, Shape is the abstract class, its implementation is provided by the Rectangle
and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the
end user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.

In this example, if you create the instance of Rectangle class, draw () method of Rectangle
class will be invoked.

abstract class Shape {


abstract void draw ();
}
//In real scenario, implementation is provided by others i.e. unknown by
end user
class Rectangle extends Shape {
void draw () {System.out.println("drawing rectangle");}
}
class Circle1 extends Shape {
void draw () {System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main (String args[]){
Shape s=new Circle1(); //In real scenario, object is provided through met
hod e.g. getShape() method
s.draw();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy