Java Programs for freshers: Find second largest number in the array

               In this series of programming, let us create a java program to find the largest number in the array.

Logic:

  • Get the number of elements in the array.
  • Read the array elements from the user.
  • Find the largest value and the minimum value in the array.
  • Create a for loop for checking all elements.
  • Now, check the element is greater than largest value, then assign the element as largest value.
  • Else, if the element is greater than second largest and not equal to largest, assign it as second largest.
  • If the second largest is equal to minimum value, then print there is no second largest number.
  • Otherwise, print the second largest number.

Program implementation:

  • Include the built in package.
  • Create a public class with main() function.
  • Using scanner object,read the number of elements and elements from the user at run time.
  • Use the above logic to implement the program.

Program:

import java.util.Scanner;

public class SecondLargestEg {

    public static void main(String[] args) {

        Scanner sObj = new Scanner(System.in);

              System.out.print("Enter the number of elements of the array: ");

              int n = sObj.nextInt();

        int[] a = new int[n];

              System.out.println("Enter the elements of the array: ");

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

              a[i] = sObj.nextInt();

              }

        int large = Integer.MIN_VALUE;

        int secondLarge = Integer.MIN_VALUE;

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

            if (a[i] > large) {

                secondLarge = large;

                large = a[i];

            } else if (a[i] > secondLarge && a[i] != large) {

                secondLarge = a[i];

            }

        }

       

        if (secondLarge == Integer.MIN_VALUE) {

            System.out.println("There is no second largest number.");

        } else {

            System.out.println("The second largest number is: " + secondLarge);

        }

    }

}

Output:

C:\raji\blog>javac SecondLargestEg.java

C:\raji\blog>java SecondLargestEg

Enter the number of elements of the array: 5

Enter the elements of the array:

235

312

657

456

888

The second largest number is: 657

This is the way of implementing java program to find the second largest number in the array.

Java Program for freshers: To reverse a String

               String is a collection of characters. String operations includes concatenation, counting the number of characters, deletion of a character and so on. let us create a reversal of string program as follows.

Logic:

  • ·       Read the input from the user.
  • ·       Create an empty string.
  • ·       Using a for loop, repeat the process.
  • ·       Assign the ‘i’ value to string length-1. Until i>0 , split the character at location ‘i’.
  • ·       Add to the empty string.
  • ·       Finally, print the value.

Program implementation:

  • ·       Import the built in module java.util.Scanner.
  • ·       Create a public class with main() function.
  • ·       An object is created for Scanner.
  • ·       Get the input from the user.
  • ·       Using the above logic, implement the reverse string program.
  • ·       Print the reversed String.

Program:

import java.util.Scanner; //Include the built in package

public class RevStringEg {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the string which is supposed to be reversed:");

        String inStr = scanner.nextLine();

        String revString = "";

        for (int i = inStr.length() - 1; i >= 0; i--) {

            revString += inStr.charAt(i);

        }

         System.out.println("The input String is: " + inStr);

        System.out.println("The Reversed String is: " + revString);

    }

}

Output:

let us compile and execute the program as follows....

C:\raji\blog>javac RevStringEg.java

C:\raji\blog>java RevStringEg

Enter the string which is supposed to be reversed:

welcome to Java World

The input String is: welcome to Java World

The Reversed String is: dlroW avaJ ot emoclew

That’s all. The java program to implement the reversal of string is written. Keep coding!!!

How to implement an Address book in java?

     Address book contains a set of contact details.It can be a student details, customer details and so on.

Let us create it in java.

Logic:

This Application has four operations as follows.

  • ·       Add Contact
  • ·       Remove Contact
  • ·       View Contacts
  • ·       Exit

To add the contact details, user has to enter the person name, phone number and email id.

To remove the contact details, user need to give the index value.

View contacts used to display the details.

Exit is used to exit the application.

Steps:

  • Three classes: ContactData, AddressBookEg, AddressBookAppEg
  • ContactData class is used to declare the variables, get the values and set the values.
  • AddressBookEg class is used to define the functions addContact(),getContacts() and removeContact().
  • AddressBookAppEg is the main class. It contains the main() function.
  • It reads the input from the user.Process according to the input and give you the output.

Program:

import java.util.ArrayList;

import java.util.Scanner;

class ContactData {

    private String cName;

    private String cPhoneNumber;

    private String cEmail;

 

    public ContactData(String cName, String cPhoneNumber, String cEmail) {

        this.cName = cName;

        this.cPhoneNumber = cPhoneNumber;

        this.cEmail = cEmail;

    }

    public String getName() {

        return cName;

    }

    public String getPhoneNumber() {

        return cPhoneNumber;

    }

    public String getEmail() {

        return cEmail;

    }

    public void setName(String cName) {

        this.cName = cName;

    }

    public void setPhoneNumber(String phoneNumber) {

        this.cPhoneNumber = cPhoneNumber;

    }

    public void setEmail(String email) {

        this.cEmail = cEmail;

    }

}

class AddressBookEg {

    private ArrayList<Contact> contacts;

    public AddressBookEg() {

        contacts = new ArrayList<>();

    }

    public void addContact(String cName, String cPhoneNumber, String cEmail) {

        contacts.add(new Contact(cName, cPhoneNumber, cEmail));

    }

    public void removeContact(int index) {

        if (index >= 0 && index < contacts.size()) {

            contacts.remove(index);

        }

    }

    public ArrayList<Contact> getContacts() {

        return contacts;

    }

    public Contact getContact(int index) {

        if (index >= 0 && index < contacts.size()) {

            return contacts.get(index);

        }

        return null;

    }

}

public class AddressBookAppEg {

    private static AddressBookEg addressBookeg = new AddressBookEg();

    private static Scanner scanner1 = new Scanner(System.in);

    public static void main(String[] args) {

        while (true) {

            printMenu();

            int choice1 = scanner1.nextInt();

            scanner1.nextLine();

 

            switch (choice1) {

                case 1:

                    addContact();

                    break;

                case 2:

                    removeContact();

                    break;

                case 3:

                    displayContacts();

                    break;

                case 4:

                    System.out.println("Exiting the application...");

                    return;

                default:

                    System.out.println("Invalid choice. Please try again.");

            }

        }

    }

    private static void printMenu() {

        System.out.println("****Address Book Application****");

        System.out.println("1. Add the Contact detail");

        System.out.println("2. Remove a Contact");

        System.out.println("3. View the Contacts");

        System.out.println("4. Exit the application");

        System.out.print("Choose an option according to your choice: ");

    }

    private static void addContact() {

        System.out.print("Enter the Person name: ");

        String name = scanner1.nextLine();

        System.out.print("Enter the phone number: ");

        String phoneNumber = scanner1.nextLine();

        System.out.print("Enter the email id: ");

        String email = scanner1.nextLine();

        addressBookeg.addContact(name, phoneNumber, email);

    }

    private static void removeContact() {

        System.out.print("Enter the index to delete the data: ");

        int contactNumber = scanner1.nextInt();

        addressBookeg.removeContact(contactNumber - 1);

    }

    private static void displayContacts() {

        ArrayList<Contact> contacts = addressBookeg.getContacts();

        System.out.println("Contacts details:");

        for (int i = 0; i < contacts.size(); i++) {

            Contact contact = contacts.get(i);

            System.out.println((i + 1) + ". " + contact.getName() + " - " + contact.getPhoneNumber() + " - " + contact.getEmail());

        }

    }

}

Output:

C:\raji\blog>javac AddressBookAppEg.java

 

C:\raji\blog>java AddressBookAppEg

****Address Book Application****

1. Add the Contact detail

2. Remove a Contact

3. View the Contacts

4. Exit the application

Choose an option according to your choice: 1

Enter the Person name: william

Enter the phone number: 2314428901

Enter the email id: william23@qwe.com

****Address Book Application****

1. Add the Contact detail

2. Remove a Contact

3. View the Contacts

4. Exit the application

Choose an option according to your choice: 1

Enter the Person name: raja

Enter the phone number: 1234567899

Enter the email id: raji78@gwe.com

****Address Book Application****

1. Add the Contact detail

2. Remove a Contact

3. View the Contacts

4. Exit the application

Choose an option according to your choice: 1

Enter the Person name: ajay

Enter the phone number: 09123456788

Enter the email id: ajay@abc.com

****Address Book Application****

1. Add the Contact detail

2. Remove a Contact

3. View the Contacts

4. Exit the application

Choose an option according to your choice: 3

Contacts details:

1. william - 2314428901 - william23@qwe.com

2. raja - 1234567899 - raji78@gwe.com

3. ajay - 09123456788 - ajay@abc.com

****Address Book Application****

1. Add the Contact detail

2. Remove a Contact

3. View the Contacts

4. Exit the application

Choose an option according to your choice: 2

Enter the index to delete the data: 1

****Address Book Application****

1. Add the Contact detail

2. Remove a Contact

3. View the Contacts

4. Exit the application

Choose an option according to your choice: 3

Contacts details:

1. raja - 1234567899 - raji78@gwe.com

2. ajay - 09123456788 - ajay@abc.com

****Address Book Application****

1. Add the Contact detail

2. Remove a Contact

3. View the Contacts

4. Exit the application

Choose an option according to your choice: 4

Exiting the application...

That’s all. The java program to implement address book application is created successfully. Keep coding!!

Simple ChatBot Application in java

     ChatBot is a simple AI application. Whenever user asks a question, it gives you the response. This chatbot is developed using java language.

How to create a simple Chatbot application in java?

First, get the input from the user. Check the input with the corresponding content and

display the output.

Steps to follow:

  • ·       Include the built-in package.
  • ·       Create a public class with a main() function.
  • ·       Read the input from the user.
  • ·       Call the function to get the response.
  • ·       Convert the user input into lowercase.
  • ·       Check the input with the keywords.
  • ·       If the keyword is found, it gives the output.
  • ·       Finally,when you give bye,the chatbot ends the process.

Program:

import java.util.Scanner;

public class ChatBotEg {

    public static void main(String[] args) {

        Scanner scanner1 = new Scanner(System.in);

        String userIn;

        System.out.println("Welcome to ChatBot world for memory storage. How can I help you  

        today?");

        while (true) {

            userIn = scanner1.nextLine();

            String response1 = getResponse(userIn);

            System.out.println(response1);

            if (userIn.equalsIgnoreCase("bye")) {

                break;

            }

        }

        scanner1.close();

        System.out.println("Thank you for using ChatBot World.Goodbye!");

    }

    public static String getResponse(String input) {

        input = input.toLowerCase();

        if (input.contains("hi") || input.contains("hello")) {

            return "Hello! Shall I help you?. ask me questions about memory";

        } else if(input.contains("what is a bit")) {

            return "bit is a binary digit";}

        else if(input.contains("nibble")) {

            return "Nibble is 4 bit binary digit";

        } else if(input.contains("byte")) {

            return "byte is a 8 bit binary digit";

        } else if(input.contains("kb")) {

            return "Kilobyte is 1024 bytes.It is represented as KB";

        } else if(input.contains("mb")) {

            return "Megabyte is 1024 kilobytes.It is represented as MB";

        } else if(input.contains("gb")) {

            return "Gigabyte is 1024 megabytes.It is represented as GB";

        } else if(input.contains("tb")) {

            return "Terabyte is 1024 Gigabytes.It is represented as TB";

        } else if(input.contains("pb")) {

            return "Petabyte is 1024 Terabytes.It is represented as PB";

        } else if(input.contains("eb")) {

            return "Exabyte is 1024 petabytes.It is represented as EB";

        } else if(input.contains("zb")) {

            return "Zettabyte is 1024 Exabytes.It is represented as ZB";

        } else if(input.contains("yb")) {

            return "Yottabyte is 1024 Zettabytes.It is represented as YB";

        }

        else {

            return "I'm not sure how to respond to that.";

        }

    }

}

Output:

C:\raji\blog>javac ChatBotEg.java

C:\raji\blog>java ChatBotEg

Welcome to ChatBot world for memory storage. How can I help you today?

hi

Hello! Shall I help you?. ask me questions about memory

byte

byte is a 8 bit binary digit

kb

Kilobyte is 1024 bytes.It is represented as KB

gb

Gigabyte is 1024 megabytes.It is represented as GB

tb

Terabyte is 1024 Gigabytes.It is represented as TB

zb

Zettabyte is 1024 Exabytes.It is represented as ZB

yb

Yottabyte is 1024 Zettabytes.It is represented as YB

bye

Thank you for using ChatBot World.Goodbye!

This is a simple Chatbot implemented in java. Keep coding!!!

Calculator Application in java

Let us create a simple Calculator project in java. It has four options. Addition, Subtraction, Multiplication and Division.

Steps:

  • Get the input from user for the type of arithmetic operation as integer(1,2,3 or 4).
  • Get the two inputs from the user.
  • Using switch case, choose the case according to the user input.
  • Process the statement and print the output.

Program:

   import java.util.Scanner;

   public class CalculatorApp {

       public static void main(String[] args) {

           Scanner scanner1 = new Scanner(System.in);

           System.out.println("Simple Calculator Application");

           System.out.println("Choose an operation:");

           System.out.println("1. Addition");

           System.out.println("2. Subtraction");

           System.out.println("3. Multiplication");

           System.out.println("4. Division");

           int choice1 = scanner1.nextInt();

           System.out.print("Enter the first number: ");

           double no1 = scanner1.nextDouble();

           System.out.print("Enter the second number: ");

           double no2 = scanner1.nextDouble();

           double res = 0;

           switch (choice1) {

               case 1:

                   res = no1 + no2;

                   System.out.println("Addition of two numbers: " + res);

                   break;

               case 2:

                   res = no1 - no2;

                   System.out.println("Subtraction of two numbers: " + res);

                   break;

               case 3:

                   res = no1 * no2;

                   System.out.println("Multiplication of two numbers: " + res);

                   break;

               case 4:

                   if (no2 != 0) {

                       res = no1 / no2;

                       System.out.println("Division of two numbers: " + res);

                   } else {

                       System.out.println("Error: Division by zero is not allowed.");

                   }

                   break;

               default:

                   System.out.println("Invalid choice. Please select a valid operation.");

           }

           scanner1.close();

       }

   }

C:\raji\blog>javac CalculatorApp.java

C:\raji\blog>java CalculatorApp

Simple Calculator Application

Choose an operation:

1. Addition

2. Subtraction

3. Multiplication

4. Division

1

Enter the first number: 56

Enter the second number: 67

Addition of two numbers: 123.0

 

C:\raji\blog>java CalculatorApp

Simple Calculator Application

Choose an operation:

1. Addition

2. Subtraction

3. Multiplication

4. Division

2

Enter the first number: 78

Enter the second number: 45

Subtraction of two numbers: 33.0

C:\raji\blog>java CalculatorApp

Simple Calculator Application

Choose an operation:

1. Addition

2. Subtraction

3. Multiplication

4. Division

3

Enter the first number: 34

Enter the second number: 5

Multiplication of two numbers: 170.0

 

C:\raji\blog>java CalculatorApp

Simple Calculator Application

Choose an operation:

1. Addition

2. Subtraction

3. Multiplication

4. Division

4

Enter the first number: 67

Enter the second number: 4

Division of two numbers: 16.75

 

C:\raji\blog>java CalculatorApp

Simple Calculator Application

Choose an operation:

1. Addition

2. Subtraction

3. Multiplication

4. Division

5

Enter the first number: 67

Enter the second number: 78

Invalid choice. Please select a valid operation.

 

C:\raji\blog>java CalculatorApp

Simple Calculator Application

Choose an operation:

1. Addition

2. Subtraction

3. Multiplication

4. Division

4

Enter the first number: 69

Enter the second number:

0

Error: Division by zero is not allowed.

Thus the simple Calculator project is written and executed successfully. Keep coding!!!!

Java Program to find Longest Substring Without Repeating Characters

              It is a typical problem in Strings. As the name indicates this concept reads a substring that should not contain any repeated characters.

To solve this problem, let us use a “Sliding Window Approach”. This approach deals with a window slide around the data.

Logic:

  • ·       A window is maintained.
  • ·       It has two pointers to point the start and end of the window.
  • ·       When the window slides, pointers may expand or contract.

Steps:

  • ·       Import the built in packages import java.util.HashMap and import java.util.Scanner.
  • ·       Create a public class with a constructor and main() function.
  • ·       Inside the constructor, initialize the pointers for start and longest.
  • ·       At first, assign the values as zero.
  • ·       Using a HashMap, create an object.
  • ·       A loop is created to check for non-repeatable sub string.
  • ·       To expand the window: it tracks the characters in current window and add the current character to HashMap object.
  • ·       It also moves the pointer to right.
  • ·       To contract the window: it checks the uniqueness of character and keep the window characters unique.
  • ·       The length of maximum characters in substring is noted.
  • ·       The loop is repeated until the entire string.
  • ·       ‘main()’ function reads the string from user. Call the constructor and print the length of longest substring.

Program:

import java.util.HashMap;

import java.util.Scanner;

public class longestUniqueSubstringEg {

    public static int longestUniqueSubstringEg(String s) {

        HashMap<Character, Integer> chIndexMap = new HashMap<>();

        int longer = 0;

        int start = 0;

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

            char currentChar = s.charAt(index);

            if (chIndexMap.containsKey(currentChar) && chIndexMap.get(currentChar) >= start) {

                start = chIndexMap.get(currentChar) + 1;

            }

            chIndexMap.put(currentChar, index);

            longer = Math.max(longer, index - start + 1);

        }

        return longer;

    }

    public static void main(String[] args) {

        Scanner scanner1 = new Scanner(System.in);

        System.out.print("Enter the String:");

        String ipStr= scanner1.nextLine();

        int res = longestUniqueSubstringEg(ipStr);

        System.out.println("Here, is the length of the longest substring without any repetition: " + res);

    }

}

Output:

C:\raji\blog>javac longestUniqueSubstringEg.java

C:\raji\blog>java longestUniqueSubstringEg

Enter the String:abcdef

Here, is the length of the longest substring without any repetition: 6

Thus, the java program to find Longest Substring Without Repeating Characters is explained. Keep coding!!!

Meeting Maximum Guests Problem – Java implementation

    Imagine a party. Many guests are coming. You want to calculate the maximum number of guests in the party hall at a particular time given to you.

How will you do this????

First, Get the inputs. The inputs are two array of integers given below.

‘arrive[]’ – This represents the guests who enters the party hall at that time.

‘depart[]’ – This represents the guests who leaves the party hall at that moment.

Note:

Always check both array’s length should be same in size.

Arrival entry should be entered in ‘arrive[]’ and Departure entry should be noted in ‘depart[]’.

Algorithm:

  • Get the inputs ‘arrive[]’ and ‘depart[]’;
  • Sort the arrays.
  • Let us declare two pointers ‘i’ and ‘j’. ‘i’ points arrive[] and ‘j’ points depart[].
  • Call the function finditMaxGuests()
  • This function check the condition to proceed.
  •   If arrive[i]<=depart[j] then, a guest came into the party hall. Increase the count of arrive[].
  •   Otherwise, decrease the count of depart and move on.
  • Finally, print the value of maximum guests in the party at a particular time.

Here, is the program.

import java.util.Arrays;

import java.util.Scanner;

public class MeetingMaxGuestsEg {

    public static void main(String[] args) {

         Scanner scanner1 = new Scanner(System.in);

          System.out.print("Enter number of guests arrived: ");

          int no = scanner1.nextInt();

          int[] arrive = new int[no];

          for (int i = 0; i < no; i++)

          {

           System.out.print("Enter the next one: ");

           arrive[i] = scanner1.nextInt();

          }

          Scanner scanner2 = new Scanner(System.in);

          System.out.print("Enter number of guests leaved: ");

          int no1 = scanner2.nextInt();

          int[] depart = new int[no];

          for (int i = 0; i < no1; i++)

          {

           System.out.print("Enter the next one: ");

           depart[i] = scanner2.nextInt();

          }

        System.out.println("Maximum number of guests at the party: " + finditMaxGuests(arrive, depart));

    }

     public static int finditMaxGuests(int[] arrive, int[] depart) {

        Arrays.sort(arrive);

        Arrays.sort(depart);

        int mGuests = 0;

        int cGuests = 0;

        int i = 0, j = 0;

        while (i < arrive.length && j < depart.length) {

            if (arrive[i] <= depart[j]) {

                cGuests++;

                mGuests = Math.max(mGuests, cGuests);

                i++;

            } else {

                cGuests--;

                j++;

            }

        }

        return mGuests;

    }

}

Output:

C:\raji\blog>javac MeetingMaxGuestsEg.java

C:\raji\blog>java MeetingMaxGuestsEg

Enter number of guests arrived: 10

Enter the next one: 1

Enter the next one: 3

Enter the next one: 5

Enter the next one: 7

Enter the next one: 9

Enter the next one: 11

Enter the next one: 15

Enter the next one: 2

Enter the next one: 4

Enter the next one: 6

Enter number of guests leaved: 4

Enter the next one: 6

Enter the next one: 3

Enter the next one: 45

Enter the next one: 34

Maximum number of guests at the party: 2

That’s all. The java program to find the maximum guests in the party is clearly written. Keep coding!!!

Different ways of Sorting using built in functions-Java Programming

     Sorting is a process of arranging elements in particular order. It may be ascending and descending order.

Here, two examples are given to sort the elements using built in functions.

  • ·       Arrays.sort()
  • ·       Custom comparators

Java Program to sort integers using ‘Arrays.sort()’:

              This program reads the integer array from user. It process it using ‘Arrays.sort()’ function.

Finally, it prints the sorted integers.

Program:

   import java.util.Arrays;

   import java.util.Collections;

   import java.util.Scanner;

   public class SortEg1 {

       public static void main(String[] args) {

          Scanner scanner = new Scanner(System.in);

          System.out.print("Enter number of elements: ");

          int no = scanner.nextInt();

          int[] integerArray = new int[no];

          for (int i = 0; i < no; i++)

          {

           System.out.print("Enter element: ");

           integerArray[i] = scanner.nextInt();

          }

           Arrays.sort(integerArray);

           System.out.println(Arrays.toString( integerArray));

       }

   }

Output:

C:\raji\blog>javac SortEg1.java

C:\raji\blog>java SortEg1

Enter number of elements: 5

Enter element: 45

Enter element: 56

Enter element: 9

Enter element: 23

Enter element: 34

[9, 23, 34, 45, 56]

This is a normal sorting.

If you want to sort the data in reverse manner, let us use the custom comparators.

Java Program to sort the string elements in reverse order:

              This program reads the number of String elements and input strings from the user. Using the custom comparator, it sorts in reverse order.

At last, it prints the data.

Program:

   import java.util.Arrays;

   import java.util.Comparator;

   import java.util.Scanner;

   public class CustomSortEg {

       public static void main(String[] args) {

          Scanner scanner = new Scanner(System.in);

          System.out.print("Enter number of Strings: ");

          int no = scanner.nextInt();

          String[] a = new String[no];

          for (int i = 0; i < no; i++)

          {

           System.out.print("Enter element: ");

           a[i] = scanner.next();

          }

           Arrays.sort(a, Comparator.reverseOrder());

           System.out.println("Sorting in reverse order");

           System.out.println(Arrays.toString(a));

       }

   }

Output:

C:\raji\blog>javac CustomSortEg.java

C:\raji\blog>java CustomSortEg

Enter number of Strings: 5

Enter element: car

Enter element: van

Enter element: bike

Enter element: truck

Enter element: bus

Sorting in reverse order

[van, truck, car, bus, bike]

That’s all. These are the ways to sort the elements using built in functions.

Java Program to create a List and perform functions using Collections

    A set of elements grouped together under a common name is called a collection. To implement this, a package “java.util” is used. This package has many static methods and operates the collections.

Collections has some set of operations like reverse, search and sorting. Let us list the some of methods in the ‘Collections’ class.

Java Program to create a List and perform functions using Collections:

This program starts by importing the header files and has following steps.

Steps:

  • A public class is created with main() function.
  • A list object list1 is created as integer ArrayList.
  • To insert the values, use add() function.
  • Print the newly created list.
  • Now, sort the elements by sort() function using Collections.
  • Print the sorted list.
  • To search an element using binary search, a function binarySearch() is used.
  • It display the key position as output.
  • Next,the list is reversed using reverse() function.
  • The list is printed after the reversal.
  • To shuffle the data at random, a function shuffle() is used.
  • Finally, the list is displayed after shuffled.

Program:

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class CollEg1 {

    public static void main(String[] args) {

        // A list is created here

        List<Integer> list1 = new ArrayList<>();     

        // Let us add the elements to the list

        list1.add(43);

        list1.add(81);

        list1.add(25);

        list1.add(12);

        list1.add(56);

        System.out.println("The original list is:" + list1);

        //Sorting the list using collections

        Collections.sort(list1);

        // Display the list

        System.out.println("The Sorted List is: " + list1);

        //Searching an element using Binary Search

        int a =Collections.binarySearch(list1,25);

        System.out.println("The key is at Position :"+ a);

      //Reverse the list

        Collections.reverse(list1);

        //Print the list after reverse

        System.out.println("The Reversed List is: " + list1);

        //Shuffle the list

        Collections.shuffle(list1);

        //Print the list after shuffling

        System.out.println("The shuffled List is: " + list1);

            }

}

Output:

C:\raji\blog>javac CollEg1.java

C:\raji\blog>java CollEg1

The original list is:[43, 81, 25, 12, 56]

The Sorted List is: [12, 25, 43, 56, 81]

The key is at Position :1

The Reversed List is: [81, 56, 43, 25, 12]

The shuffled List is: [81, 25, 43, 56, 12]

This is the simple way of creating a list and perform operations using Collections. Hope you understand it. Keep coding!!!

Java Program to implement ‘Arrays’ and its member functions.

     Array has collection of elements. ‘Arrays’ is a built in class in java package java.util. This class contains many static methods to process array operations.

Some of the methods are listed below.

sort() :This function sorts the array elements.

parrelSort() : Suits for larger array to sort the elements parallel.

equals():It compares two arrays for equality.

binarySearch(): It uses binary Search method to find an element.

fill() :it fills a data for set of elements.

toString(): It converts the array to String

asList():It converts the array to List.

Stream():it is used for Stream operations.

copyOf(): It copys the array elements into another array.

copyOfRange(): it copys the data in the specified range and add to another array.

setAll(): All the elements are set by this method.

An example is given below.

#Java Program to implement ‘Arrays’ and its member functions.

import java.util.Arrays;

import java.util.Scanner;

public class ArrayEg3 {

    public static void main(String[] args) {

        Scanner scanner1 = new Scanner(System.in);

        //get the size of the array

        System.out.print("Please,Enter the size of the array: ");

        int size = scanner1.nextInt();

        // An array with specified size is created here

        int[] sample = new int[size];

        // Read the data elements by for loop

        System.out.println("Enter " + size + " elements:");

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

            sample[i] = scanner1.nextInt();

        }

       // Sort the data elements using sort()

        Arrays.sort(sample);

        System.out.println("Sorted: " + Arrays.toString(sample));

       // binarySearch() method of searching

        int index = Arrays.binarySearch(sample, 7);

        System.out.println("Index of 7: " + index);

       // Let us check for equality of two arrays

        int[] anotherArray = {11, 24, 45, 7, 19};

        boolean areEqual = Arrays.equals(sample, anotherArray);

        if(areEqual)

           System.out.println("Arrays are equal");

        else

           System.out.println("Arrays are not equal");

       // Fill the data with a data

        int[] fArray = new int[5];

        Arrays.fill(fArray, 12);

        System.out.println("The array after Filled data: " + Arrays.toString(fArray));

    }

}

Output:

C:\raji\blog>javac ArrayEg3.java

C:\raji\blog>java ArrayEg3

Please,Enter the size of the array: 7

Enter 7 elements:

23

4

67

56

34

98

87

Sorted: [4, 23, 34, 56, 67, 87, 98]

Index of 7: -2

Arrays are not equal

The array after Filled data: [12, 12, 12, 12, 12]

This is the way of using ‘Arrays’ in java. Enjoy Coding!!!!!