0% found this document useful (0 votes)
3 views12 pages

22BCS14689_Assignment

The document contains a lab assessment for a Computer Science and Engineering course, detailing various programming tasks and their solutions in Java. It includes problems related to finding the next greater element in arrays, inheritance, string encoding, method overloading, custom exceptions, and more. Each problem is accompanied by a code solution and output examples.

Uploaded by

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

22BCS14689_Assignment

The document contains a lab assessment for a Computer Science and Engineering course, detailing various programming tasks and their solutions in Java. It includes problems related to finding the next greater element in arrays, inheritance, string encoding, method overloading, custom exceptions, and more. Each problem is accompanied by a code solution and output examples.

Uploaded by

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

DEPARTMENT OF

COMPUTERSCIENCE & ENGINEERING

PBLJ - Lab Assesment


Course Name: PBLJ
Subject Code: - (22CSH-359)

Student Name: Aman Kumar Mishra UID: 22BCS14689


Branch: BE-CSE Section/Group: 22BCS_EPAM-801/B
Semester: 6th Date of Performance: 21-04-2025.
-------------------------------------------------------------------------------------
Qus.-1: The next greater element of some element x in an array is the first greater element
that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a
subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and
determine the next greater element of nums2[j] in nums2. If there is no next greater element,
then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as
described above.

Hint:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.

Soln.-
import java.util.*;
public class NextGreaterElement {
public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> nextGreaterMap = new HashMap<>();
Stack<Integer> stack = new Stack<>();

for (int num : nums2) {


while (!stack.isEmpty() && stack.peek() < num) {
nextGreaterMap.put(stack.pop(), num);
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
}
stack.push(num);
}
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
result[i] = nextGreaterMap.getOrDefault(nums1[i], -1);
}
return result;
}
public static void main(String[] args) {
int[] nums1 = {4, 1, 2};
int[] nums2 = {1, 3, 4, 2};
System.out.println(Arrays.toString(nextGreaterElement(nums1, nums2)));
}
}
Output:

Qus.-2: Develop a Java program showcasing the concept of inheritance. Create a base class and
a derived class with appropriate methods and fields.
Soln.- class Animal {
String name = "Animal";
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
System.out.println(d.name);
}
}
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING

Output:

Qus.-3: Encoding Three Strings: Anand was assigned the task of coming up with an
encoding mechanism for any given three strings.He has come up with the following plan.

Step ONE :- Given any three strings,break each string into 3 parts each.
For example- if the three strings are below:
Input 1: “John”
Input 2: “Johny”
Input 3 : “Janardhan”
“John” should be split into”J”,”oh”,”n,” as the FRONT ,MIDDLE and END part
repectivly.
“Johny” should be spilt into “jo”,” h”, “ny” as the FRONT ,MIDDLE and END
respectively.
“Janardhan” should be split into “Jan” ,” ard” ,”han” as the FRONT ,MIDDLE and END
part respectively.
i.e. If the no. of characters in the string are in multiples of 3 ,then each split –part will contain
equal no of characters , as seen in the example of “Janadhan”.
If the no. of characters in the string are NOT in multiples of 3 ,and if there is one character
more than multiple of 3, then the middle part will get the extra character ,as seen in the
example of “john”.
If the no. of characters in the string are Not in multiples of 3 and if there are two characters
more than multiple of 3, then the FRONT and END parts will get one extra character each,
as seen in the example of “Johny”.

Step TWO : Concatenate (join) the FRONT ,MIDDLE and END parts of the string as per
the below specified concatenation – rule to from three Output strings.
Output 1: FRONT part of input 1 + MIDDLE part of input 2 +END part of input 3
Output2:- MIDDLE part of input1+ END part of input2 + FRONT part of input3
Output3: END part of the input1+FRONT part of input2 +MIDDLE part of input3
For example , for the above example input strings:
Output1 = “J” +”h”+han”=”jhhan”
Output2 =”oh”+”ny”+”Jan”=”ohnyjan”
Output3=”n”+Jo”+ard”+=“njoard”
Step THREE :-
Process the resulting output strings based on the output-processing rule .After the above two
steps, we will now have three output string. Further processing is required only for the third
output string as per below rule-
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
“Toggle the case of each character in the string “ ,i.e. in the third output string, all lower-case
characters should be made upper-case and vice versa.
For example , for the above example strings ,output3 is “nJoard”, so after applying the
toggle rule. Output3 should become “NjOARD”.
Final Result – The three output strings after applying the above three steps i.e. for the above
example .
Output1 =”Jnhan”
Output2=”ohnyJan’
Output3 = “NJOARD”
Help Anand to write a program that would do the above.

Soln.- public class EncodeThreeStrings {


static String[] splitString(String s) {
int len = s.length();
int part = len / 3;
int rem = len % 3;
int front = part, middle = part, end = part;
if (rem == 1) middle += 1;
else if (rem == 2) {
front += 1;
end += 1;
}
String frontStr = s.substring(0, front);
String middleStr = s.substring(front, front + middle);
String endStr = s.substring(front + middle);
return new String[]{frontStr, middleStr, endStr};
}
static String[] encode(String s1, String s2, String s3) {
String[] p1 = splitString(s1);
String[] p2 = splitString(s2);
String[] p3 = splitString(s3);

String out1 = p1[0] + p2[1] + p3[2];


String out2 = p1[1] + p2[2] + p3[0];
String out3 = p1[2] + p2[0] + p3[1];
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
out3 = toggleCase(out3);
return new String[]{out1, out2, out3};
}
static String toggleCase(String s) {
StringBuilder result = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c))
result.append(Character.toLowerCase(c));
else if (Character.isLowerCase(c))
result.append(Character.toUpperCase(c));
else
result.append(c);
}
return result.toString();
}
public static void main(String[] args) {
String[] result = encode("John", "Johny", "Janardhan");
for (String s : result) System.out.println(s);
}
}
Output:

Qus.-4: Implement a Java program that uses method overloading to perform different
mathematical operations.
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
Soln.- public class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
MathOperations m = new MathOperations();
System.out.println(m.add(2, 3));
System.out.println(m.add(2.5, 3.5));
System.out.println(m.add(1, 2, 3));
}
}
Output:

Qus.-5: . Given a String (In Uppercase alphabets or Lowercase alphabets), new alphabets is
to be appended with following rule:

(i) If alphabet is present in input string, use numeric value of that alphabet.

E.g. a or A numeric value is 1 and so on. New alphabet to be appended between 2


alphabets :
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING

(a) If (sum of numeric value of 2 alphabets) %26 is 0, then append 0.

E.g. string is ay. Numeric value of a is 1, y is 25. Sum is 26. Remainder is 0, new string will
be a0y.

(b) Otherwise (sum of numeric value of 2 alphabets) %26 numeric value alphabet is to
appended. E.g. ac is string. Numeric value of a is 1, c is 3, sum is 4. Remainder with 26 is 4.
Alphabet to be appended is d. output will be adc.

(ii) If digit is present, it will be same in output string. E.g. string is 12, output string is 12.

(iii) If only single alphabet is present, it will be same in output string. E.g. input string is
1a, output will be 1a.

(iv) If space is present, it will be same in output string. E.g. string is ac 12a, output will be
adc 12a.

Constraint: Whether string alphabets are In Uppercase or Lowercase, appended alphabets


must be in lower case. Output string must also be in lowercase.

Soln.- public class InsertAlphabet {

static String convert(String s) {

StringBuilder result = new StringBuilder();

s = s.toLowerCase();

for (int i = 0; i < s.length(); i++) {

result.append(s.charAt(i));

if (i + 1 < s.length() && Character.isLetter(s.charAt(i)) && Character.isLetter(s.charAt(i


+ 1))) {

int sum = (s.charAt(i) - 'a' + 1) + (s.charAt(i + 1) - 'a' + 1);

if (sum % 26 == 0)
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
result.append("0");

else

result.append((char) ((sum % 26 - 1) + 'a'));

return result.toString();

public static void main(String[] args) {

System.out.println(convert("ac"));

System.out.println(convert("ay"));

System.out.println(convert("ac 12a"));

}
Output:
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
Qus.-6: Define an interface in Java and create a class that implements it, demonstrating the
concept of abstraction.

Soln.- interface Vehicle {


void start();
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car started");
}
public void stop() {
System.out.println("Car stopped");
}
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start();
myCar.stop();
}
}
Output:

Qus.-7: String t is generated by random shuffling string s and then add one more letter at a
random position.
Return the letter that was added to t.
Hint:
Input: s = "abcd", t = "abcde"
Output: "e"

Soln.- public class FindAddedLetter {

static char findTheDifference(String s, String t) {


int sum = 0;
for (char c : t.toCharArray()) sum += c;
for (char c : s.toCharArray()) sum -= c;
return (char) sum;
}
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
public static void main(String[] args) {
System.out.println(findTheDifference("abcd", "abcde")); // Output: e
}
}
Output:

Qus.-8: Create a custom exception class in Java. Write a program that throws this custom
exception in a specific scenario.

Soln.- class InvalidAgeException extends Exception {


public InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) throw new InvalidAgeException("Age must be 18 or older.");
else System.out.println("You are allowed.");
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (InvalidAgeException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
Output:

Qus.-9: Consider a function public String matchFound(String input 1, String input 2), where
• input1 will contain only a single word with only 1 character replaces by an underscore ‘_’
• input2 will contain a series of words separated by colons and no space character in between
• input2 will not contain any other special character other than underscore and alphabetic
characters.
The methods should return output in a String type variable “output1” which contains all the
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
words from input2 separated by colon which matches with input 1. All words in output1 should be
in uppercase.

Soln.- public class MatchWords {


public static String matchFound(String input1, String input2) {
String[] words = input2.split(":");
String regex = input1.replace("_", "[a-zA-Z]");
StringBuilder result = new StringBuilder();

for (String word : words) {


if (word.matches(regex)) {
if (result.length() > 0) result.append(":");
result.append(word.toUpperCase());
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(matchFound("c_t", "cat:cut:cot:coat"));
}
}
Output:

Qus.-10: Explain the difference between the throw and throws keywords in Java. Provide
examples illustrating their usage.

Soln.- class Demo {


static void validate(int age) throws IllegalArgumentException {
if (age < 18) {
throw new IllegalArgumentException("Not eligible to vote");
}
System.out.println("Eligible");
}
public static void main(String[] args) {
try {
validate(15);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
DEPARTMENT OF
COMPUTERSCIENCE & ENGINEERING
}
}
}
Output:

You might also like