Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, 1 October 2013

Program to eliminate duplicates and print numbers in sequence

//input numbers are duplicate and not in sequence and you have to eliminate duplicate and print in sequence
//input - 1,2,3,4,5-10,6-14,11-25,20-30,13-16
//output - 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30

import java.util.*;
class EliminateDuplicateAndExpandNumbersInSequence
{

public static void main(String[] args) {
printNumbers(args[0]);
}
static String[] split(String input)
{
return input.split("[,-]");
}
static void printNumbers(String data)
{
String inputs[] = split(data);
TreeSet<Integer> set = new TreeSet<Integer>();
for(String s : inputs )
set.add(Integer.parseInt(s));
int num1 = set.first();
int num2 = set.last();
for(int i = num1 ; i <= num2 ; i++)
{
if(i == num2)
System.out.println(i);
else
System.out.print(i + ",");
}
}
}

Program to expand the given numbers in sequence

//input numbers are unique and in sequence
//input - 1,2,3,4,5-10,11,12,13-16
//output - 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16

import java.util.*;
class ExpandNumberInSequence
{
public static void main(String[] args) {
printNumbers(args[0]);
}
static String[] split(String input)
{
return input.split("[,-]");
}
static void printNumbers(String data)
{
String inputs[] = split(data);
int num1 = Integer.parseInt(inputs[0]);
int num2 = Integer.parseInt(inputs[inputs.length-1]);
for(int i = num1; i <= num2 ;i++)
{
if(i == num2)
System.out.println(i);
else
System.out.print(i+",");
}
}
}

Program to print frequency count of all characters in the given word


import java.util.*;
class FrequencyCountOfChar
{
public static void main(String[] args) {
printAllCounts(args[0]);
}
static void printAllCounts(String input)
{
for( ; input.length() > 0 ; )
{
printFrequencyCount(input);
input = input.replace(""+input.charAt(0),"");
}
}
static void printFrequencyCount(String data)
{
int count = 0;
char temp = data.charAt(0);
for(int i = 0 ; i < data.length() ;i++)
{
if( temp == data.charAt(i) && i != (data.length() - 1))
{
count++;
}
if( temp == data.charAt(i) && i == (data.length() - 1))
{
count++;
System.out.println(temp + "=" + count);
}
else if( temp != data.charAt(i) && i == (data.length() - 1))
{
System.out.println(temp + "=" + count);
}
}
}
}

output :-

C:\Users\mulpk\Desktop>javac FrequencyCountOfChar.java

C:\Users\mulpk\Desktop>java FrequencyCountOfChar hellohi
h=2
e=1
l=2
o=1
i=1

Program to Format Date

// input - 20 jul 2013 (or) 20,jul,2013 (or) 20 ,jul ,2013 (or) 20, jul, 2013

// output - 2013-07-20

import java.util.*;
class DateFormatConversion
{
public static void main(String[] args) {
if(args.length != 1)
{
System.out.println("Enter only one argument ");
return;
}
System.out.println(getDate(args[0]));
}

static String getDate(String s)
{
s = s.replace(","," ");
String[] temp = splitString(s);
String result="";
temp[1] = getMonthNumber(temp[1]);
for(int i = temp.length - 1 ; i >= 0 ; i--)
{
if(i==0)
result += temp[i];
else
result += temp[i] + "-";
}
return result;
}

static String[] splitString(String s)
{
return s.split("[ ]+");
}

static String getMonthNumber(String s)
{
String months = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
int num = (months.indexOf(s.toUpperCase())/3)+1;
if(num < 10)
return "0" + num;
return "" + num;
}
}

Monday, 30 September 2013

Program to check the difference b/w the highest number and lowest number(formed by digits in givenNumber) is equal to given number or not ? if not, choose the difference result as the new input and repeat the process untill the difference equals given number

//java code -- to understand this you need to have little knowledge on Collections interface and ArrayList class, can be found in java.util package
Here am giving two solutions with recursion and without recursion

//with recursion

import java.util.*;
class Calculation
{

static int findHighestOrLeast(int num,boolean highOrLow)   //true - highest and false - least
{
List<Integer> l = new ArrayList<Integer>();
while( num > 0 )
{
l.add(num%10);
num /= 10;
}
Collections.sort(l);
if(highOrLow)
Collections.reverse(l);
num = 0;
for(int i : l )
num = num*10 + i;
return num;

}
static int findNumber(int num)
{
int num2=0;

num2 = findHighestOrLeast(num,true) - findHighestOrLeast(num,false);
if(num == num2)
{
return num;
}
else
{
return findNumber(num2);
}
}
public static void main(String[] args)
{
int num1 = 7624;
System.out.println(findNumber(num1));
}
}

//without recursion

import java.util.*;
class Calculation
{
static int leastPossibleNumber(int num)
{
List<Integer> l = new ArrayList<Integer>();
while( num > 0 )
{
l.add(num%10);
num /= 10;
}
Collections.sort(l);
num = 0;
for(int i : l )
num = num*10 + i;
return num;
}
static int highestPossibleNumber(int num)
{
List<Integer> l = new ArrayList<Integer>();
while( num > 0 )
{
l.add(num%10);
num /= 10;
}
Collections.sort(l);
Collections.reverse(l);
num = 0;
for(int i : l )
num = num*10 + i;
return num;
}
public static void main(String[] args)
{
int num1 = 7624;
int num2=0;
while( true )
{
num2 = highestPossibleNumber(num1) - leastPossibleNumber(num1);
if(num1 == num2)
{
System.out.println(num1 + "  " + num2);
break;
}
else
{
num1 = num2;
}
}
}
}

instead of having two methods leastPossibleNumber and highestPossibleNumber, we can have one method findLeastOrHighest with an extra boolean argument. if you are keen about reusability then you can plan that way.

Program to print all the twin prime combinations b/w the given inputs

//java code

class PrintTwinPrimes{

public static void main(String[] args) {
int num1 = 0,num2 = 0;
int input1 = Integer.parseInt(args[0]);
int input2 = Integer.parseInt(args[1]);
for( int i = input1 ; i <= input2 ; i++)
{
if(isPrime(i))
{
num2 = num1;
num1 = i;
}
if( (num1 - num2) == 2 )
{
System.out.println(num1+"  "+num2);
num2 = 0;
}
}
}
static boolean isPrime(int num)
{
for(int i = 2 ; i <= num/2 ; i++ )
{
if( num % i == 0 )
{
return false;
}
}
return true;
}
}

// compile
javac PrintTwinPrimes.java
// run
java PrintTwinPrimes 2 1000

-- at the time of running the program need to give inputs, otherwise ArrayIndexOutOfBoundException will raise
or else you can validate the program instead

public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Enter only two integer inputs");
return;
}
int num1 = 0,num2 = 0;
int input1 = Integer.parseInt(args[0]);
int input2 = Integer.parseInt(args[1]);
for( int i = input1 ; i <= input2 ; i++)
----------------
---------------

similarly if you want a robust program, you can validate that the first input should be smaller than second input

Program to find whether a given number is Palindrome or not ? if not add the number to the reverse of it, and check the sum for palindrome, repeat this until we get a palindrome

// code in java
class findPalindrome
{
public static void main(String[] args)
{
int num = 165;

System.out.println(findNumber(num));
}
static int findNumber(int num)
{
if(isPalindrome(num))
{
return num;
}
else
{
return findNumber(num + reverseNumber(num));
}
}
static int reverseNumber(int num)
{
int newNum = 0;
while(num > 0)
{
newNum = newNum*10 + num % 10;
num /= 10;
}
return newNum;
}
static boolean isPalindrome(int num)
{
return num == reverseNumber(num);
}
}

Friday, 9 August 2013

Program to list the anagrams from a file (which consists of large volumes of words) in efficient way using JAVA

There can be many ways to do this task but the efficient way is to read each word only once as disk i/o calls are always costlier.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

class PrintAnagramsFromFile
{
public static void main(String[] args) throws Exception
{

printAnagrams(validateInput(args[0]));
}

public static void printAnagrams(HashMap printAnagrams)
{
Set keys = printAnagrams.keySet();
Iterator it = keys.iterator();
while(it.hasNext())
{
String key = (String)it.next();
String value = printAnagrams.get(key);
if(value.indexOf(';') != -1)
{
System.out.println(value);
}

}
}
public static HashMap validateInput(String fileName) throws IOException
{
HashMap storeAnagrams = new HashMap();

BufferedReader br = new BufferedReader(new FileReader(fileName));
String temp = "";
while((temp = br.readLine()) != null)
{
String sorted = sortAscending(temp);
if(storeAnagrams.get(sorted) == null)
{
storeAnagrams.put(sorted,temp);
}
else
{
storeAnagrams.put(sorted,(String)storeAnagrams.get(sorted)+";"+temp);
}
}
return storeAnagrams;
}

public static String sortAscending(String inputString)
{
char[] splittedInput = inputString.toCharArray();
Arrays.sort(splittedInput);
return new String(splittedInput);
}
}


//sample i/p data
Abelard
Abelson
Aberdeen
Abernathy
Abidjan
Abigail
Abilene
Abner
Abraham
Abram
Abrams
Absalom
Abuja
Abyssinia
Abyssinian
Ac
Acadia
Acapulco
Accenture
Accra
Acevedo
Achaean
Achebe
Achernar
Acheson
Achilles
Aconcagua
Acosta
Acropolis
Acrux
Actaeon
Acton
Acts
Acuff
Ada
Adam
Adams
Adan
Adana
Adar
Addams
Adderley
Addie
Addison
Adela
Adelaide
Adele
Adeline
Aden
Adenauer
Adhara
Adidas
Adirondack
Adirondacks
Adkins
Adler
Adolf
Adolfo
Adolph
Adonis
Adonises
Adrian
Adriana
Adriatic
Adrienne
Advent
Adventist
Advents
Advil
Aegean
Aelfric
Aeneas
Aeneid
Aeolus
Aeroflot
Aeschylus
Aesculapius
Aesop
Afghan
Afghanistan
Afghans
Africa
African
Africans
Afrikaans
Afrikaner
Afrikaners
Afro
Afrocentrism
Afros
Ag
Agamemnon
Agassi
Agassiz
Agatha
Aggie
Aglaia
Agnes
Agnew
Agni
Agra
Agricola
Agrippa
Agrippina
Aguilar
Aguinaldo
Aguirre
Agustin
Ahab
Ahmad
Ahmadabad
Ahmadinejad
Ahmed
Ahriman
Aida
Aiken
Aileen
Aimee
Ainu
Airedale
Airedales
Aisha
Ajax
Akbar
Akhmatova
Akihito
Akita
Akiva
Akkad
Akron
Al
Ala
Alabama
Alabaman
Alabamans
Alabamian
Alabamians
Aladdin
Alamo
Alamogordo
Alan
Alana
Alar
Alaric
Alaska
Alaskan
Alaskans
Alba
Albania
Albanian
Albanians
Albany
Albee
Alberio
Albert
Alberta
Alberto
Albigensian
Albion
Albireo
Albuquerque
Alcatraz
Alcestis
Alcibiades
Alcindor
Alcmena
Alcoa
Alcott
Alcuin
Alcyone
Aldan
Aldebaran
Alden
Alderamin
Aldo
Aldrin
Alec
Aleichem
Alejandra
Alejandro
Alembert
Aleppo
Aleut
Aleutian
Alex
Alexander
Alexandra
Alexandria
Alexei
Alexis
Alfonso
Alfonzo
Alford
Alfred
Alfreda
Alfredo
Algenib
Alger
Algeria
Algerian
Algerians
Algieba
Algiers
Algol
Algonquian
Algonquians
Algonquin
Alhambra
Alhena
Ali
Alice
Alicia
Alighieri
Aline
Alioth
Alisa
Alisha
Alison
Alissa
Alistair
Alkaid
Allah
Allahabad
Allan
Alleghenies
Allegheny
Allegra
Allen
Allende
Allentown
Allie
Allison
Allstate
Allyson
Alma
Almach
Almaty
Almighty
Almohad
Almoravid
Alnilam
Alnitak
Alonzo
Alpert
Alphard
Alphecca
Alpheratz
Alphonse
Alphonso
Alpine
Alpo
Alps
Alsace
Alsatian
Alsop
Alston
Alta
Altai
Altaic
Altair
Altamira
Althea
Altiplano
Altman
Altoids
Alton
Aludra
Alva
Alvarado
Alvarez
Alvaro
Alvin
Alyce
Alyson
Alyssa
Alzheimer
Am
Amadeus
Amado
Amalia
Amanda
Amarillo
Amaru
Amaterasu
Amati
Amazon
Amazons
Amber
Amelia
Amenhotep
Amerasian
America
American
Americana
Americanism
Americanisms
Americanization
Americanizations
Americanize
Americanized
Americanizes
Americanizing
Americans
Americas
Amerind
Amerindian
Amerindians
Amerinds
Ameslan
Amharic
Amherst
Amie
Amiga
Amish
Amman
Amoco
Amos
Amparo
Ampere
Amritsar
Amsterdam
Amtrak
Amundsen
Amur
Amway
Amy
Ana
Anabaptist
Anabel
Anacin
Anacreon
Anaheim
Analects
Ananias
Anasazi
Anastasia
Anatole
Anatolia
Anatolian
Anaxagoras
Anchorage
Andalusia
Andalusian
Andaman
Andean
Andersen
Anderson
Andes
Andorra
Andre
Andrea
Andrei
Andres
Andretti
Andrew
Andrews
Andrianampoinimerina
Android
Andromache
Andromeda
Andropov
Andy
Angara
Angel
Angela
Angelia
Angelica
Angelico
Angelina
Angeline
Angelique
Angelita
Angelo
Angelou
Angevin
Angie
Angkor
Anglia
Anglican
Anglicanism
Anglicanisms
Anglicans
Anglicize
Anglo
Anglophile
Angola
Angolan
Angolans
Angora
Angoras
Anguilla
Angus
Aniakchak
Anibal
Anita
Ankara
Ann
Anna
Annabel
Annabelle
Annam
Annapolis
Annapurna
Anne
Annette
Annie
Annmarie
Anouilh
Anselm
Anselmo
Anshan
Antaeus
Antananarivo
Antarctic
Antarctica
Antares
Anthony
Antichrist
Antichrists
Antietam
Antigone
Antigua
Antilles
Antioch
Antipas
Antofagasta
Antoine
Antoinette
Anton
Antone
Antonia
Antoninus
Antonio
Antonius
Antony
Antwan
Antwerp
Anubis
Anzac
Apache
Apaches
Apalachicola
Apennines
Aphrodite
Apia
Apocrypha
Apollinaire
Apollo
Apollonian
Apollos
Appalachia
Appalachian
Appalachians
Appaloosa
Apple
Appleseed
Appleton
Appomattox
Apr
April
Aprils
Apuleius
Aquafresh
Aquarius
Aquariuses
Aquila
Aquinas
Aquino
Aquitaine
Ar
Ara
Arab
Arabia
Arabian
Arabians
Arabic
Arabs
Araby
Araceli
Arafat
Araguaya
Aral
Aramaic
Aramco
Arapaho
Ararat
Araucanian
Arawak
Arawakan
Arbitron
Arcadia
Arcadian
Archean
Archibald
Archie
Archimedes
Arctic
Arcturus
Arden
Arequipa
Ares
Argentina
Argentine
Argentinian
Argentinians
Argo
Argonaut
Argonne
Argos
Argus
Ariadne
Arianism
Ariel
Aries
Arieses
Ariosto
Aristarchus
Aristides
Aristophanes
Aristotelian
Aristotle
Arius
Ariz
Arizona
Arizonan
Arizonans
Arizonian
Arizonians
Arjuna
Ark
Arkansan
Arkansas
Arkhangelsk
Arkwright
Arlene
Arline
Arlington
Armageddon
Armageddons
Armagnac
Armand
Armando
Armani
Armenia
Armenian
Armenians
Arminius
Armonk
Armour
Armstrong
Arneb
Arnhem
Arno
Arnold
Arnulfo
Aron
Arrhenius
Arron
Art
Artaxerxes
Artemis
Arthur
Arthurian
Artie
Arturo
Aruba
Aryan
Aryans
As
Asama
Ascella
Asgard
Ashanti
Ashcroft
Ashe
Ashikaga
Ashkenazim
Ashkhabad
Ashlee
Ashley
Ashmolean
Ashurbanipal
Asia
Asian
Asians
Asiatic
Asiatics
Asimov
Asmara
Asoka
Aspell
Aspen
Aspidiske
Asquith
Assad
Assam
Assamese
Assisi
Assyria
Assyrian
Assyrians
Astaire
Astana
Astarte
Aston
Astor
Astoria
Astrakhan
AstroTurf
Asturias
Asunción
Aswan
At
Atacama
Atahualpa
Atalanta
Atari
Atatürk
Athabasca
Athabascan
Athena
Athenian
Athenians
Athens
Atkins
Atkinson
Atlanta
Atlantes
Atlantic
Atlantis
Atlas
Atlases
Atman
Atreus
Atria
Atropos
Ats
Attic
Attica
Attila
Attlee
Attucks
Atwood
Au
Aubrey
Auckland
Auden
Audi
Audion
Audra
Audrey
Audubon
Aug
Augean
Augsburg
August
Augusta
Augustan
Augustine
Augusts
Augustus
Aurangzeb
Aurelia
Aurelio
Aurelius
Aureomycin
Auriga
Aurora
Auschwitz
Aussie
Aussies
Austen
Austerlitz
Austin
Austins
Australasia
Australia
Australian
Australians
Australoid
Australopithecus
Austria
Austrian
Austrians
Austronesian
Autumn
Av
Ava
Avalon
Ave
Aventine
Avernus
Averroes
Avery
Avesta
Avicenna
Avignon
Avila
Avior
Avis
Avogadro
Avon
Axum
Ayala
Ayers
Aymara
Ayrshire
Ayurveda
Ayyubid
Azana
Azania
Azazel
Azerbaijan
Azerbaijani
Azores
Azov
Aztec
Aztecan
Aztecs
Aztlan

Thursday, 9 May 2013

How to check if two strings are ANAGRAM's or not?

An Anagram is the rearrangement of the letters of a word into another word. 
For Ex: LISTEN and SILENT are Anagrams



SOLUTION 1;


sort both the Strings and compare them. if equal then they are said to be anagrams otherwise not.

sample code snippet in java:

.......
.......

String inputString1 = "SILENT";
String inputString2 = "LISTEN";

boolean checkWhetherAnagramorNot(String inputString1,String inputString2)

{


        char[] chars = inputString1.toCharArray();
        Arrays.sort(chars);
        String sorted1 = new String(chars);
        //System.out.println(sorted1);
        chars = inputString2.toCharArray();
        Arrays.sort(chars);
        String sorted2 = new String(chars);
        //System.out.println(sorted2);
      
         if(sorted1.equals(sorted2))
               return true;
         else
              return false;


}
.........

.........


SOLUTION 2:









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.

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/

Thursday, 9 August 2012

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).