0% found this document useful (0 votes)
11 views11 pages

Koustubh Java Practicle Assignment 2

The document contains questions and answers related to Java programming. It includes 9 questions covering topics like creating packages and classes, arrays, sorting, strings, and matrices. For each question, it provides the code to implement the given task and the expected output.

Uploaded by

rdlolge
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)
11 views11 pages

Koustubh Java Practicle Assignment 2

The document contains questions and answers related to Java programming. It includes 9 questions covering topics like creating packages and classes, arrays, sorting, strings, and matrices. For each question, it provides the code to implement the given task and the expected output.

Uploaded by

rdlolge
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

Name: Koustubh Rajesh Sadavarte

Roll No: 41

[Link] Package College with one class Student(rollno, Percent and method set(), get() to
get and show the details of student). Use this package in another class.

//Define the "Student" class in the "[Link]" file

package College; public class Student { private

int rollno; private double percent;

// Constructor public Student(int rollno,

double percent) { [Link] = rollno;

[Link] = percent;

// Default constructor

public Student() {

[Link] = 0;

[Link] = 0.0;

// Set student details public void set(int

rollno, double percent) { [Link] =

rollno; [Link] = percent;

// Get and display student details

public void get() {

[Link]("Roll No: " + rollno);

[Link]("Percentage: " + percent);

}
//To use the "College" package in another class, you can create a separate Java class and import
the "Student" class: import [Link]; public class Main { public static void main(String[]
args) { //Create a student object

Student student = new Student();

// Set student details

[Link](101, 90.5);
// Display student details

[Link]("Student Details:");

[Link]();

Output:
[Link] package Library with 3 classes books (bid, qty), Issue() and Returns() package

Library; public class Books { private int bid; private int qty; public Books(int bid, int qty) {

[Link] = bid; [Link] = qty;

// Getters and setters for bid and qty

public int getBid() { return bid;

public void setBid(int bid) {

[Link] = bid;

public int getQty() {

return qty;

public void setQty(int qty) {

[Link] = qty;

package Library; public

class Issue {

// Add methods and attributes related to issuing books here

package Library; public

class Returns {

// Add methods and attributes related to returning books here

package Library; public

class Returns {

// Add methods and attributes related to returning books here

Output:
[Link] to count occurance of given number in an integer array of size 10
public class CountOccurrencesInArray { public static

void main(String[] args) { int[] array = {5, 2, 8, 5, 9, 5,

4, 2, 7, 5}; int targetNumber = 5; // The number you

want to count int count = countOccurrences(array,

targetNumber);

[Link]("The number " + targetNumber + " appears in the array " + count + "
times.");

public static int countOccurrences(int[] arr, int target) {

int count = 0; for (int num : arr) { if (num ==

target) { count++;

return count;

Output:

[Link] to sort an array in descending order.


import [Link]; import

[Link]; public class

SortArrayListDescending { public

static void main(String[] args) {

ArrayList<Integer> arrayList = new ArrayList<Integer>();

[Link](5); [Link](2); [Link](8);

[Link](5); [Link](9); [Link](5);

[Link](4); [Link](2); [Link](7);

[Link](5);

// Sort the ArrayList in descending order

[Link](arrayList, [Link]());

// Print the sorted ArrayList

[Link]("Sorted ArrayList in descending order: " + arrayList);

Output:

Q5. Program to sum odd and even elements of an array


public class SumOddEvenElements {
public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int sumEven = 0; int sumOdd = 0;

for (int num : array) { if (num % 2 ==


0) { // Even number

sumEven += num;

} else {

// Odd number

sumOdd += num;

[Link]("Sum of even elements: " + sumEven);

[Link]("Sum of odd elements: " + sumOdd);

Output:

Q6. For a given 2D square matrix of size N*N, the task is to find the sum of elements in the
Principal diagonals. For example, analyze the following 4 × 4
public class PrincipalDiagonalSum {

public static void main(String[] args) {

int N = 4; // Size of the square matrix

int[][] matrix = { {1, 2, 3, 4},

{5, 6, 7, 8},
{9, 10, 11, 12},

{13, 14, 15, 16}

};

int diagonalSum = 0;

// Iterate through the principal diagonal

for (int i = 0; i < N; i++) {

diagonalSum += matrix[i][i];

[Link]("Sum of elements in the principal diagonal: " + diagonalSum);

Output:

Q7. Program to reverse string


public class ReverseString { public
static void main(String[] args) {

String originalString = "Hello, World!";

String reversedString = reverseString(originalString);

[Link]("Original string: " + originalString);


[Link]("Reversed string: " + reversedString);

public static String reverseString(String input) {

StringBuilder reversed = new StringBuilder(); for

(int i = [Link]() - 1; i >= 0; i--) {

[Link]([Link](i));

return [Link]();

Output:

Q8. Program to remove duplicate characters from String


public class RemoveDuplicateCharacters {

public static void main(String[] args) {

String inputString = "programming";

String resultString = removeDuplicates(inputString);


[Link]("Original string: " + inputString);

[Link]("String without duplicates: " + resultString);

public static String removeDuplicates(String input) {

StringBuilder result = new StringBuilder(); for (int i = 0; i

< [Link](); i++) { char currentChar =

[Link](i); if

([Link]([Link](currentChar)) == -1) {

[Link](currentChar);

return [Link]();

Output:

Q9. Program to toggle case each charatcer of every word of string


public class ToggleCaseInWords {

public static void main(String[] args) {


String inputString = "Hello World!";

String resultString = toggleCaseInWords(inputString);

[Link]("Original string: " + inputString);

[Link]("String with toggled case in words: " + resultString);

public static String toggleCaseInWords(String input) {

String[] words = [Link](" ");

StringBuilder result = new StringBuilder(); for (String

word : words) { for (int i = 0; i < [Link](); i++) {

char currentChar = [Link](i); if

([Link](currentChar)) {

[Link]([Link](currentChar));

} else {

[Link]([Link](currentChar));

[Link](" "); // Add a space between words

return [Link]().trim(); // Trim to remove the trailing space

Output:

Common questions

Powered by AI

The logic involves iterating through each array element, checking if it's odd or even using the modulus operator, and accumulating corresponding sums in separate variables `sumEven` and `sumOdd`. This technique highlights patterns such as parity, revealing insights like the relative distribution of even vs. odd numbers or cumulative parity effects in sequences.

Utilizing packages in Java organizes code into manageable sections, preventing namespace collisions by providing separate scopes for classes. This enhances maintainability by grouping related classes and enabling easier navigation, fostering better scalability and collaboration across larger projects due to clear demarcation of code responsibilities.

The constructor in the Student class within the College package allows for direct initialization of the object's fields when an instance is created. It provides a way to assign initial values to 'rollno' and 'percent', ensuring that the object has a valid state upon creation, which enhances code reliability and readability.

Reversing a string using a for loop with a `StringBuilder` offers simplicity and straightforward implementation with linear time complexity O(n). Alternatives, like using recursion, may introduce additional overhead and complexity without performance gains. Methods using built-in functions like `Collections.reverse()` for lists or Python-like slices in other languages can offer similar efficiency with potentially cleaner code.

The Java program sorts an ArrayList in descending order using the `Collections.sort()` method with `Collections.reverseOrder()` as the comparator. The final outcome is the ArrayList sorted in descending order, which is then printed.

The method to remove duplicate characters involves iterating over the input string and checking each character against a `StringBuilder` that accumulates unique characters. If a character is not present in the `StringBuilder`, it is appended. This approach has a complexity of O(n^2) due to the `indexOf` method used in each iteration, which itself has a complexity of O(n)

The program iterates over the array with a loop, comparing each element to the target number. For each match, a counter is incremented. This strategy is efficient for small arrays but has a linear complexity of O(n), making it less efficient for large arrays due to the need to inspect each element individually.

Encapsulating the `Books`, `Issue`, and `Returns` classes within the Library package ensures modularity and organization, allowing each class to manage specific aspects of library functionality: book data, issue transactions, and returns. This design principle facilitates code maintenance and scalability by separating concerns and promoting reusable code.

The methodology involves iterating through each word split by spaces, and toggling the case of each character using `Character.isUpperCase` and `Character.toLowerCase` methods to flip the character's case. Non-alphabetic characters remain unchanged as the methods only affect alphabetic characters, ensuring other characters do not break the string format.

The program iterates over each matrix row and utilizes the index equality of `matrix[i][i]` to sum elements along the principal diagonal. A limitation is the assumption that the matrix is square (N*N), which is necessary for accessing indices `i,i` safely. There is also an implicit assumption that the matrix is populated with valid integer values.

You might also like