Experiment 14 22z433 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Name : T K Santhosh

Roll No : 22Z433
Date : 10/12/2023

Experiment 14

Object Oriented Programming Laboratory

1.
Aim : To write a java program to use generics to demonstrate Code
Reusability.

// Program to use generics to demonstrate Code Reusability.

package EXP_15;

class Printer <T> {

T value;

public Printer(T value){


this.value = value;
}

public void print(){


System.out.println(this.value);
}
}

public class CodeReusability {


public static void main(String[] args){

// Printer instance for String.


Printer <String> ps = new Printer <> ("Santhosh");
ps.print();

// Printer instance for integer.


Printer <Integer> pi = new Printer <> (10);
pi.print();

Page 1
Name : T K Santhosh
Roll No : 22Z433
Date : 10/12/2023

}
}

santhoshtk@intense ~/Desktop/PSG-TECH/3rd-sem/OPP-LAB
Santhosh
10

2.
Aim : To write a java program to work with generic methods in Java.

// Program to work with generic methods in Java.

package EXP_15;

public class GenericMethods {

public static <T> void printValue(T value) {


System.out.println("Value: " + value);
}

public static <T> void swap(T a, T b) {


T temp = a;
a = b;
b = temp;
}

public static void main(String[] args) {


// Print values of different types
printValue("Hello");
printValue(100);
printValue(3.14159);

// Swap values of different types

Page 2
Name : T K Santhosh
Roll No : 22Z433
Date : 10/12/2023

Integer x = 10;
Integer y = 20;
swap(x, y);
System.out.println("x: " + x + ", y: " + y);

String s1 = "Java";
String s2 = "World";
swap(s1, s2);
System.out.println("s1: " + s1 + ", s2: " + s2);
}
}

santhoshtk@intense ~/Desktop/PSG-TECH/3rd-sem/OPP-LAB
Value: Hello
Value: 100
Value: 3.14159
x: 10, y: 20
s1: Java, s2: World

3.
Aim : To write a java program to concatenate two strings using lambda
expression.

// Program to use the generics to work with two parameters.

package EXP_15;

class MultipleValues <T>{

T a;
T b;

// Constructing the object.


public MultipleValues(T a, T b){
this.a = a;

Page 3
Name : T K Santhosh
Roll No : 22Z433
Date : 10/12/2023

this.b = b;
}

public void printer(){


System.out.println("First value : " + this.a);
System.out.println("Second value : " + this.b);
}

public class GenericTwoParameters {


public static void main(String[] args){

// Working with Integers.


MultipleValues <Integer> i = new MultipleValues <> (10,
110);
i.printer();

// Working with Strings.


MultipleValues <String> s = new MultipleValues <>
("santhosh ", "tk");
s.printer();
}
}

santhoshtk@intense ~/Desktop/PSG-TECH/3rd-sem/OPP-LAB
First value : 10
Second value : 110
First value : santhosh
Second value : tk

Result
Hence the given programs were executed successfully.

Page 4
Name : T K Santhosh
Roll No : 22Z433
Date : 10/12/2023

Page 5

You might also like