// TOH refers to Tower Of Hanoi.publicclassTOH{// Defining a method which accepts parameters as: no of disks, name of rods (should match according to name of formal arguments passed).publicvoidtower(intnoOfDisks,StringsourceRod,StringdestinationRod,StringauxiliaryRod){if(noOfDisks==1){System.out.format("\nRod %d moved from %s to %s",1,sourceRod,destinationRod);return;}else{// Key Algorithms :tower(noOfDisks-1,"Source Rod","Auxiliary Rod","Destination Rod");System.out.format("\nDisk %d moved from %s to %s",noOfDisks,sourceRod,destinationRod);tower(noOfDisks-1,"Auxiliary Rod","Destination Rod","Source Rod");}}}
Driver Code
// TOHDemo refers to Tower Of Hanoi Demo.classTOHDemo{publicstaticvoidmain(String[]args){// This accepts the no of disksintnoOfDisks=4;TOHobjectOne=newTOH();// Passing the no of disks and rod names to recursive function.objectOne.tower(noOfDisks,"Source Rod","Destination Rod","Auxilary Rod");}}