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

Program t1

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

Program t1

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

1. Wirte a sample program to explain the constructor overloading.

Constructor overloading in Java allows a class to have multiple


constructors with different parameter lists.
This means a class can have multiple constructors that take different
numbers or types of parameters.
Here's a sample program to demonstrate constructor overloading:

public class Student {


private String name;
private int age;
private String department;

// Default constructor
public Student() {
this.name = "John Doe";
this.age = 20;
this.department = "Computer Science";
}

// Constructor with name and age parameters


public Student(String name, int age) {
this.name = name;
this.age = age;
this.department = "Computer Science";
}

// Constructor with all parameters


public Student(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}

// Method to display student details


public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Department: " + department);
}

public static void main(String[] args) {


// Creating objects using different constructors
Student student1 = new Student(); // Default constructor
Student student2 = new Student("Alice", 22); // Constructor with
name and age parameters
Student student3 = new Student("Bob", 25, "Electrical
Engineering"); // Constructor with all parameters

// Displaying details of students


System.out.println("Student 1 details:");
student1.displayDetails();
System.out.println();
System.out.println("Student 2 details:");
student2.displayDetails();
System.out.println();

System.out.println("Student 3 details:");
student3.displayDetails();
}
}

In this program:

The Student class has three constructors:

Default constructor: Sets default values for name, age, and department.
Constructor with name and age parameters: Allows setting name and age
while keeping the department as default.
Constructor with all parameters: Allows setting name, age, and
department.
The displayDetails() method prints the details of a student.

In the main method, we create three Student objects using different


constructors and then display their details.

This demonstrates how constructor overloading works in Java.


Depending on the parameters provided while creating an object,
different constructors can be invoked to initialize object state
differently.

2. Take List of strings in HashMap, Write a program to iterate through


all elements in Hash
Map and print them in ascending order by their values.

import java.util.*;

public class SortHashMapByValue {


public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 30);
hashMap.put("banana", 20);
hashMap.put("orange", 40);
hashMap.put("grape", 10);

// Sort HashMap by values in ascending order


TreeMap<String, Integer> sortedMap = sortHashMapByValue(hashMap);
// Print the sorted entries
System.out.println("Elements in HashMap sorted by values in
ascending order:");
for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + " -> " +
entry.getValue());
}
}

public static TreeMap<String, Integer>


sortHashMapByValue(HashMap<String, Integer> map) {
// Create a custom Comparator to compare map entries by their
values
Comparator<Map.Entry<String, Integer>> valueComparator = new
Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> entry1,
Map.Entry<String, Integer> entry2) {
return entry1.getValue().compareTo(entry2.getValue());
}
};

// Sort the entries of the HashMap by values using the custom


Comparator
TreeMap<String, Integer> sortedMap = new
TreeMap<>(valueComparator);
sortedMap.putAll(map);

return sortedMap;
}
}
When you run this program, it will output:

Elements in HashMap sorted by values in ascending order:


grape -> 10
banana -> 20
apple -> 30
orange -> 40
This demonstrates how to iterate through a HashMap and print its elements
in ascending order by their values.

3. Implement the runtime polymorphism using following example.


Consider a scenario where Bank is a class that provides a method to get
the rate of
interest. However, the rate of interest may differ according to banks.
For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and
9.7% rate of
interest.

class Bank {
public double getInterestRate() {
return 0.0;
}
}

class SBI extends Bank {


@Override
public double getInterestRate() {
return 8.4;
}
}

class ICICI extends Bank {


@Override
public double getInterestRate() {
return 7.3;
}
}

class AXIS extends Bank {


@Override
public double getInterestRate() {
return 9.7;
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Bank sbi = new SBI();
Bank icici = new ICICI();
Bank axis = new AXIS();

System.out.println("Rate of interest in SBI: " +


sbi.getInterestRate() + "%");
System.out.println("Rate of interest in ICICI: " +
icici.getInterestRate() + "%");
System.out.println("Rate of interest in AXIS: " +
axis.getInterestRate() + "%");
}
}
In this program:

Bank is the base class with a method getInterestRate() which returns 0.0
by default.
SBI, ICICI, and AXIS are subclasses of Bank which override the
getInterestRate() method to return their specific interest rates.
In the main() method, we create objects of type Bank but initialize them
with instances of SBI, ICICI, and AXIS. When we call getInterestRate()
method on these objects, it invokes the overridden method specific to
each bank, demonstrating runtime polymorphism.
When you run this program, it will output:

Rate of interest in SBI: 8.4%


Rate of interest in ICICI: 7.3%
Rate of interest in AXIS: 9.7%
This demonstrates runtime polymorphism in Java where the method called is
determined at runtime based on the type of object.

4. Write a Java Program To Reverse Each Word Of A String?


ex : Reverse Me
o/p esreveR eM

public class ReverseWords {


public static void main(String[] args) {
String str = "Reverse Me";
String reversed = reverseWords(str);
System.out.println("Original String: " + str);
System.out.println("Reversed String: " + reversed);
}

public static String reverseWords(String str) {


String[] words = str.split(" ");
StringBuilder reversedString = new StringBuilder();

for (String word : words) {


StringBuilder reversedWord = new StringBuilder(word);
reversedWord.reverse();
reversedString.append(reversedWord).append(" ");
}

return reversedString.toString().trim();
}
}
In this program:

We define a method reverseWords that takes a string as input.


We split the input string into words using split(" ") method.
Then, we iterate through each word, reverse it using StringBuilder's
reverse() method, and append the reversed word to a new StringBuilder.
Finally, we trim the trailing space and return the reversed string.
When you run this program with the input string "Reverse Me", it will
output:

Original String: Reverse Me


Reversed String: esreveR eM
This demonstrates how to reverse each word of a string in Java.

5. Write a program to remove the duplicate elements from the following


array and print
the all unique elements.
int a[] = {10,20,10,50,70,80,12};
You can remove duplicate elements from an array by iterating through it
and storing unique elements in a HashSet,
which automatically eliminates duplicates. Then, you can convert the
HashSet back to an array to print the unique elements.
Here's a Java program to do that:

import java.util.HashSet;

public class RemoveDuplicatesFromArray {


public static void main(String[] args) {
int[] a = {10, 20, 10, 50, 70, 80, 12};

// HashSet to store unique elements


HashSet<Integer> uniqueElements = new HashSet<>();

// Iterate through the array and add unique elements to HashSet


for (int num : a) {
uniqueElements.add(num);
}

// Convert HashSet back to array


int[] uniqueArray = new int[uniqueElements.size()];
int index = 0;
for (int num : uniqueElements) {
uniqueArray[index++] = num;
}

// Print unique elements


System.out.println("Unique elements:");
for (int num : uniqueArray) {
System.out.println(num);
}
}
}

When you run this program, it will output:

Unique elements:
10
12
50
20
80
70
This demonstrates how to remove duplicate elements from an array and
print the unique elements in Java.

6. Write a Java program to create a class called Employee with a method


called getSalary().
Create a subclass called HREmployee that overrides the getSalary()
method. Create a
main method and create objects for both the classes and call the
getSalary method on
both the object.

/ Employee class
class Employee {
public double getSalary() {
return 50000.0; // Default salary for Employee
}
}

// HREmployee class (subclass of Employee)


class HREmployee extends Employee {
// Override getSalary method for HREmployee
@Override
public double getSalary() {
return 60000.0; // Salary for HREmployee
}
}

// Main class
public class Main {
public static void main(String[] args) {
Employee employee = new Employee();
HREmployee hrEmployee = new HREmployee();

// Call getSalary method for both Employee and HREmployee


System.out.println("Salary of Employee: $" +
employee.getSalary());
System.out.println("Salary of HREmployee: $" +
hrEmployee.getSalary());
}
}
In this program:

Employee is a class with a method getSalary() that returns a default


salary.
HREmployee is a subclass of Employee that overrides the getSalary()
method to return a different salary specific to HR employees.
In the main() method, we create objects of both Employee and HREmployee
classes and call the getSalary() method on each object.
When you run this program, it will output:

Salary of Employee: $50000.0


Salary of HREmployee: $60000.0
This demonstrates how to use inheritance and method overriding in Java to
achieve polymorphic behavior.

7. Write a java program use array,find the min and Max value
public class MinMaxArray {
public static void main(String[] args) {
int[] array = {10, 5, 8, 20, 3, 15};

// Find minimum and maximum values


int min = findMin(array);
int max = findMax(array);

// Print the minimum and maximum values


System.out.println("Minimum value: " + min);
System.out.println("Maximum value: " + max);
}

public static int findMin(int[] array) {


int min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}

public static int findMax(int[] array) {


int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
}

In this program:

We define two methods findMin and findMax to find the minimum and maximum
values in the array respectively.
The findMin method initializes the min variable with the first element of
the array and then iterates through the array to find the minimum value.
The findMax method initializes the max variable with the first element of
the array and then iterates through the array to find the maximum value.
In the main method, we create an array and call the findMin and findMax
methods to find the minimum and maximum values respectively.
Finally, we print the minimum and maximum values.
When you run this program with the provided array, it will output:

Minimum value: 3
Maximum value: 20
This demonstrates how to find the minimum and maximum values in an array
using Java.

8. In a given array arrange all the even numbers first and remaining
next?
A[] = {24,57, 5, 3, 28, 2, 7, 9, 10}
o\p = 2, 28, 2, 10, 57, 5, 3, 7, 9

public class ArrangeEvenOdd {


public static void main(String[] args) {
int[] array = {24, 57, 5, 3, 28, 2, 7, 9, 10};

// Arrange even and odd numbers


arrangeEvenOdd(array);

// Print the arranged array


System.out.println("Arranged Array:");
for (int num : array) {
System.out.print(num + " ");
}
}

public static void arrangeEvenOdd(int[] array) {


int evenIndex = 0;

// Arrange even numbers first


for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
// Swap even number with the current evenIndex
int temp = array[i];
array[i] = array[evenIndex];
array[evenIndex] = temp;

evenIndex++;
}
}
}
}

In this program:

We define a method arrangeEvenOdd to arrange even numbers first in the


array.
We use the evenIndex variable to keep track of the position where the
next even number should be placed.
The method iterates through the array, and when it finds an even number,
it swaps it with the element at the evenIndex position and increments
evenIndex.
In the main method, we create an array and call the arrangeEvenOdd method
to arrange even and odd numbers.
Finally, we print the arranged array.
When you run this program with the provided array, it will output:

Arranged Array:
24 28 2 10 57 5 3 7 9
This demonstrates how to arrange even numbers first in an array in Java.

9.In a given sentence remove the extra white spaces and print the result
"Telstra is my destiny"?

public class RemoveExtraSpaces {


public static void main(String[] args) {
String sentence = "Telstra is my destiny";
String result = removeExtraSpaces(sentence);
System.out.println("Original sentence: " + sentence);
System.out.println("After removing extra spaces: " + result);
}

public static String removeExtraSpaces(String sentence) {


// Split the sentence by one or more spaces
String[] words = sentence.split("\\s+");

// Join the words with single space


return String.join(" ", words);
}
}
In this program:

We define a method removeExtraSpaces that takes a sentence as input and


returns the sentence after removing extra spaces.
We split the sentence into words using split("\\s+") method, which splits
the sentence by one or more whitespace characters (space, tab, newline,
etc.).
Then, we join the words using String.join(" ", words) to create a new
sentence with single spaces between words.
In the main method, we provide the input sentence, call the
removeExtraSpaces method, and print the original and modified sentences.
When you run this program with the provided sentence, it will output:

Original sentence: Telstra is my destiny


After removing extra spaces: Telstra is my destiny
This demonstrates how to remove extra white spaces from a sentence in
Java.

10. Write a program to print the string in reverse order without using
any string functions.
public class ReverseStringWithoutStringFunctions {
public static void main(String[] args) {
String str = "Hello, World!";
String reversed = reverseString(str);
System.out.println("Original string: " + str);
System.out.println("Reversed string: " + reversed);
}

public static String reverseString(String str) {


char[] charArray = str.toCharArray();
int length = charArray.length;

// Swap characters from start and end positions


for (int i = 0; i < length / 2; i++) {
char temp = charArray[i];
charArray[i] = charArray[length - i - 1];
charArray[length - i - 1] = temp;
}

return new String(charArray);


}
}
In this program:

We define a method reverseString that takes a string as input and returns


the reversed string.
We convert the input string to a character array using toCharArray()
method.
We iterate through the character array up to half its length, swapping
characters from start and end positions.
Finally, we create a new string from the reversed character array and
return it.
In the main method, we provide the input string, call the reverseString
method, and print the original and reversed strings.
When you run this program with the provided string "Hello, World!", it
will output:

Original string: Hello, World!


Reversed string: !dlroW ,olleH
This demonstrates how to reverse a string without using any string
functions in Java.

You might also like