Monday, 14 January 2013

Class X - Strings

Strings are made up of characters.A character in a string can be refered by its position in the string.The index of the first character in a string is 0.String value cannot be changed.So string is immutable.
String functions:
1. charAt(index)
        It gives the character at the specified index.
        String s="Computer Application";
         char x=s.charAt(3);
        The answer is p,since index starts from 0.
2. indexOf(character)
        It gives the index of the first occurance of the given character.Its just opposite of charAt.
          String s="reading books";
           int x=s.indexOf('0');
           The answer will be  9,since space is also part of a string
3. lastIndexOf(character)
           It gives the index of the last occurance of the given character.
            String s="reading books";
            int x=s.lastIndexOf('0');
           The answer will be  10.
4. length()
           It gives the total characters in the string.It value statrs from 1 not 0.Therefore the length of "BCBS" is 4.It includes even the space. Remember the length of the array is length, whereas string is length().
5. toLowerCase()
          Converts the string to lowercase letters.
          String s="BORDER";
          String s1=s.toLowerCase();
          The answer will be computer.
6.toUpperCase()
            Converts the string to uppercase letters.
            String s="tension";
            String s1=s.toUpperCase();
            The answer will be TENSION.
7. equals()
          Compares two strings and return true if both are same else it will return false.
           String s="Boys";
            String s1="boys";
           s.equals(s1) will give you false.
8. equalsIgnoreCase()
          Returns true even if the strings are of different cases.
          String s="Boys";
            String s1="boys";
           s.equals(s1) will give you true since it is ignore case.
9.  compareTo()
          Compares two strings lexicographically.
          It gives 0 if both the strings are equal. value less than 0 if string1 lexicographically less than string2, value greater than 0 if string1 lexicographically greater than string2.
          String a="Computer";
          String b="Application";
          int n=a.compareTo(b);
          if a and b are same then  n=0,
          if a is greater than b then  n>0,
          if a is less than b then  n>0,  i am refering  a  always coz in the syntax i have given a first.
10. startsWith()
          The result is true if the given string begins with a specified string.
11.endsWith()
          The result is true if the given string ends with a specified string.
12. substring(int n )
        Removes the part of the string till the end of the string
13. substring(int start, int end)
        Removes the part of the string from starting from the index start upto character at the index end without including it.
  String s="something";
String s1=s.substring(2,5);
The answer will be met.
14. replace(char ch1,char ch2)
         It gives a new string obtained by replacing every occurance of character ch1 by character ch2.
              

StringBuffer:
You cannot change the size or the content once the strings are created.However, sometimes we need to have a dynamic string that can be modified.So we are using StringBuffer instead of string.
     To assign a value:
  StringBuffer s=new StringBuffer("Computer");
1. append(char ch)
          It adds a character to the end of the StringBuffer.
2. insert(int index, char ch)
          Inserts a character into the StringBuffer at the specified index.
3. setCharAt(int index,char c)
        It changes the character with ch in the specified location
4. reverse()
5. capacity()
       It gives the amount of memory space allocated.       
6. delete(index1,index2)
      It deletes the characters from index 1 to index2
Character Functions :
1. Character.isLetter()
      Checks whether the character is a letter or not.
2.Character.isDigit()
      Checks whether the character is a digit or not.
3. Character.isLetterOrDigit()
      Checks whether the character is a letter or digit.
4. Character.isWhiteSpace()
      Checks whether the character is a space or not.
5. Character.isUpperCase()
       It checks whether the character is a uppercase letter.There is a difference between toUpperCase and isUpperCase.refer string functions.
6. Character.isLowerCase()
       It checks whether the character is a uppercase letter.There is a difference between toLowerCase and isLowerCase.refer string functions.
7.Character.toUpperCase()
          Changes the character into uppercase letter.There is a string function also.This is only for a particular character.
8.Character.toLowerCase()
       Changes the character into lowercase letter.There is a string function also.This is only for a particular character.  
Converting string data type to other data types:

 String to integer
    i.  Integer.parseInt (string) or
        Integer.valueOf(string)
 same way you convert string into long,float double.Replace Integer with the corresponding data type.

Converting primitive data types to string :

Integer to string
  Integer.toString(integer);
 Now you can't do any mathematical operations with this number.
same way you convert long,float double to string.Replace Integer with the corresponding data type.

       


Sunday, 13 January 2013

Class X - Arrays

Array is an interesting topic.Imagine a situation where you want to input the names of students in your class along with the roll no and 3 subjects marks. There are 50 boys in your class. Then how many variables you need? There is no point in writing a program. Array comes in handy in such a situation .

An array is a collection of variables of same data type. Each element in an array is refered by the array name with the subscript or index.It is enclosed in square bracket [ ], whereas methods use ( ).
  • Declaration
  • Memory allocation
  • Initialization
Declaration:
Like the normal declaration of variables, we need to declare the array also.
data type array name[];

int marks[];
Memory allocation:
data type array name[]=new datatype[size];

int a[]=new int[10];
How many values you are going to use should be mentioned where it is given size.The common mistake we make here is writing the variable name after new.
int a[]=new a[10]; is wrong
Initializing values
int a[]={10,20,30,40};
The place value of each element is called a subscript or an index. The index value starts from zero, so the last element index is one less than the size.
To find the length of an array use length.
int l=a.length;
No brackets.It finds the length of the array 'a' which is 4 and it is stored in a variable l;
To accept 10 values from the user.
Example 1: Blue J method
class ar1
{
public static void main(int a[])

Example 2:
import java.util.*;
class ar1
{
public static void main()
   {
int a[]=new int[10];--------------------------1
Scanner s=new Scanner(System.in);
int i,l,s=0;
l=a.length;------------------------------------2
System.out.println("Enter the values");
for(i=0;i<l;i++)------------------------------3
a[i]=s.nextInt();------------------------------4
for(i=0;i<l;i++)
s=s+a[i];-------------------------------------5
 
System.out.println(a[i]);
   }
}
Step 1 : an array a is created ,
Step 2 :finds the  Length
Step 3 : index starts from 0 and less than length l
Step 4 : The values are store in a.First value is stored in
a[0], second in a[1] and so on
Step 5: When i=0, a[0] value is added to s, when i=1 ,a[1] is added and so on..

Search 
  • Linear
  • Binary

import java.util.*;
class linear{
public static void main()
   {
int a[]=new int[10];
Scanner s=new Scanner(System.in);
int i,l,n,flag=0;
l=a.length ;
System.out.println("Enter the values");
for(i=0;i<l;i++)
a[i]=s.nextInt();
System.out.println("Enter the number to be searched");
n=s.nextInt();
for(i=0;i<l;i++)
{
   if(a[i]==n)
     {
       flag=1;
        break;
    }
}
if(flag==1)
System.out.print(n+"found");
else
System.out.print(n+"not found");
  }
}

Initially flag is 0, if the number is found the flag value will change to 1.

Binary Search
This might look little complicated,but if you understand how it works,it is a cake walk.
The prerequisite is that the array elements should be arranged in some order either in ascending or descending.
In the boards generally the question will not ask you to sort and search in the same program.
The linear search takes more time since it has to check each and every element sequentially.It is a good idea but not a great one.
So, here in binary search the idea is divide the array and discard whatever not necessary.
Step 1: we are going to divide the array into  two parts.For that we should find the middle value.
Step 2: Compare the number  to be searched say 'n' with the middle value say 'm'.If both are same,  Bingo.
Step 3: If the n is smaller than m, then you would find n in the first half ,if the array  is arranged in ascending order.Then you dont want the second part anymore.discard it. So the length changes after you discard the second part.Lower index value remains the same that is 0, but upper limit becomes middle value - 1.Then step 2 will be repeated.
If the n is bigger than m, then you would find n in the second half ,if the array  is arranged in ascending order.Then you dont want the first part anymore.discard it. So the length changes after you discard the second part.Upper index value remains the same, but lower limit becomes middle value + 1.Then step 2 will be repeated.
Example :

The array is
 14 ,  23,  28, 36,  69,  88
The number to be searched is 23.
Step 1:
Middle value = (lower index +Upper index)/2
                      = (0+5)/2
                      = 2.5
Either round off or truncate it. Let us take 3.So the middle value is 36.
Step 2 :
Compare 23 and 3 rd element 36.Both are not same.
Step 3 :
23 is smaller than 36, that means 23 will not be there after 36.
so discard second half, that is elements after 36.Lower index is still 0, and upper index becomes the value before the middle value , i.e 28.Checking will go on till it finds the value.
If the value to be searched is 88 then,
88 is bigger than 36, therefore 88 will not be in the list before 36.
so discard first half, that is elements before 36.upper index remains the same and lower index becomes the value after the middle value. Checking will go on till it finds the value. Otherwise  it will print the nmber not in the list.class binary
{
public static void main(int a[],int n)---------------------------1
{
int l,i,mid,place,flag=0;
l=a.length;--------------------------------------------------------2
int low=0,up= l -1;----------------------------------------------3
while(low <= upp)----------------------------------------------4
{
      mid = (low+up)/2;------------------------------------------5
      if(a[mid]==n)
         {
              flag=1;------------------------------------------------6
              place=mid;--------------------------------------------7
              break;-------------------------------------------------8
         }
      else if(a[mid] < n)-----------------------------------------9
            low=mid+1;
      else
            upp=mid - 1;
}
if(flag==1)
System.out.print(n+"is found at+(place+1));-----------------10
else
System.out.print(n+"is not found ");

}

}
step 1: input the array, number to be searched
step 2: find the length of the array
step 3:initialize the values for lower and upper index. l-1 coz, index starts from 0.
step 4:the loop should continue as long as lower limit is less than upper limit.
step 5:find the middle value.common mistake here is
(a[low]+a[upp])/2
step 6:there is some variable with some intial value so that when we find the number, change that value.If the value is not changed then it means the number is not found,coz you would not have gone to step 6.
step 7: if you want to find exactly where the number occurs in the array,then assign the mid index, not mid value.It is not a[mid].
step 8:Once we found the number,come out. no more searching.
step 9:check the number with middle value , change the low or upper index accordingly.
Isn't that easy.


Sorting Arrays
  • Selection Sort
  • Bubble Sort
Before we go to sorting , learn how to swap two values.
let us take x=30 and y=20, now interchange these two in java.
we might write
        x=y;
        y=x;
Now the value of x will be 20 and y also will be 20, coz in the first line y is assigned to x.Therefore the value of x is 20.In the second line ,we assign 20 to y not 30.Therefore we need one more temporary variable.
       temp=x;
        x=y;
        y=temp;
temp takes the value 30, x becomes 20, and y becomes 30.
Bubble Sort:
import java.util.*;
class bubble{
public static void main()
   {
int a[]=new int[10];
Scanner s=new Scanner(System.in);
int i,j,l,temp;
l=a.length ;
System.out.println("Enter the values");
for(i=0;i<l;i++) -----------------------------------1
a[i]=s.nextInt();-----------------------------------2

for(i=0;i< l-1;i++)--------------------------------3
{
    for(j=i+1;j<l;j++)------------------------------4
      {
         if(a[i]>a[j])----------------------------------5
           {
              temp=a[i];
              a[i]=a[j];
               a[j]=temp;
           }
     }
}
System.out.println("The values after sorting");
  for(i=0;i<l;i++)
System.out.println(a[i]);
}
}

step 1 and 2  : input values
step 3 and 4 : There should be 2 loops,so that we compare the top most element with the least value.
step 4: If the top value is bigger(in case you want to sort in ascending order) the you should change it.Therefore swap the values.
Selection Sort :
import java.util.*;
class selection
{
public static void main()
   {
int a[]=new int[10];
Scanner s=new Scanner(System.in);
int i,j,l,temp,loc;
l=a.length ;
System.out.println("Enter the values");
for(i=0;i<l;i++) 

a[i]=s.nextInt();
for(i=0;i< l-1;i++)
{
      small=a[i];---------------------------------------1
      loc=i;---------------------------------------------2
    for(j=i+1;j<l;j++)
        {
            if(small > a[j])------------------------------3
              {
                 small=a[j];-------------------------------4
                 loc=j;
              }
        }
        temp=a[i];------------------------------------5
        a[i]=a[loc];
        a[loc]=temp;
    }
System.out.println("The values after sorting");
  for(i=0;i<l;i++)
System.out.println(a[i]);
}
}

step 1 : Take the value in ith place as the small value.Initially the first value is small.So that we can compare it with other values.
step 2: Record the location of that value
step 3 :Compare the small value with the other values
step 4 :If small is bigger than the other value then assign that value to small.
step 5: Swap the values
 Write a program to pass an array to a function:
import java.util.*;
class arr2
{
void get(int a[], int l)
{   int i;
    for(i=0;i<l;i++) 
    System.out.println(a[i]);
}
public static void main()
   {
arr2 ob=new arr2();

int a[]=new int[10];
Scanner s=new Scanner(System.in);
int i,j,l,temp;
l=a.length ;
System.out.println("Enter the values");
for(i=0;i<l;i++) 

a[i]=s.nextInt();
ob.get(a,l);
}
}

Saturday, 12 January 2013

Class X - Constructors

Its not ROCKET  SCIENCE.....

Its just COMPUTER SCIENCE .....
Constructor is similar to method .
  • It has the same name as the class.
  • It has no return value not even void.
  for e.g
                  int print( )
                  print ( )
from the above two functions ,the first one cannot be a constructor because of the data type int before the function name.
Characteristics of constructors :
  • It initializes the data members .
  • It is called when the object is created.
  • It cannot be inherited.
There are two types of constructors :
  • Default constructor or non parameterized
  • Parameterized constructor
Default constructor accepts no parameter.
Parameterized constructor accepts parameter.

Example 1:
A class commision is defined with the following specifications :
Class name   : commision
Data members  : double salary(per week)
                              double com(amount per item sold)
                               int qty(total items sold in a week)
Member functions :
commision(double s,double c,int q)
void earn( ) -calculate the total salary
Write a main method to create the object.
class commision
{
double salary,com;------------------------------1
int qty;--------------------------------------------2
commision(double s,double c,int q)-----------3
{
salary =s;-----------------------------------------4
com=c;-------------------------------------------5
qty=q;--------------------------------------------6
}

void earn()
{
     System.out.print((salary+com*qty));
}
public  void main( )
{
commision ob=new commision(20000.0, 15.5, 300);--------7
ob.earn(); ------------------------------------8
}
}
The class name and function name are same so it is a constructor.There are values passed to it,so it is a parameterized constructor.
Steps 1 and 2 are global variables.Refer methods to learn about it.
Step 3 is the papameterized constructor.
In steps 4 to 6 local values are assigned to global variables.earn ia method,since the name is different and also there is a data type void.
In step 7, ob is created, and the values are in order.
commision(sal,com,qty).
In step 8, earn() is called. DONOT call a constructor using the object coz constructors are called automatically  called when the object is created.So do not write ob.commision().

Example 2 :
Define a class Number to find the sum of the digits.
class name     :Number
Data members : int num
Member functions  :
 Number() - assign 0 to num
Number(int n) - assign n to num
void sum()
class Number
{
int num;
Number()
{
num=0;
}
Number (int n)
{
num=n;
}
void sum( )
{ int a,s=0;
while(num>0)
{
a=num%10;
s=s+a;
num=num/10;
}
System.out.print(s);
}
public void main( )
{
Number ob=new Number(145);
ob.sum();
}
}
In the above program both the constructor types are used.Just follow what is given in the question.Make sure the names and variables are used as it is given in the question.
Remember to write the global variable on the left hand side and local variable on the right hand side in  the constructor Number(int n).Donot mix it up

I will keep posting the other chapters in the coming days.If you have any doubts mail me at kavitha.m.samuel@gmail.com

Class X- Method

Its not ROCKET  SCIENCE.....

Its just COMPUTER SCIENCE .....



METHODS
When our program is too complicated, the best approach is to divide it into smaller sections, so that it is easy to write the code and also easy to debug.
If we want to use  a set of statements in more than one place, instead of writing the same code  again and again,we can write it once and call it wherever we need it.
For instance
*******************************************************
WELCOME TO MY BLOG
*******************************************************
Class X Notes.

*******************************************************
class example1
{
    public static void main( )
       {
          System.out.println("******************************");
          System.out.println("WELCOME TO MY BLOG");
          System.out.println("******************************");
          System.out.println("Class X Notes");
              System.out.println("****************************");
      }
}
In the above program the highlighted lines are repeated 3 times. We can reduce the code by writing once and calling it 3 times.
class example1
{
    public static void main( )
       {          
                    star( );
                    System.out.println("WELCOME TO MY BLOG");
                    star( );
                    star( );
                 }
public static void star ( )
     {
                Sytem.out.println("*****************************");
      }
}
Method Header
access_specifier  modifier  return data_type method name( )e.g :
 public static void main() 
 

NOTE
  • The other name for method is FUNCTION
  • A method can be easily identified .A method name is always followed by the opening and closing parantheses ( ).
  • A method name must begin with a letter or an underscore, it also can contain letters, numbers and underscore.
  • Access specifier and modifier are optional.
  • main( )  method can be written anywhere in the program.
Function header or prototype
The first line of the method with the name of the method,data type of the return value, number and the type of arguments is called the header or prototype.
Function Signature
It is the number and types of arguments.
1. Example
Write a program to add two numbers .
class addition{
public static void main( )
  {
     int a=10,b=45; --------------------------------------------1
     int s= add(a,b); -------------------------------------2,6     System.out .print("Sum = "+s);-----------------------7
}
 int add(int a,int b)----------------------------------------3
  {      int c;
       c=a+b;-----------------------------------------------4
       return  c; --------------------------------------------5 
  }
}
In the above program , the numbers are the order in which the program will be executed. In the step 2, add( ) is the method name,this is the function call.the control will go to the function in step 3.The method statements will be executed.And the answer will be sent to the step which called the function, that is step 2.The answer is stored in variable s.The data type of the answer is int that is why the return data type is int in function header. Step 2 is also called calling a funtion or invoking a function.
Tha above program can be written like this:

class addition
{
public static void main( )
  {
     int a=10,b=45; --------------------------------------------1
      add(a,b); -------------------------------------2   
}
 void add(int a,int b)----------------------------------------3
  {      int c;
       c=a+b;-----------------------------------------------4
       System.out.print(c); -----------------------------------5 
  }
}
There is a change in step 2, the answer is not stored in any variable .The answer is displayed in the method add itself, thats why there is no return statement and also the datatype is void in function header.  a and b in step 2 are called actual parameters ,a and b in step 3 is called formal parameters.
2. Example 
 Write a program to find the factorial of a number .
class factorial
{
public static void main( )
  {
     int n=5; --------------------------------------------1
     int x= fact(n); -------------------------------------2,8
     System.out .print("Factorial = "+x);------------9
}
 int fact(int n)----------------------------------------3
{
     int i,f=1; ------------------------------------------4
    for(i=1;i<=n;i++)---------------------------------5
     f=f*i; ----------------------------------------------6
  return f; --------------------------------------------7
}
}
After the  step 2 the control will go to the function fact.It will complete all the statements there and send the answer back to main function. The answer will be an integer value ,thats why the return data type is int.
3. Example
Write a program to display the sum of the series
13+23+33+….n3
using the function cube()
class sum

{
public static void main(int n)---------1
{
int i,s=0;
for (i=1;i<=n;i++)
s=s+cube(i);
System.out.print("Sum="+s);
}
public static int cube(int a)
  {
    int c=a*a*a;
    return c;
   }
}
In step 1 you should accept the value of ' n ' from the user. In the above question we should find the cube of each number.We write the code for this once, but call it again and again.

Let me introduce the scope of variables here......

The scope of the variable is nothing but where all you can use a particular variable in a program.
  • Local variable - Variable which is declared inside any function.You can use the variable only in that function not throughout the program .
  • Global variable - variable declared ouside all functions. i.e. just after class.This can be used anywhere in the program.
Example 4
Define a class salary describesd as below:
Data members : Name,Address,Subject,Salary,Income tax
Member methods :
  1.   accept the details of the teacher
  2. display the details
  3. compute the income tax as 5% of the annual salary above Rs.1,75,000.
Write a main method to create an object .
import java.util.*;
class salary
{
String name,address,subject;-----------1
double sal,it;--------------------------2
void get(String n,String add,String sub,double s1)------3
{
  name=n;
  address=add;
  subject=sub;
  sal=s1;
}
void compute()
{  
   int a=sal*12 ;
  if(a > 175000)
          it=0.05* a;
  else
          it=0;
}

void display( )
{
  System.out.println("Name="+name);
  System.out.println("Address="+address);
  System.out.println("Subject="+subject);
  System.out.println("Salary="+sal);
  System.out.println("tax="+it);
}
public static void main()
{
   salary ob=new salary();---------------------------4
   Scanner s=new Scanner(System.in);
    System.out.println("Enter the name");
    name=s.next();
    System.out.println("Enter the address");
    address=s.next();
    System.out.println("Enter the subject");
    subject=s.next();
    System.out.println("Enter the  Monthly salary");
   salary=s.nextDouble();
   ob.get(name,address,subject);
   ob.compute();
   ob.display( );
}
}

Steps 1 and 2 are the global variables.You can use them anywhere in the program. In step 3, the values received from the main method . and in   get ()  the values are stored in global variable for the same reason mentioned above.compute() and display() are according to the question.In step 4, we create an object. salary is the calss name,donot use anything else, ob is the object name,you can give any name. new is the keyword, it allocates memory for the object.
Remember to write the global variable on the left hand side and local variable on the right hand side in void get().Donot mix it up
Methods can be divided into
  • Pure method or accessors - methods donot change the state of an object.
  • Impure mentod or mutators - methods the change  the state of the object.
Method Overlaoding or Function OverloadingThere can be more than one method with the same name.But the problem is how the control will go to the method it is supposed to go.Thats why there should be  some difference in the methods.So method overloading will have more than one method with same name but differ in the number or types of arguments or both.   
Write a program using a function called area( ) to do the following :
  1. Area of a circle
  2. Area of a square
  3. Area of a rectangle

import java.util.*;
class menu
{
public void area(int r)
{
System.out.println("Area of circle="+(3.14*r*r));
}
public void area(int l,int b)
{
System.out.println("Area of rectangle="+(l*b));
}
public void area(float side)
{
System.out.println("Area of square="+(side*side));
}
public  void main( )
{
   Scanner s =new Scanner(System.in);
   System.out.println("Enter radius");
   int r=s.nextInt();
   System.out.println("Enter length and breadth");
    int l=s.nextInt();
    int b=s.nextInt();
   System.out.println("Enter side:");
   float side=s.nextFloat();
area(r);-------------------1
area(l,b);-----------------2
area(side);---------------3
}
}

In step 1 and step 3 have same number of arguments but different data type values and all the 3 functions have same name and differ in something or the other so it represents function overloading.

I give a similar program, try it.If you want your program to be checked, mail it to me.
Write a program using a class to calculate the volume,surface area and the diagonal of cuboid with the following specifications:
class name  : Cuboid
Data members : int l,int b,int h
Member funcions :
void input() : Accept length,breadth and height of cuboid
void calculate() : find volume,surface area and diagonal
void dispaly(): Print the result
Volume of cuboid : lxbxh
Surface Area : 2(lb+bh+lh)
Diagonal :  square root of   l2+b2+h2

Java provides two ways in which a value can be called.
  • Pass or call by value : Its simple,just pass the value in calling function and receive the value in receiving function like in the above examples.
  • Pass or call by reference : Reference is the memory address. The memory address of the variable is passed , so if there is a change in the receiving function, then it will refelect in the calling function also.e.g passing arrays.
I will keep posting the other chapters in the coming days.If you have any doubts mail me at kavitha.m.samuel@gmail.com

Sunday, 6 January 2013

Back to school

Learn as much as you can while you are young, since life becomes too busy later.Dana Stewart Scott
WELCOME     BACK

Wednesday, 2 January 2013

New Year - His Grace

May everyday of this New Year be filled with Peace , Love , Joy and Thanksgiving.   A blessed New Year to you and your family.

Monday, 17 December 2012