Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

APPWEEKK6

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

21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
SAIDINESH
RA2211029010016(Q2)

1)Write a Java program to create a class called "Person" with a name and age attribute. Create two
instances of the "Person" class, set their attributes using the constructor, and print their name and
age.

PROGRAM:

class Person {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age; }

public String getName() {

return name; }

public int getAge() {

return age;

} }

public class Main {

public static void main(String[] args) {

Person person1 = new Person("Alice", 25);

Person person2 = new Person("Bob", 30);

System.out.println("Person 1 - Name: " + person1.getName() + ", Age: " + person1.getAge());

System.out.println("Person 2 - Name: " + person2.getName() + ", Age: " + person2.getAge());

} }

OUTPUT:
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM

2) 2. Write a Java program to create class called "TrafficLight" with attributes for color and duration,
and methods to change the color and check for red or green.

PROGRAM:

class TrafficLight {

private String color;

private int duration; // Duration in seconds

public TrafficLight(String initialColor, int initialDuration) {

color = initialColor;

duration = initialDuration;

} public void changeColor(String newColor) {

color = newColor;

public String getColor() {

return color;

public int getDuration() {

return duration;

public boolean isRed() {

return color.equals("red");

public boolean isGreen() {

return color.equals("green");

}public class Main {

public static void main(String[] args) {

TrafficLight trafficLight = new TrafficLight("red", 30);


21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
System.out.println("Initial Color: " + trafficLight.getColor());

System.out.println("Is it Red? " + trafficLight.isRed());

System.out.println("Is it Green? " + trafficLight.isGreen());

trafficLight.changeColor("green");

System.out.println("New Color: " + trafficLight.getColor());

System.out.println("Is it Red? " + trafficLight.isRed());

System.out.println("Is it Green? " + trafficLight.isGreen());

OUTPUT:

3. Write a Java program to perform arithmetic operations using method overloading.

PROGRAM:

public class ArithmeticOperations {

// Method to add two integers

public static int add(int a, int b) {

return a + b;

//Method to add three integers

public static int add(int a, int b, int c) {

return a + b + c;

}
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
// Method to add two double values

public static double add(double a, double b) {

return a + b;

// Method to subtract two integers

public static int subtract(int a, int b) {

return a - b;

// Method to subtract two double values

public static double subtract(double a, double b) {

return a - b;

// Method to multiply two integers

public static int multiply(int a, int b) {

return a * b; }

// Method to multiply two double values

public static double multiply(double a, double b) {

return a * b; }

// Method to divide two integers

public static int divide(int a, int b) {

if (b != 0) {

return a / b;

} else {

throw new IllegalArgumentException("Cannot divide by zero");

} // Method to divide two double values

public static double divide(double a, double b) {

if (b != 0) {

return a / b;

} else {
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
throw new IllegalArgumentException("Cannot divide by zero");

} public static void main(String[] args) {

System.out.println("Addition (int): " + add(5, 3));

System.out.println("Addition (double): " + add(2.5, 1.5));

System.out.println("Subtraction (int): " + subtract(8, 4));

System.out.println("Subtraction (double): " + subtract(6.7, 2.2));

System.out.println("Multiplication (int): " + multiply(6, 7));

System.out.println("Multiplication (double): " + multiply(3.5, 2.0));

System.out.println("Division (int): " + divide(10, 2));

System.out.println("Division (double): " + divide(15.0, 3.0));

OUTPUT:

4. Write a Java program to create a class called Employee with methods called work() and getSalary().
Create a subclass called HRManager that overrides the work() method and adds a new method called
addEmployee().

PROGRAM:

// Employee.java

// Parent class Employee

public class Employee {

private int salary;


21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
public Employee(int salary) {

this.salary = salary;

public void work() {

System.out.println("working as an employee!");

public int getSalary() {

return salary;

// HRManager.java

// Child class HRManager

public class HRManager extends Employee {

public HRManager(int salary) {

super(salary);

public void work() {

System.out.println("\nManaging employees");

public void addEmployee() {

System.out.println("\nAdding new employee!");

Copy
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
// Main.java

// Main class

public class Main {

public static void main(String[] args) {

Employee emp = new Employee(40000);

HRManager mgr = new HRManager(70000);

emp.work();

System.out.println("Employee salary: " + emp.getSalary());

mgr.work();

System.out.println("Manager salary: " + mgr.getSalary());

mgr.addEmployee();

OUTPUT:

5. Write a Java program to create a class called Shape with methods called getPerimeter()
and getArea(). Create a subclass called Circle that overrides the getPerimeter() and
getArea() methods to calculate the area and perimeter of a circle.

PROGRAM:

class Shape {

// Methods to be overridden by subclasses


21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
public double getPerimeter() {

return 0.0;

public double getArea() {

return 0.0;

class Circle extends Shape {

private double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double getPerimeter() {

return 2 * Math.PI * radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

}
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
public class Main {

public static void main(String[] args) {

Circle circle = new Circle(5.0);

double circlePerimeter = circle.getPerimeter();

double circleArea = circle.getArea();

System.out.println("Circle Perimeter: " + circlePerimeter);

System.out.println("Circle Area: " + circleArea);

OUTPUT:

6. Write a Java program to create an interface Sortable with a method sort() that sorts an
array of integers in ascending order. Create two classes BubbleSort and SelectionSort that
implement the Sortable interface and provide their own implementations of the sort()
method.

PROGRAM:

interface Sortable {

void sort(int[] arr);

class BubbleSort implements Sortable {

@Override
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
public void sort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

class SelectionSort implements Sortable {

@Override

public void sort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

int minIndex = i;

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[minIndex]) {

minIndex = j;

}
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

public class Main {

public static void main(String[] args) {

int[] arr = { 64, 34, 25, 12, 22, 11, 90 };

Sortable bubbleSort = new BubbleSort();

bubbleSort.sort(arr);

System.out.println("Sorted array using Bubble Sort:");

printArray(arr);

int[] arr2 = { 64, 34, 25, 12, 22, 11, 90 };

Sortable selectionSort = new SelectionSort();

selectionSort.sort(arr2);

System.out.println("\nSorted array using Selection Sort:");

printArray(arr2);

static void printArray(int[] arr) {


21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
for (int value : arr) {

System.out.print(value + " ");

System.out.println();

OUTPUT:

7. Write a Java program to create an interface Resizable with methods resize Width(int
width) and resizeHeight(int height) that allow an object to be resized. Create a class
Rectangle that implements the Resizable interface and implements the resize methods.

PROGRAM:

interface Resizable {

void resizeWidth(int width);

void resizeHeight(int height);

class Rectangle implements Resizable {

private int width;

private int height;


21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
public Rectangle(int width, int height) {

this.width = width;

this.height = height;

public int getWidth() {

return width;

public int getHeight() {

return height;

@Override

public void resizeWidth(int width) {

this.width = width;

@Override

public void resizeHeight(int height) {

this.height = height;

public class Main {


21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
public static void main(String[] args) {

Rectangle rectangle = new Rectangle(10, 5);

System.out.println("Original Rectangle Dimensions:");

System.out.println("Width: " + rectangle.getWidth());

System.out.println("Height: " + rectangle.getHeight());

rectangle.resizeWidth(15);

rectangle.resizeHeight(7);

System.out.println("\nResized Rectangle Dimensions:");

System.out.println("Width: " + rectangle.getWidth());

System.out.println("Height: " + rectangle.getHeight());

OUTPUT:

8. Write a Java program to create an interface Flyable with a method called fly_obj(). Create
three classes Spacecraft, Airplane, and Helicopter that implement the Flyable interface.
Implement the fly_obj() method for each of the three classes. Hint :- fly_obj definition –
prints the particular object is flying.
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
PROGRAM:

interface Flyable {

void fly_obj();

class Spacecraft implements Flyable {

@Override

public void fly_obj() {

System.out.println("Spacecraft is flying in outer space.");

class Airplane implements Flyable {

@Override

public void fly_obj() {

System.out.println("Airplane is flying in the sky.");

class Helicopter implements Flyable {

@Override

public void fly_obj() {

System.out.println("Helicopter is flying in the air.");

}
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM

public class Main {

public static void main(String[] args) {

Flyable spacecraft = new Spacecraft();

Flyable airplane = new Airplane();

Flyable helicopter = new Helicopter();

System.out.println("Flying Objects:");

System.out.println("-----------------");

spacecraft.fly_obj();

airplane.fly_obj();

helicopter.fly_obj();

OUTPUT:

9. Write a Java program to have the arithmetic functions defined in different user-defined
packages and incorporate all the packages and perform the function in a single class.

PROGRAM:

package mathoperations;
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
public class Addition {

public static int add(int a, int b) {

return a + b;

package mathoperations;

public class Subtraction {

public static int subtract(int a, int b) {

return a - b;

package mathoperations;

public class Multiplication {

public static int multiply(int a, int b) {

return a * b;

package mathoperations;

public class Division {

public static double divide(double a, double b) {

if (b != 0) {
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
return a / b;

} else {

throw new IllegalArgumentException("Cannot divide by zero");

package mathoperations;

public class MainApp {

public static void main(String[] args) {

int num1 = 10;

int num2 = 5;

int sum = Addition.add(num1, num2);

int difference = Subtraction.subtract(num1, num2);

int product = Multiplication.multiply(num1, num2);

double quotient = Division.divide(num1, num2);

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

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

System.out.println("Product: " + product);

System.out.println("Quotient: " + quotient);

}}
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
OUTPUT:

10. Create two different packages to compute bubblesort and selection sort. Write a Java
program to implement sorting functions in a single class.

PROGRAM:

package bubblesort;

public class BubbleSort {

public static void sort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

package selectionsort;
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM

public class SelectionSort {

public static void sort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

int minIndex = i;

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[minIndex]) {

minIndex = j;

int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

package app;

import java.util.Arrays;

import bubblesort.BubbleSort;

import selectionsort.SelectionSort;

public class SortApp {

public static void main(String[] args) {


21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
int[] arr1 = { 64, 34, 25, 12, 22, 11, 90 };

int[] arr2 = { 64, 34, 25, 12, 22, 11, 90 };

System.out.println("Original arrays:");

System.out.println("Array 1: " + Arrays.toString(arr1));

System.out.println("Array 2: " + Arrays.toString(arr2));

BubbleSort.sort(arr1);

SelectionSort.sort(arr2);

System.out.println("\nSorted arrays using Bubble Sort and Selection Sort:");

System.out.println("Array 1: " + Arrays.toString(arr1));

System.out.println("Array 2: " + Arrays.toString(arr2));

OUTPUT:
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM

3 Hackerranker questions
1) A string containing only parentheses is balanced if the following is true: 1. if it is an empty

string 2. if A and B are correct, AB is correct, 3. if A is correct, (A) and {A} and [A] are also

correct.Examples of some correctly balanced strings are: "{}()", "[{()}]", "({()})"Examples of some

unbalanced strings are: "{}(", "({)}", "[[", "}{" etc.Given a string, determine if it is balanced or not.

PROGRAM:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static boolean isBalanced(String s) {


Stack<Character> stack = new Stack<Character>();
for (int i=0; i<s.length();++i){
if (s.charAt(i) == '(') stack.push('(');
else if (s.charAt(i) == '{') stack.push('{');
else if (s.charAt(i) == '[') stack.push('[');
else if (s.charAt(i) == ')') {
if (stack.isEmpty()) return false;
if (stack.pop() != '(') return false;
}
else if (s.charAt(i) == '}') {
if (stack.isEmpty()) return false;
if (stack.pop() != '{') return false;
}
else if (s.charAt(i) == ']') {
if (stack.isEmpty()) return false;
if (stack.pop() != '[') return false;
}
}
return stack.isEmpty();
}

public static void main(String[] args) {


Stack<Character> stack = new Stack<Character>();
Scanner sc = new Scanner(System.in);
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
String line;
while (sc.hasNextLine()){

line = sc.nextLine();
if (isBalanced(line)) System.out.println("true");
else System.out.println("false");
}
}
}

OUTPUT:

2) Static initialization blocks are executed when the class is loaded, and you can initialize static

variables in those blocks . It's time to test your knowledge of Static initialization blocks. You can

read about it here . You are given a class Solution with a main method. Complete the given code

so that it outputs the area of a parallelogram with breadth and height .You should read the

variables from the standard input.

PROGRAM:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static int B,H;


private static boolean flag = false;
static
{
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
Scanner sc = new Scanner(System.in);
B = sc.nextInt();
H = sc.nextInt();
if(B>0 && H>0)
{
flag = true;
}
else
{
System.out.println("java.lang.Exception: Breadth and heig
ht must be positive");
}
}

public static void main(String[] args){


if(flag){
int area=B*H;
System.out.print(area);
}

}//end of main

}//end of class

OUTPUT:

3) Given a string, , matching the regular expression [A-Za-z !,?._'@]+, split the string into tokens.

We define a token to be one or more consecutive English alphabetic letters. Then, print the

number of tokens, followed by each token on a new line.

Note: You may find the String.split method helpful in completing this challenge.
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM

PROGRAM:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String S = sc.nextLine();
String[] tokens = S.split("[^a-zA-Z]");
int numTokens = 0;

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


if (tokens[i].length() > 0)
numTokens++;

System.out.println(numTokens);

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


if (tokens[i].length() > 0)
System.out.println(tokens[i]);
}
}

OUTPUT:
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM
21CSC203P ADVANCED PROGRAMMING PRACTICE

WEEk 6 – TuTORIAl ASSIGNMENT


ObjECT-ORIENTED PROGRAMMING PARADIGM

You might also like