Wednesday 19 December 2012

What is the major difference b/w 32-bit and 64-bit processor ??

At any time processor can execute only one machine instruction, and that instruction length is 32 bits in 32-bit processor and 64 bits in 64-bit processor.

The memory addresses represented by a 32-bit processor is 2power32(2^32) where as 2power64(2^64) in case of 64-bit processor.since 64-bit processor has more memory address, it can even load entire program into memory and executes the program by reducing the overhead of Disk I/O cycles, thereby increasing the performance.

(if not entire program, 64-bit processor will have large "frame" size compared to 32-bit. so it can execute the program in less Disk I/O cycles) 

Cards Game Puzzle

Puzzle:- This puzzle is a game related one. Consider a game contains two participants(let is say player,comp) there are 21 cards in total and each participant can pick either 1 or 2 or 3 or 4 cards at a time. In every game first chance of picking cards is given to player and whoever takes the last card(here 21st card) will be the looser. solve the puzzle such that always comp should win the game.

Solution
if player picks x cards then computer should pick 5-x cards each round.
after four rounds 5*4 = 20 cards will be picked up then the player turn will come, as rule says he should pick atleast one card, so picks up the last card and looses the game.
this is the algorithm for which always computer will win the game.

Missing Ball Puzzle

This is one of the famous puzzles asked in interviews.

Puzzle: There are total hundred balls in a bag, numbered from 1..100(no two balls will have same number).From that bag one ball is stolen by a thief and you will be given that bag with remaining 99 balls. so you need to findout the missing ball in a better way?

Solution:

step1:- calculate the sum of hundred balls. use some of n numbers formula n*(n+1)/2.  i.e., ActualCount.

step2:- calculate the sum of remaining 99 balls.   i.e.,  ObtainedCount

step3:- missing ball number = ActualCount - ObtainedCount


If you have better solutions..please share them in comments!!

Sunday 28 October 2012

differences b/w Android and iPhone


About Android:
Android is a mobile operating system based on Linux kernel with additional middleware services and key applications configured specifically for the mobile devices, tablet computers developed by Google. Android is an open development platform which consists of an Android SDK which provides the tools and API’s needed for developing applications on the Android platform, using Java programming language. Android was acquired by Google in the year 2005. Since then, Android has come with many new versions, with newer updates and features.
The various versions of Android:
Android 1.6 (Cupcake)
Android 2.0 and 2.1 (Eclair)
Android 2.2 (Froyo)
Android 2.3 (Gingerbread)
Android 3.0, 3.1, 3.2 (Honeycomb)
Android 4.0 (Ice Cream Sandwich)
And there are rumours about the name of next version of Android, and its “jellybean”
Android has seen a number of features and updates in each of the above versions like HTML5 support, flash support, color effects, Wi-Fi hotspot tethering, multicore processors, video calling, Bluetooth etc. Android architecture also consists of a Dalvik virtual machine which provides the runtime execution environment of all Android applications in the android device. Android comes with its own inbuilt browser based on the WebKit layout engine. Android consists of an Android market which is the online store developed and maintained by Google for Android mobiles and tablets. The users have a few applications from Android Market preinstalled in their devices; the users can also browse and download applications published by many third party developers in the Android Market app store.
About iPhone:
The iPhone is a smart phone designed and marketed by Apple, configured to operate with an Apple operating system called iOS. The first iPhone was first released on June 29th, 2007 by the Apple then-CEO, Steve Jobs. iPhone consists of various features like Video camera, Wi-Fi, 3G, multi-touch screen etc. iPhone has 5 generations and the iPhone4S came with cool voice activated personal assistant called “Siri”. The Apple operating system iOS is a variant of Darwin operating system found in Mac OS, however iOS takes less than half a gigabyte only. The web browser used in iPhone is Safari which displays the web pages in the phone similar to any other browser. Apple also has an online app store which acts as a repository for many third party and Apple applications which could be downloaded and installed in the user’s respective iPhone.
Similarities between Android and iPhone:
Android devices and iPhone has a number of similarities as both were meant to provide the new Smartphone’s features to the mobile users of both platforms. Some common features supported by both Android and iPhone include an Online app store maintained by both, Android Market in Android and Apple app store in iPhone. This online store contains a number of applications which can be downloaded in the device. Both Android and iPhone supports Wi-Fi, 3G, blue-tooth etc. Another similarity is form factor where form factor includes size, shape, interaction paradigm, full web browser, on screen keyboard.
Differences between Android and iPhone:
Though Android and iPhone is meant to serve the new Smartphone features to the mobile users, there are some differences that are to be noted between Android and iPhone. Android devices are configured with an Android operating system developed by Google whereas iPhone, developed by Apple, is configured to operate with its own iOS operating system. Android’s operating system is Linux based and it’s the open development platform where any third parties can develop android applications using Android SDK and API; install the applications in the Android devices, thus making Android to be device independent. On the other hand, Apple’s iOS is similar to Mac OS, which is device dependent. Another important difference is the online app store in Android is the Android Market store managed by Google and in iPhone it is Apple’s app store managed by Apple. Other key differences are iPhone comes with the Safari web browser which does not support Java and Flash whereas Android comes with its own inbuilt browser, based on Web-kit, which provides full support to Flash and Java. In terms of display, instead of icons littering in your desktop like in iPhone, Android phone adds widgets to the desktop. Android also comes with additional support for buttons which instantly allows to turn on/off certain connectivity options easily. This feature is not available in iPhone. Another important difference is that Android supports multi-notification with the help of its Notification manager. The notification bar in the Android phones can alert you to new voice and email messages, facebook notifications etc.  In-terms of PC connection, in Android, unlike iPhone there is no need to have iTunes to manage the phone because Android can mount the SD card so that it is usable by any operating system. On this, music and files can be added which will then be usable on the phone. Flash support is another main difference between iPhone and Android, Apple have never include flash support on their devices on the other hand android boasts its flash support.

Thursday 20 September 2012

what are OOP concepts ??

OOP concepts are the concepts which are supposed to be satisfied by a programming language inorder to call that programming language as an Object-Oriented programming language.

since c programming language doesn't satisfy the three OOP concepts, we cannot call c as Object-Oriented programming language.

The three OOP concepts are:

1) Encapsulation
2) polymorphism
3) Inheritance

The birth of OOP concepts took place with encapsulation. Thus sometimes people call encapsulation as the backbone of OOP concepts.

what is the difference between static loading and dynamic loading ??

Static Loading:
The concept of allocating memory and loading the executable code of the functionality to the RAM before the function is called (or) before the program is under execution is known as static loading. static loading increases the overhead on the system. Thus, static loading is always disadvantageous.

Any structured programming language program would be based on the concept of static loading. Thus c programs would be working based on the concept of static loading.

Dynamic Loading:
The concept of allocating memory and loading the executable code of a function to the RAM dynamically at the run-time as and when a function call is made i.e., when the program is under execution , is known as dynamic loading.

Any object oriented programming language would be working based on the concept of dynamic loading. Thus java, works based on the concept of dynamic loading only. Dynamic loading reduces the overhead on the system. Thus, always dynamic loading is advantageous.

Sunday 2 September 2012

what is First Normal Form ??

1. eliminate repeating groups in individual tables.
2. create a separate table for each set of related data.
3. identify each set of related data with a primary key.

what is normalization and for what it is meant for ??

Normalization is the process of organizing data in a database. This includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating two factors: redundancy and inconsistent dependency. 

Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place must be changed, the data must be changed in exactly the same way in all locations. A customer address change is much easier to implement if that data is stored only in the Customers table and nowhere else in the database. 

What is an "inconsistent dependency"? While it is intuitive for a user to look in the Customers table for the address of a particular customer, it may not make sense to look there for the salary of the employee who calls on that customer. The employee's salary is related to, or dependent on, the employee and thus should be moved to the Employees table. Inconsistent dependencies can make data difficult to access; the path to find the data may be missing or broken. 

There are a few rules for database normalization. Each rule is called a "normal form." If the first rule is observed, the database is said to be in "first normal form." If the first three rules are observed, the database is considered to be in "third normal form." Although other levels of normalization are possible, third normal form is considered the highest level necessary for most applications. 

Tuesday 21 August 2012

What is a pure virtual function in C++ and abstract methods in JAVA?



A pure virtual function contains only method signature without any body( i.e., no implementation)
Example of pure virtual function in C++

class AbstractClass {
public:
   virtual void pure_virtualfunction() = 0;  // a pure virtual function - no body
   

};
Here "=0" may seems like 0 is assigned to the function, that is not true. It only indicates that the virtual function is pure virtual function and it has no body

Any base class that contains pure virtual function is abstract and cannot have an instance itself created and it also means that any class derived from the base class must override the definition of pure virtual function in the base classm if it doesn't, then derived class becomes abstract class as well.
In Java, pure virtual methods are declared using the abstract keyword. Such a method cannot have a body. A class containing abstract methods must itself be declared abstract. But, an abstract class is not necessarilly required to have any abstract methods. An abstract class cannot be instantiated.
In java we declare the class as abstract under two cenarios:
1) when the class contains abstract methods whose implementation will be provided later by its sub-  class.
2) whenever we don't want the object of a class to be created as sub-most object then we declare the class as abstract even if it doesn't contains any abstract methods.
EX: javax.servlet.http.HttpServlet class is declared as abstract even it doesn't contain any abstract methods.
In C++, a regular, "non-pure" virtual function provides a definition, so it doesn’t mean that the class that contains it becomes abstract. You would want to create a pure virtual function when it doesn’t make sense to provide a definition for a virtual function in the base class itself. Use a regular virtual function when it makes sense to provide a definition in the base class.
this link helped me  http://www.programmerinterview.com/index.php/c-cplusplus/pure-virtual-function/

Does C support function overloading like C++?

Look at the printf() function in C, that may lead one to think that C supports function overloading. Because, in C you can have printf("%d", DecimalValue) and printf("%f", FloatValue). This looks a lot like function overloading, because we are using the same function name to handle different arguments differently.

Actually, this is not a case of function overloading – the printf function is just using a feature of C known as variable argument lists. This should not be confused with function overloading. So, to answer the question, Standard C does not support function overloading.


As an interesting side note, C++ doesn’t really have function overloading. What it does have is a means of faking it: the C++ compiler actually ‘mangles’ (or changes) function names according to the function’s parameters. So, functions that share the same name but have different numbers or types of parameters can be differentiated when invoked. Also, since the ‘mangling’ of function names is not standardized, it’s usually difficult to link object files compiled by different C++ compilers.



Thursday 9 August 2012

implementation of single linked list in c language


#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *link;
}NODE;
NODE *first=NULL,*last,*temp,*newnode;
void creation()
{
int ch;
do
{
newnode=(NODE*)malloc(sizeof(NODE));
newnode->link=NULL;
printf("\n enter the data of the node : ");
scanf("%d",&newnode->data);
if(first==NULL)
{
first=newnode;
}
else
{
last->link=newnode;
}
last=newnode;
printf("\n do u want to add one more node [1/0] : ");
scanf("%d",&ch);
}
while(ch==1);
}
void insertion()
{
int ch,data;
printf("\n 1.at first \n 2.at middle \n 3.at end ");
printf("\n enter your choice :");
scanf("%d",&ch);
newnode=(NODE *)malloc(sizeof(NODE));
newnode->link=NULL;
printf("\n enter the data for the new node :");
scanf("%d",&newnode->data);
switch(ch)
{
case 1:
newnode->link=first;
first=newnode;
break;
case 2:
printf("\n enter the data of the node after which you want to insert :");
scanf("%d",&data);
temp=first;
while(temp->data==data)
temp=temp->link;
newnode->link=temp->link;
temp->link=newnode;
break;
case 3:
temp=first;
while(temp->link!=NULL)
temp=temp->link;
temp->link=newnode;
last=newnode;
break;
default:
printf("\n invalid  choice ");
free(newnode);
}
}
void deletion()
{
int ch,data;
NODE *temp1;
if(first==NULL)
printf("\n list is empty ");
else
{
printf("\n1.first node \n2.middle node \n3.ending node ");
printf("\n enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
temp=first;
printf("\n deleted element is : %d ",first->data);
first=first->link;
free(temp);
break;
case 2:
printf("\n enter the data of the node that you want to delete : ");
scanf("%d",&data);
temp=first;
while(temp->link->data!=data)
temp=temp->link;
temp1=temp->link;
temp->link=temp->link->link;
free(temp1);
break;
case 3:
temp=first;
while(temp->link->link!=NULL)
temp=temp->link;
printf("\n deleted element is : %d ",temp->link->data);
temp1=temp->link;
temp->link=NULL;
free(temp1);
break;
default:
printf("\ninvalid choice");
}
}
}
void length()
{
int l=0;
temp=first;
while(temp!=NULL)
{
temp=temp->link;
l++;
}
printf("\n length of the list is : %d",l);
}
void display()
{
temp=first;
if(temp==NULL)
printf("\n list is empty...nothing to display ");
else
{
printf("\n");
while(temp!=NULL)
{
printf("%d-->",temp->data);
temp=temp->link;
}
}
}
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n 1.creation \n 2.insertion \n 3.deletion \n 4.display \n 5.length");
printf("\n 6.exit \n Enter your choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
creation();
break;
case 2:
insertion();
break;
case 3:
deletion();
break;
case 4:
display();
break;
case 5:
length();
break;
case 6:
exit(0);
default:
printf("\ninvalid choice\n");
}
}
}

implementation of circular queue using arrays in c language

#include<stdio.h>
#include<conio.h>
#include<process.h>
#define MAX 5
int queue[MAX],front=0,rear=0;
void insertion()
{
if(front==(rear+1)%MAX)
printf("\n queue is full..cannot insert ");
else
{
rear=(rear+1)%MAX;
printf("\n Enter the element to insert in the queue : ");
scanf("%d",&queue[rear]);
}
}
void deletion()
{
if(front==0&&rear==0)
printf("\n queue is empty...nothing to delete ");
else
{
printf("\n deleted element is : %d ",queue[front]);
front=(front+1)%MAX;
}
if(front==rear)
{
front=0;
rear=0;
}
}
void display()
{
int i;
if(front==0&&rear==0)
printf("\n queue is empty...nothing to display ");
else
{
if(front==0)
front++;
for(i=front;i!=rear;i=(i+1)%MAX)
{
printf("%d ",queue[i]);
}
printf("%d ",queue[i]);
}
}
void length()
{
int length=0,i;
if(front==0&&rear==0)
length=0;
else
{
for(i=front;i!=rear;i=(i+1)%MAX)
length++;
}
printf("\n length of the queue is : %d",length);
}
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n 1.insertion\n 2.deletion\n 3.display\n 4.length\n 5.exit");
printf("\n Enter your choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
insertion();
break;
case 2:
deletion();
break;
case 3:
display();
break;
case 4:
length();
break;
case 5:
exit(0);
default:
printf("\n invalid choice...try again");
}
}
}

implementation of stack using arrays in c language

#include<stdio.h>
#include<conio.h>
#define max 5
int stack[max],ele,top;
void push();
void pop();
void display();
void topelement();
int main()
{
    char ch;
    top=-1;
    printf("1.push\n2.pop\n3.display\n4.topelement\n5.end\nenter your choice:");
    scanf("%d",&ele);
    do
    {
                    switch(ele)
                    {
                              case 1:
                                   push();
                                   break;
                              case 2:
                                   pop();
                                   break;
                              case 3:
                                   display();
                                   break;
                              case 4:
                                   topelement();
                                   break;
                              case 5:
                                   exit(0);
                                   break;
                    }
             printf("\ndo u want to perform more stack operations[y/n]:");
             ch=_getch();
             if(ch=='y')
             {
                        printf("\n1.push\n2.pop\n3.display\n4.topelement\n5.end\nenter your choice:");
                        scanf("%d",&ele);
             }
    }
    while(ch=='y');
    _getch();
    return 0;
}
void push()
{
     if(top==max-1)
     {
                   printf("stack is full cannot insert anymore\n");
                   return;
     }
     else
     {
                 printf("enter the element do u want to insert:");
                 scanf("%d",&ele);
                 top++;
                 stack[top]=ele;
     }
}
void pop()
{
     if(top==-1)
     {
                printf("stack is empty..no elements to delete\n");
                return;
     }
     else
     {
                top--;
                printf("deleted element from the stack is : %d",stack[top+1]);
     }
}
void display()
{
     int i;
     if(top==-1)
     {
                printf("stack is empty..no elements to display\n");
                return;
     }
     else
     {
         printf("the elememts of the stack are : ");
         for(i=0;i<=top;i++)
                            printf("%d\t",stack[i]);
     }
}
void topelement()
{
     if(top==-1)
     {
                printf("stack is empty\n");
                return;
     }
     else
                printf("the top most element of the stack is : %d",stack[top]);
}

implementation of linearsearch using arrays in c language

#include<stdio.h>
#include<conio.h>
int main()
{
    int key,i,a[]={11,3,56,78,93,45,26,28,6,71};
    printf("enter a values to search:");
    scanf("%d",&key);
    for(i=0;i<=9;i++)
    {
                     if(a[i]==key)
                     break;
    }
    if(i==10)
    printf("search element is not found");
    else
    printf("search element is found at %d location",i+1);
    getch();
    return 0;
}

binary search implementation in c language using arrays

#include<stdio.h>
#include<conio.h>
int main()
{
    int i,key,a[]={1,5,9,11,23,43,56,59,78,99},l=0,h=9,mid;
    printf("enter a values to search:");
    scanf("%d",&key);
    while(l<=h)
    {
               mid=(l+h)/2;
               if(a[mid]==key)
               {
                              printf("search element is found at %d location",mid);
                              getch();
                              //exit(0);
                              return;
               }
               a[mid]>key?(h=mid-1):(l=h+1);
    }
    printf("search element is not found");
   getch();
   return 0;
}

implementation of insertion sorting through single linked list in c


#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *link;
};
struct node *first=NULL,*new,*temp;
void creation()
{
int data;
do
{
printf("enter the data of node which you want to sort :");
scanf("%d",&data);
new=(struct node*)malloc(sizeof(struct node));
new->data=data;
new->link=NULL;
if(first==NULL || new->data < first->data)
{
new->link=first;
first=new;
}
else
{
temp=first;
while(temp->link!=NULL&&new->data>=temp->link->data)
temp=temp->link;
new->link=temp->link;
temp->link=new;
}
printf("\n do u want to add one more node[1/0] : ");
scanf("%d",&data);
}while(data);
}

void display()
{
if(first==NULL)
{
printf("\n list is empty... nothing to display");
}
else
{
temp=first;
printf("\n sorted list is :\n");
while(temp!=NULL)
{
printf("%d-->",temp->data);
temp=temp->link;
}
}
}
int main()
{
creation();
display();
getch();
return 0;
}

Ascending Priority Queue implementation in java

import java.io.*;
class Node
{
 int data;
 int priority;
 Node link;
  Node(int priority,int data)
  {
   this.data=data;
   this.priority=priority;
  }
}
class PriorityQueue
{
 Node front;
        
  BufferedReader br;

  void creation()
  {
   int a,b;
   boolean ch=true;
   Node newnode;
                   do
            {  
    try
    {

     System.out.print("enter the data for newnode : ");
     a=Integer.parseInt(br.readLine());
     System.out.println();
     System.out.print("enter the priority for new node : ");
     b= Integer.parseInt(br.readLine());
     System.out.println();
     newnode=new Node(b,a);
    if(front==null||newnode.priority<front.priority)
    {
     newnode.link=front;
     front=newnode;
    }
    else
    {
     Node temp=front;
     while(temp.link!=null&&newnode.priority>=temp.link.priority)
      temp=temp.link;
     newnode.link=temp.link;
     temp.link=newnode;
    }
     System.out.println("do u want to add one mode node [true/false] : ");

                          ch=Boolean.parseBoolean(br.readLine());
    }
               
    catch(Exception e)
    {
     System.out.println(e);
    }
  }
                    while(ch);
  }
             
   void display()
   {
   Node temp=front;
   if(temp==null)
    System.out.println("list is empty");
   else
   {

    while(temp!=null)
    {
     System.out.println(temp.priority+"--->"+temp.data);
     temp=temp.link;
    }
   }
  }

  void delete()
  {
   Node temp=front;

   if(temp==null)
    System.out.println("list is empty");
   else
   {
    System.out.println("deleted element is:" + front.data+" having a priority:"+front.priority);
    front=front.link;
    temp=null; /*whenever you are assining null to a reference of a class ,then the object associated  with  that reference is immediately deleted by the garbage collector due to automatic memory management */
    display();
   }
  }
  public static void main(String [] args)
  {
   int ch;
   PriorityQueue pq=new PriorityQueue();
   pq.br=new BufferedReader(new InputStreamReader(System.in));
  try
  {
   while(true)
   {
    System.out.println("1.creation");
    System.out.println("2.display");
    System.out.println("3.delete");
    System.out.println("4.exit");
    System.out.print("Enter your choice : ");
    ch=Integer.parseInt(pq.br.readLine());
    System.out.println();
    switch(ch)
    {
     case 1:
      pq.creation();
       break;
     case 2:
      pq.display();
       break;
     case 3:
      pq.delete();
       break;
     case 4:
      return;
     default:
      System.out.println("invalid choice...try again ");
    }
   }
  }
   catch(Exception e)
   {
    System.out.println(e);
   }
  }
}


2.Stack implementation using single linked list in c language

program:

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void display();
typedef struct stack
{
int ele;
stack *link;
} node;
node *top=NULL;
void push(int x)
{
node *current=NULL;
current=(node *)malloc(sizeof(node));
if(current==NULL)
{
printf("\nmemory is not allocated properly");
return;
}
current->ele=x;
current->link=top;
top=current;
}
void length()
{
node *temp;
int len=0;
temp=top;
while(temp!=NULL)
{
++len;
temp=temp->link;
}
printf("\n the length of the stack is : %d",len);
}
void pop()
{
node *temp;
if(top==NULL)
printf("\n stack is empty ");
else
{
temp=top;
top=top->link;
printf("\n the deleted element is :%d\n",temp->ele);
free(temp);
}
}
void topmost()
{
if(top==NULL)
printf("\nstack is empty");
else
printf("top most element is : %d",top->ele);
}
void display()
{
if(top==NULL)
printf("\n stack is empty ");
else
{
node *temp;
temp=top;
printf("\n the stack elements are:");
while(temp!=NULL)
{
printf("%d<---",temp->ele);
temp=temp->link;
}
}
}
void main()
{
int i,ch;
clrscr();
ab:
printf("\n1.push\n2.pop\n3.topmost\n4.display\n5.length of stack\n6.exit\nenter your choice:");
scanf("%d",&i);
switch(i)
{
case 1:
printf("\n enter the element that you want to insert into d stack :");
scanf("%d",&ch);
push(ch);
break;
case 2:
pop();
break;
case 3:
topmost();
break;
case 4:
display();
break;
case 5:
length();
break;
case 6:
return;
default:
printf("\n invalid choice...try again..");
}
goto ab;
}

Friday 3 August 2012

What is the significance of equals() and hashCode() methods of Object class in JAVA?

public boolean equals(Object obj)

This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison". However, the classes providing their own implementations of the equals method are supposed to perform a "deep comparison"; by actually comparing the relevant data members. Since Object class has no data members that define its state, it simply performs shallow comparison.

The equals method for class Object implements the most discriminating possible equivalence relation on objects i.e., for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

Note that it is generally necessary to override the hashCode method(of Object class) whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.



public int hashCode()

This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that overrides the equals method.

    The general contract of hashCode is:
    Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
    If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
    It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Thursday 2 August 2012

What is HashMap and Map?

      Map is an Interface which is part of Java collections framework. This is used to store Key-Value pairs, and HashMap is the class that implements Map Interface.

      EX:
        package com.ks.j2se;
        import java.util.HashMap;
        import java.util.Iterator;
        import java.util.Map;
        import java.util.Set;
         
        public class HashMapDemo {
        public static void main(String[] args) {
        try {
        Map<String,String> hMap = new HashMap<String,String>();
        hMap.put("Db2" ,"Expensive Enterprise database from IBM");
        hMap.put("Oracle" , "Expensive Enterprise Database from Oracle");
        hMap.put("MySQL" , "Free Open Source Database from Sun Microsystems");

        Iterator itr = hMap.entrySet().iterator(); 
        //getting the keys of hashmap in the form of set, so that we can iterate over keys in loop and in each iteration we can get the corresponding value associated with the key
        while (itr.hasNext()) {
        Map.Entry mEntry = (Map.Entry) itr.next();
        System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
        }
        } catch (Exception e) {
        System.out.println(e.toString());
        }
        }
        }

What is the difference between java.util.Iterator and java.util.ListIterator?

    Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements.
    ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

    Example:

      import java.util.*;

      public class Demo {

         public static void main(String args[]) {
            ArrayList al = new ArrayList();
            al.add("A");
            al.add("B");
            al.add("C");
            al.add("D");
            al.add("E");
            al.add("F");

            //iterator 
            System.out.print("Original contents of al: ");
            Iterator itr = al.iterator();
            while(itr.hasNext()) {
               Object element = itr.next();
               System.out.print(element + " ");
            }
            System.out.println();
            
       // listIterator modifying objects
            ListIterator litr = al.listIterator();
            while(litr.hasNext()) {
               Object element = litr.next();
               litr.set(element + "-");
            }

            System.out.print("Modified contents of al: ");

            itr = al.iterator();
            while(itr.hasNext()) {
               Object element = itr.next();
               System.out.print(element + " ");
            }
            System.out.println();

            // Now, display the list backwards
            System.out.print("Modified list backwards: ");
            while(litr.hasPrevious()) {
               Object element = litr.previous();
               System.out.print(element + " ");
             }
             System.out.println();
          }
      }

      output :

      Original contents of al: A B C D E F
      Modified contents of al: A- B- C- D- E- F-
      Modified list backwards: F- E- D- C- B- A-

What is an Iterator interface in java?

    Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.


      Method Summary
       boolean  hasNext() :
                                            Returns true if the iteration has more elements.
                         E   next() :
                                             Returns the next element in the iteration.
               void   remove() :
                                             Removes from the underlying collection the last element returned by the iterator (optional operation).
       

How would you find the size of structure without using sizeof()?

struct MyStruct
{
int i;
int j;
};

int main()
{
struct MyStruct *p=0;
int size = ((char*)(p+1))-((char*)p);
printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);
return 0;
}

Is there something we can do in C but not in C++?

The answer is Yes and its seems to be funny but the interviewer may trouble you on this..

Declare variable names which are keywords in C++ but not C.


#include < stdio.h >
int main(void)
{
int  new=3,delete=4;
return 0;
}


this above code will compile in c compiler but not in c++ compiler because new,delete are keywords specific to c++ and they are not in c.

How to swap the two nibbles in a byte ?

unsigned char swapNibbles(unsigned char c)
{
unsigned char temp1, temp2;
temp1 = c & 0x0F;
temp2 = c & 0xF0;
temp1=temp1 << 4;
temp2=temp2 >> 4; 

return(temp2|temp1); //adding the bits
}

int main(void)
{
char ch=0x34;
printf("\nThe exchanged value is %x",swapNibbles(ch));
return 0;
}

How to fast multiply a number by 7?

(num << 3)- num

This is same as

num*8 - num = num * (8-1) = num * 7

How can we sum the digits of a given number in single statement?

void main()
{
int num=123456; 
int sum=0;

for(;num > 0;sum+=num%10,num/=10); // This is the "single line".

printf("\nsum = [%d]\n", sum);
}


Given two strings A and B, how would you find out whether the characters in B were a subset of the characters in A?

#include < stdio.h >
#include < conio.h >

int isSubset(char *a, char *b);

int main()
{
char str1[]="defabc";
char str2[]="abcfed";

if(isSubset(str1, str2)==0)
{
printf("\nYes, characters in B=[%s] are a subset of characters in A=[%s]\n",str2,str1);
}
else
{
printf("\nNo, characters in B=[%s] are not a subset of characters in A=[%s]\n",str2,str1);
}

getch();
return(0);
}


// Function to check if characters in "b" are a subset
// of the characters in "a"

int isSubset(char *a, char *b)
{
int letterPresent[256];
int i;

for(i=0; i < 256; i++)
letterPresent[i]=0;

for(i=0; a[i]!='\0'; i++)
letterPresent[a[i]]++;

for(i=0; b[i]!='\0'; i++)
if(!letterPresent[b[i]])
return(1);

return(0);
}