Tuesday, September 27, 2011

Introduction to Advance Java : An starter for Interviewes



Introduction:

This post will introduce the concept of advance java classes. This post introduces several java classes which are highly required during coding in JAVA programming language. This is the first part of “Introduction to Advance JAVA”. This post will discuss the classes, its details and a sample program that how to use these classes in JAVA code.

In this post we are talking about Arrays, File Reader and Writer and a map interface classes. In coming post we will be discussing several other useful classes like database connectivity, transaction management classes and other important things.

   

1.     Arrays Class
Public class Arrays extends Object

This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The methods in this class all throw a NullPointerException if the specified array reference is null, except where noted.

The documentation for the methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementers should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort (Object []) does not have to be a merge sort, but it does have to be stable.) The following function definition searches the specified array of bytes for the specified value using the binary search algorithm.

static int binarySearch(byte[] a, byte key)


The following program illustrates Array Class implementation.

import java.util.Arrays;
public class ArrayInt {
       public static void main(String[] args) {
int[] a1 = new int[]{4,3,5};
int[] a2 = new int[]{1,3,8,4,5,7};
             
boolean check=Arrays.equals(a1, a2);
System.out.println(check);
System.out.println("The Contents of the array are as follows");
for(float i:a1){
System.out.println(" ====== "+i);
}
     
Arrays.sort(a2);
for(float i:a2){
                                    }
int index=Arrays.binarySearch(a2,3);
System.out.println("The Index of the given names"+index);

int index1=Arrays.binarySearch(a2,9);
System.out.println("Search is not Successful"+index1);

Arrays.fill(a2, 4, 6,9);

for(int i:a1){
                System.out.println(" ##### " + i);}
}





2.     File Reader and File Writer

FileInputstream:

This class is a subclass of Inputstream class that reads bytes from a specified file name. The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throwsFileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as below. Sample function signature is as below which should be used during coding

FileInputstream (File filename);


FileOutputStream:

This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriterBufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as below. Sample function signature is as below which should be used during coding

FileOutputStream (File filename);


The following program illustrates Reading data from the File and writes data into the file.

File Read Program
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
            FileReader fr = new FileReader("out.txt");
            BufferedReader br = new BufferedReader(fr);
            String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
   fr.close();
}
}



File Write Program
package AdvancedIO;
import java.io.*;
class FileWrite
{
   public static void main(String args[])
  {
      try{
        FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("Hello Java");
        out.close();
        }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Relevant AD
This ad may be helpful, if relevant to your search.


3.     Map Interface

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets. The following constructors are defined:

HashMap( )
HashMap(Map
 m)
HashMap(int
 capacity)
HashMap(int
 capacity, float fillRatio)

HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator. The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapExample {
    public static void main(String[] args) {
        Map<Object,String> mp=new HashMap<Object, String>();
        mp.put(new Integer(2), "100");
        mp.put(new Integer(1), "200");
        mp.put(new Integer(3), "300");
        mp.put(new Integer(4), "400");
        mp.put(new Integer(7), "777");
        mp.put(new Integer(6), "666");
        mp.put(new Integer(5), "333");
       
        Set s=mp.entrySet();
        Iterator it=s.iterator();

        while(it.hasNext())
        {
           Map.Entry m =(Map.Entry)it.next();

            // getKey is used to get key of Map
            int key=(Integer)m.getKey();

            // getValue is used to get value of key in Map
            String value=(String)m.getValue();

                     System.out.println("Key :"+key+"  Value :"+value);
        }
    }
}

Friday, September 23, 2011

Logitech Revue (Google TV) reveiw

Fast Track Summary
Google TV is a great deal with the fact that it has very less price and nice integration with TV. You should try this. The important thing to note about Google TV is that it is best suited those who has Big  Screen TV.  The bigger the TV you have, the more enjoyment you will have using Google TV.

Other Facts
Few days back, I purchased the Logitech Revue ( Google TV) equipment and an HD capable Camera for video chatting.

Price drop to $99 is an excellent reason to purchase Google TV. Wait, if you are interested in Video chatting, the Logitech is offering you an offer of$50 less price on its HD capable Camera. The whole deals come to only 199.98 $, saving of 50$ more, is another reason to buy this product.

Relevant AD
This ad may be helpful, if relevant to your search.


I am a technical person (IT Guy) with s/w architecture and development experience and I am still testing  these two products ( Google TV and web camera).  Till now I am very happy that it works great on the TV.
I am able to watch the cable/set top box programs and at the same time I can surf most of the internet based web sites.

Its not amazing to know that several american web sites has already optimized their websites for easy viewing and reading the contents on a large screen TV, but the more important thing is that some web sites from India has already optimized their web sites for Google TV.  The one I am using is www.raaga.com on my TV to listen the Hindi language songs. It works perfectly fine. I don't now need to open my computer to listed the song.

I have purchased both only in $ 199.98 . No other charges at all. I am enjoying right now YouTube leanback, Video chatting and some Indian Channels who has already optimized their web site for Google TV viewing. One example is raaga.com.

Some more technical review about Google TV can be found here.
What is Google TV -- Cnet's year review
Google TV -- how to set up

Google TV future expectations
It is based on Android platform. Google is bringing the latest version of Android operatings  system soon. This will allow the easy application development for Developer on Google TV platform. What does it means that we should be seeing and will be able to download a lot of useful applicaiton on Google TV.  The future seems to be bright.

Logitech Revue (Google TV) is an excellent product when compared to price, current features and most important when related to the expected growth (usability of this product) which is backed by Google.

If two or three Google TV applications works great and  seamlessly, it would be great for several users to buy this product. In coming weeks, I will write some more application specific details. Google TV has several application which may be an interest for someone to know that how it works. I will write a detailed review on Video Chatting (HD) software. I know that for the people,

Wednesday, September 21, 2011

C Language: Beginners’ Guide



Introduction
The purpose of this post is to introduce elementary idea of C - Programming language to the readers. This post requires no earlier experience of any programming  language.
The post has been written keeping the audiences in mind who need to know what C programming language is and what are the different features available. It will help the elementary school students who need to prepare some type of reports for their annual/half-yearly report on a technical topic like this one.
This post will try to highlight the basic features of C. The post is not trying to teach the basic working knowledge of this programming language.
         1.  Overview of C:
C is a powerful structured programming language developed by Dennis Ritchie. It supports functions that enable easy maintainability of code, by breaking a large file
into smaller modules.

2.     Program structure:
A sample C Program template can be as simple as below. The famous “Hello World”
is the famous program among the people interested to learn this language.
#include<stdio.h>
int
main()                               
{     
        --other statements
}

3.     Header files:
The files that are specified in the include section above, are called as header files. These are precompiled files that have several commonly used functions defined in these files. The functions available in the header files are used by a program by supplying few or no parameters.

Like any other file, these header files contains an the file extension ‘.h’. The main program (not the header files) created in the C language are stored in the file system as physical file. These files must have a file name with file extension as ‘.c’. So if you see a file having an extension '.c' then you should understand that is program source code written in the C.
4. Main function:
There must be at least one function in any C source code. This is called as Main() and is a mandetory requirement of C language. This is the entry point of any C program.From main() function the code execution flows as per the programmer’s chosen custom functions. There may or may not be other functions written by user in a program.

5. The First program: Famous “Hello World”
#include<stdio.h>
int
main()
{
        printf(“Hello”);
        return 0;
}
This program prints Hello on the screen when we execute it.

6.   Running a C Program:
You need a C programming language compiler and the code editor at least. The famous ones are listed below

•  If you are working on Windows Operating system, you can download either c-tool or the whole C IDE from the link below. IDE is a helpful set of tool where there is no need to shift between multiple windows during program developement.
Borland IDE : http://www.borland.com

  If you are working on Linux Operating system, then you can download or configure the operating system components to include all the required C tools from the installation source like the DVD/CD.

  Type the above program and save it. With the help of whatever editor you are using compile the program – This will generate an exe file (executable). If you are using and IDE, it will automatically compile, link and run the program for you (actually the exe created out of compilation will run and not the .c file). The you can see the o/p in a blank screen (in most of IDE) whic is called as DOS command prompt.

7.   Comments in C:
C programming language provides two distinct type of code commenting options. Code commenting is required and considered as a very good habit for developers because it gives an adecaute logical information about a code section to the person who is reading for the first time.

• Single line comment
–   // (double slash).
–   Termination of comment is by pressing
enter key.

 Multi line comment looks like as below
/*
This is a comment to tell the reader that we can write multiline comments as in this section. More than one line commenting is possible in C just like these lines.
*/

Multiline comments helps expediting in writing comment which are more than a line.

8. Data types in C:
Any programming language needs to deal with different type of data. C may be handling some mathematical calculation based code, which demands C to work with data like integer values, decimal values. At the same time C may be handling some description about a product details. In this case it will be handling data like customer name, product name, etc. These type of description is nothing but demands C to handle data which are charachter in nature. So C must have pre-defined type of data which it can handle. It has the following type of data defination standards i.e. data types.

• Primitive data types
– int, float, double, char.

• Aggregate data types
– Arrays come under this category.
– Arrays can contain a collection of int or float or char or double type of data.

 User defined data types
– Instead of using the data types available in C, the developer can also define his/her own data type. This type of data is required when we need to store and manipulate the complex type of data, for example the student’s information.
–  Structures and enum data type fall under this category.

9. Variables:
Variables are the temporary place in the computer memory which actually stores the data (any type of data as defined in the above sections). The value in variables may change during the program execution life time,

How to Declare a variable
                         <<Data type>> <<variable name>>;
                    Example:   int a;
     
How to Define a variable
                 <<varname>>=<<value>>;
                  a=10;

How to use a variable
              <<varname>>
              a=a+1;//increments the value of a by 1.
              We can also declare and define a variable in single shot like this.
              int a=10;

          10. Variable names - Rules:
• Should not be a reserved word like intchar etc.
• Should start with a letter or an underscore (_).
 Can contain letters, numbers or underscore.
• No other special characters are allowed including space.
• Variable names are case-sensitive
– A and a are different.

11.  Input and Output:
• Input
– scanf(“%d”,&a);
– Gets an integer value from the user and stores it under the name “a”
• Output
– printf(“%d”,a);
– Prints the value present in variable on the screen.

                 Format specifier
• %d is the format specifier. This informs to the compiler that the incoming value is an integer value.
• Other data types can be specified as follows:
• %c – character
• %f – float
• %lf – double
• %s – character array (string)
• Printf and scanf are defined under the header file stdio.h

12.  For loops:
For loop is used when a set of work has to be repeated multiple time. The syntax offor loop is below
for (initialisation;condition checking;increment)
 {
      set of statements
}

A Program which print Hello 10 times can be similar like one below.
for(I=0;I<10;I++)
{
      printf(“Hello”);
}

13.  While loop:
 The while loop is used to perform some set of tasks which need to be repeated until the parent condition holds true. The syntax for while loop,
while(condn)
{
            statements;
}
Eg:
            a=10;
            while(a !=
0)   
            {
                        printf(“%d”,a);
                        a--;
            }
Output:
10987654321


14.  Do While loop:
The do while is similar to the while loop except that predecided set of task is performed without checking any condition for the first time. The syntax of do whileloop is described below.

do
{
            set of
statements
}while(condn);
Eg:
i=10;                                       
do                                                                   
{
            printf(“%d”,i);
            i--;
}while(i!=0)
Output:
10987654321
             While – Entry controlled loop. Do While – Exit controlled loop.

15.  Conditional statements:
If you want to do some set of task only once but again based on some condition which hold true, then use the IF statement as illustrated below.

if
(condition)          
{
        stmt 1;             //Executes if Condition is true.
}
else
{
        stmt 2;             //Executes if condition is false.
}

switch(var)                         
{
case
1:         //if var=1 this case executes.
                                stmt;
                                break;
case
2:         //if var=2 this case executes.
                                stmt;
                                break;
default:        //if var is something else this will
execute.
                                stmt;
}

16. Operators:
• Arithmetic (+,-,*,/,%).
• Relational (<,>,<=,>=,==,!=).
• Logical (&&,||,!).
• Bitwise (&,|).
• Assignment (=).
• Compound assignment (+=,*=,-=,/=,%=,&=,|=).
• Shift (right shift >>, left shift <<).

17.  String functions:
• strlen(str) – To find length of string str .
 strrev(str) – Reverses the string str as rts .
• strcat(str1,str2) – Appends str2 to str1 and returns str1.
• strcpy(st1,st2) – copies the content of st2 to st1.
• strcmp(s1,s2) – Compares the two string s1 and s2.
• strcmpi(s1,s2) – Case insensitive comparison of strings.
    String.h header file must be included before any of the above string functions is used in the code.

18.  Numeric functions:
• pow(n,x) – evaluates n^x.
• ceil(1.3) – Returns 2
• floor(1.3) – Returns 1
• abs(num) – Returns absolute value
• log(x)  - Logarithmic value
• sin(x) 
• cos(x)
• tan(x)
Header file to be included math.h

19.  Procedures:
• Procedure is a function whose return type is void.
• Functions will have return types int, char, double, float or even structs and arrays.
• Return type is the data type of the value that is returned to the calling point after the called function execution completes.

20. Functions and Parameters:
Functions are the small unit of a program which has some set of instruction which needs to be done as a single unit of work. Each function can do its pre-decided work based on some value which is passed to it. The values which are passed to the function called as parameters. Find below some illustrations as below.

Declaration
section
<<Returntype>>
funname(parameter list);
Definition
section
<<Returntype>>
funname(parameter list)
{
        body of the
function
}

Function
Call
Funname(parameter);

Example
function
#include<stdio.h>
void
fun(int a);                    //declaration.
int
main()
{
        fun(10);                                   //Call.
}     
void
fun(int x)                     //definition.
{
        printf(“%d”,x);                       
}

21.  Actual and Formal parameters:
• Actual parameters are those that are used during a function call.
• Formal parameters are those that are used in function definition and function declaration.

22. Arrays:
• Arrays fall under aggregate data type.
• Aggregate – More than 1.
• Arrays are collection of data that belong to same data type.
• Arrays are collection of homogeneous data.
• Array elements can be accessed by its position in the array called as index.
• Array index starts with zero. 
• The last index in an array is num – 1 where num is the no of elements in a array.
• int a[5] is an array that stores 5 integers.
• a[0] is the first element where as a[4] is the fifth element.
• We can also have arrays with more than one dimension.
• float a[5][5] is a two-dimensional array. It can store 5x5 = 25 floating point
numbers.
• The bounds are a[0][0] to a[4][4].

23.  Structures :
• Structures are user defined data types.
• It is a collection of heterogeneous data.
• It can have integer, float, double or character data in it.
• We can also have array of structures. 
struct
<<structname>>
{
  members;
}element;
We can access element.members;
struct
Person
{
int id;
char name[5];
}P1;
P1.id = 1;
P1.name = “vasu”;
For assigning more values we need to create an array of structure element like this
Struct
Person
{
Int id;
Char name[5];
}P[10];
P[0].id = 1;
P[0].name = “saran”;
P[1].id = 2;
P[1].name = “arya”;
And
so on till P[9].

24. Type def:
The typedef operator is used for creating alias of a data type. For example I have this statement, I can use integer in place of int  i.e instead of declaring int a;, I can use integer a; This is applied for structures too. 
typedef int integer;
typedef struct student
{
int id;
Char name[10];
}s;
Now I can put
s1,s2;

Instead of struct student s1,s2; //In case typedef is missed in struct definition as below
struct student
{
int id;
char name[10];
};


25.  Pointers:
•  Pointer is a special variable that stores address of another variable. Addresses are
integers. Hence pointer stores integer data. Size of pointer = size of int.

• Pointer that stores address of integer variable is called as integer pointer and is declared as int *ip;

Examples
int a;
a=10;           //a stores 10
int *ip ;
ip = &a;       //ip stores address of a (say 1000)
ip     :           fetches 1000
*ip :           fetches 10
* Is called as dereferencing operator

26.  Call by Value:
• Calling a function with parameters passed  as values
int  a=10;                                   
void fun(int a)
fun(a);                           {
                                                              defn;
                                      }
Here fun(a) is a call by value. Any change done with in the function is local to it and will not be effected outside the function. 
27.  Call by reference:
• Calling a function by passing pointers as parameters (address of variables is passed instead of variables).

int a=1;                         
void fun(int *x)
fun(&a);                                    {
                                                              defn;
                                      }
Any change done to variable a will affect outside the function also.

28. Example program – Call by value:
#include<stdio.h>
void
main()
{
        int a=10;
        printf(“%d”,a);                        a=10
        fun(a);
        printf(“%d”,a);                        a=10
}

void fun(int x)
{
        printf(“%d”,x)             x=10
        x++;
        printf(“%d”,x);                        x=11
}

 Explanation
c pointer

29.  Example Program – Call by reference:
#include<stdio.h>
void
main()
{
        int a=10;
        printf(“%d”,a);                        a=10
        fun(a);
        printf(“%d”,a);                        a=11
}
void fun(int x)
{
        printf(“%d”,x)             x=10
        x++;
        printf(“%d”,x);                        x=11
}

Explanation
c pointer illustration
30. Conclusion:
• Call by value: Copying value of variable in another variable. So any change made in the copy will not affect the original place.
• Call by reference: Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written.
.
[About the Author: Pratima Gutal is an engineering student in the IT department of College of Engineering Pandharpur, Maharashtra, India. Contact Pratima at her email-id pratima.gutal@gmail.com. If you have any concern, question or objection about this article please feel free to contact her.]