OOP – ASSIGNMENT XVI

Lab Manual Download: Write Programs in Java to sort i) List of integers ii) List of names.

ASSIGNMENT NO 16

Title: Implementation of sorting of Integer and String

Objectives: To learn arrays of integer and string type.

Problem Statement: Write Programs in Java to sort i) List of integers ii) List of names. The objective of this assignment is to learn Arrays and Strings in Java.

Outcomes: Students will be able to demonstrate use of arrays and bubble sort for integer and string array.

Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1 GB Hard Disk or more.

Software requirements: 64 bit Linux/Windows Operating System, JDK 1.4 or later

Theory:

Arrays:  An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Each item in an array is called an element, and each element is accessed by its numerical index. In a real-world programming situation, you would probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as in the preceding example

Declaring a Variable to Refer to an Array: The preceding program declares an array (named anArray) with the following line of code:

// declares an array of integersint[] anArray;

Like declarations for variables of other types, an array declaration has two components: the array’s type and the array’s name. An array’s type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array’s name can be anything you want, provided that it follows the rules and naming conventions.  As with variables of other types, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type. Similarly, you can declare arrays of other types:

byte[] anArrayOfBytes;

short[] anArrayOfShorts;

long[] anArrayOfLongs;

float[] anArrayOfFloats;

double[] anArrayOfDoubles;

boolean[] anArrayOfBooleans;

char[] anArrayOfChars;

String[] anArrayOfStrings;

You can also place the brackets after the array’s name:

// this form is discouragedfloat anArrayOfFloats[];

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating, Initializing, and Accessing an Array: One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.

// create an array of integersanArray = new int[10];

If this statement is missing, then the compiler prints an error like the following, and compilation fails:

ArrayDemo.java:4: Variable anArray may not have been initialized. The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element

anArray[1] = 200; // initialize second elementan

Array[2] = 300; // and so forth

Each array element is accessed by its numerical index:

System.out.println(“Element 1 at index 0: ” + anArray[0]);

System.out.println(“Element 2 at index 1: ” + anArray[1]);

System.out.println(“Element 3 at index 2: ” + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = {     100, 200, 300,    400, 500, 600,     700, 800, 900, 1000};

Here the length of the array is determined by the number of values provided between braces and separated by commas.

Strings: Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings: The most direct way to create a string is to write:

String greeting = “Hello world!”;

In this case, “Hello world!” is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world!.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’ };

String helloString = new String(helloArray);

System.out.println(helloString);

The last line of this code snippet displays hello.

The String class has a number of methods for comparing strings and portions of strings.

  1. int compareTo(String anotherString) : Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
  2. int compareToIgnoreCase(String str): Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.

Conclusion : In this assignment, we have studied arrays in Java and demonstrated their use in sorting integer and string array.

Roll No. Name of Student Date of Performance Date of Assessment Grade Sign of Student Sign of Faculty

PROGRAM

public class Sorting { 
    int arr[],num;
    String str[];
    Sorting()
    {
     System.out.println("Enter size of integer and string array");
      num=Integer.parseInt(System.console().readLine());
      arr=new int[num]; 
      str=new String[num];
     System.out.println("Enter "+num+" integer values");
     for(int i=0;i<num;i++)
        arr[i]=Integer.parseInt(System.console().readLine());
     System.out.println("Enter "+num+" string values");
     for(int i=0;i<num;i++)
        str[i]=System.console().readLine();   
     sortint(arr);
     sortstr(str);
}
public static void main(String args[])
{
    new Sorting();
}
void sortint(int arr[])
{
    int temp;
    for(int i=0;i<arr.length;i++)
    {
        for(int j=i+1;j<arr.length;j++)
        {
            if(arr[i]>arr[j])
            {
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
   }
    System.out.println("\n Sorted Integer array is: ");
    for(int i=0;i<arr.length;i++)
        System.out.print(arr[i]+"\t");
}
void sortstr(String str[])
{
     String temp;
    for(int i=0;i<str.length;i++)
    {
        for(int j=i+1;j<str.length;j++)
        {
            if(str[i].compareTo(str[j])>0)
            {
                temp=str[i];
                str[i]=str[j];
                str[j]=temp;
            }
        }
   }
    System.out.println("\nSorted String array is: ");
    for(int i=0;i<str.length;i++)
        System.out.print(str[i]+"\t");
}
}

OUTPUT:

Leave a Reply

Your email address will not be published. Required fields are marked *