Java Basic Problems

Java: How to sort string in alphabetical order.

In my last post I have tried to share about How to convert integer variable to object type in java.Today I will share with you about how to sort string in an array alphabetically.

Here compareTo() function is used to sort string in an alphabetical order in java.

According to compareTo() function  a string is less than another if it comes before the other in   dictionary order and a string is greater than another if it comes after the other in dictionary  

order.

If you want to ignore case differences when comparing two strings, use compareToIgnoreCase( ),

 String sorting in alphabetical order in java

Code Example:

class StringOrder

{

 static String name[]={“Chittagong”,”Dhaka”,”Rangpur”,”Sonargaon”,”Bangladesh”};

public static void main(String args[])

{

int size= name.length;

String temp=null;

System.out.println(“\n”);

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

{

for(int j=i+1;j<size;j++)

{

if(name[j].compareTo(name[i])<0)

{

//System.out.println(“name[j]:”+name[j]+”compareTo(name[i]):< 0:”+name[i]);

temp=name[i];

name[i]=name[j];

name[j]=temp;

}}}

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

{

System.out.println(name[i]);

}}}

Java Basic Problems

Java: Add value to a vector which is inside another vector.

Sometimes what we do in java programming, we add value to a vector and then adds that vector to another vector (Vector inside another vector).

For example

(“X”,”Y”,”Z”) is in Vector    name

name.add(“X”);

name.add(“Y”);

name.add(“Z”);

(“M”, “N”,”O”) is in Vector name1

name1.add(“M”);

name1.add(“N”);

name1.add(“O”);

Add  this  name and  name1 vector in nameContainer Vector

nameContainer.add(name);

nameContainer.add(name1);

So, if you want to add another value  or    modify  the vector  name and name1  which are inside nameContainer Vector,  do the following  according to the given code.

Code Example

 import java.util.Vector;

public class VectorDemo

{

 VectorDemo()

{

Vector name=new Vector();

Vector name1=new Vector();

Vector name2=new Vector();

name2.add(“Its me”);

Vector nameContainer=new Vector();

name.add(“X”);

name.add(“Y”);

name.add(“Z”);

nameContainer.add(name);

name1.add(“M”);

name1.add(“N”);

name1.add(“O”);

nameContainer.add(name1);

System.out.println(“Before NameContainer Value:”+nameContainer.get(0));

((Vector)nameContainer.get(0)).add(“HI”);

System.out.println(“name get 0 and 1:”+name.get(0)+” “+name.get(1));

System.out.println(“AfterNameContainer Value:”+nameContainer.get(0));

((Vector)nameContainer.get(0)).add(name2.get(0));

System.out.println(“AfterNameContainer Value:”+nameContainer.get(0).toString());

}

public static void main(String args[])

{

VectorDemo x=new VectorDemo();

}

}

OUTPUT: