Wednesday 20 February 2013

Class X -String

Points to remember : (Refer the String post)
1.  ASCII codes :
      A - Z   = 65 - 90
      a - z    = 97 - 122
The difference between a capital and its equivalent small letter is 32.
2. To input a character:
e.g :
char x =  (char)System.in.read( );
3. The difference between next() and nextLine( ) is
next( ) used to input a string without the space whereas
nextLine( ) used to input a line of text.
4. Difference between String and StringBuffer:
String : immutable i.e the characters that the string contains cannot be modified or changed.It has fixed length.
StringBuffer : mutable i.e the string can be changed. Flexible length.

Both are defined in java.lang, so it is available automatically.

5. Exception : unexpected situation encountered by the program.
throws: keyword to inform that an error has occured.
6. String array
 String name[] = new String[10];
10 is not the size of the string , it is the size of the array.
7. Static variable : It is also called class variable. A data member which is declared for a class, ans all the objects share this data member.
   Static method : function which uses static keyword as a modifier.
8. Group of logically related classes together are called Package.

Arrange the names in ascending order:

class sort
{
public static void main()
{
String name[]={........};------Assign names.
int l=name.length;------length of the array not string
int i,j;
String temp=" ";
for(i=0;i< l-1; i++)
{
for(j=0;j< l-i-1; j++)
{
if(name[j].compareTo(name[j+1])>0) ---comparing strings
  {
    temp=name[j];
    name[j]=name[j+1];
    name[j+1]=temp;
   }
  }
}
for(i=0;i<l;i++)
System.out.println(name[i]);
}
}
}

Binary search :
It is similar to numerical search except few changes. Assume there are 10 names and string n should be searched.
int u=9,l=0,mid=0, flag =-1;
while(l<=u)
{
mid=(l+u)/2;
if (n.compareTo(name[mid])==0)
{
flag=mid;
break;
}
else if  (n.compareTo(name[mid])>0)
{
l=mid+1;
}
else if (n.compareTo(name[mid])<0)
{
u=mid - 1;
}
}
if(flag== -1)
System.out.print("Not found in the list");
else
System.out.print("Name"+n+"is at"+flag+"index");
}

No comments:

Post a Comment