Search Tutorials

Thursday 25 April 2013

Tutorial to understand SQL language

First read SQL Statements: DDL, DML and DCL tutorial to understand this tutorial deeply. In this tutorial, we will learn how to create database, tables and how to select/insert/delete/update data in tables.

Creating and Deleting Databases

1) Creating a database
mysql> CREATE database 134a;
Query OK, 1 row affected (0.00 sec)

2) Deleting a database
mysql> DROP database 134a;
Query OK, 0 rows affected (0.00 sec)

Creating a Table

3) After we have created the database we use the USE statement to
change the current database;
mysql> USE 134a;
Database changed

4) Creating a table in the database is achieved with the CREATE table
statement
mysql> CREATE TABLE president (
-> last_name varchar(15) not null,
-> first_name varchar(15) not null,
-> state varchar(2) not null,
-> city varchar(20) not null,
-> birth date
-> death date null
not null default '0000-00-00',
-> );
Query OK, 0 rows affected (0.00 sec)

Examining the Results

5) To see what tables are present in the database use the SHOW tables:
mysql> SHOW tables;
+------------------------+
| Tables_in_134a |
+------------------------+
| president
|
+------------------------+
1 row in set (0.00 sec)

6) The command DESCRIBE can be used to view the structure of a table
mysql> DESCRIBE president;

Inserting / Retrieving Data into / from Tables

7) To insert new rows into an existing table use the INSERT command:
mysql> INSERT INTO president values ('Washington','George','VA','Westmoreland County','17320212','17991214');
Query OK, 1 row affected (0.00 sec)

8) With the SELECT command we can retrieve previously inserted rows:
mysql> SELECT * FROM president;

Selecting Specific Rows and Columns

9) Selecting rows by using the WHERE clause in the SELECT command
mysql> SELECT * FROM president WHERE state="VA";

10) Selecting specific columns by listing their names
mysql> SELECT state, first_name, last_name FROM president;

Deleting and Updating Rows

11) Deleting selected rows from a table using the DELETE command
mysql> DELETE FROM president WHERE first_name="George";
Query OK, 1 row affected (0.00 sec)

12) To modify or update entries in the table use the UPDATE command
mysql> UPDATE president SET state="CA" WHERE first_name="George";
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0


Loading a Database from a File

13) Loading a your data from a file into a table.
Assuming we have a file named "president_db" in the current directory,
with multiple INSERT commands in it, we can use the LOAD DATA command to
insert the data into the table president.

mysql> LOAD DATA LOCAL INFILE 'president_db' INTO TABLE president;
Query OK, 45 rows affected (0.01 sec)
Records: 45 Deleted: 0 Skipped: 0 Warnings: 0
Note, that any ascii file that contains a valid sequence of MySql
commands on separate lines can be read in from the command line as:
>mysql -u USERNAME -p < MY_Mysql_FILE


More on SELECT

A general form of SELECT is:
SELECT what to select
FROM table(s)
WHERE condition that the data must satisfy;
Comparison operators are: < ; <= ; = ; != or <> ; >= ; >
Logical operators are: AND ; OR ; NOT
Comparison operator for special value NULL: IS

14) The following MySQL query will return all the fields for the
presidents whose state field is "NY";
mysql> SELECT * FROM president WHERE state="NY";

15) We can limit the values of the returned fields as it is shown bellow:
mysql> SELECT last_name, first_name FROM president WHERE state="NY";

16) The following entry SELECT will return the last name and
birth date of presidents who are still alive
Note: The comparison operator will not work in this case:
mysql> SELECT * FROM president WHERE death = NULL;
Empty set (0.00 sec)
mysql> SELECT last_name, birth FROM president WHERE death is NULL;

17) This command will select the presidents who were born in the
18th century
mysql> SELECT last_name, birth FROM president WHERE birth<"1800-01-01";

18) The following command will select the president who was born first
mysql> SELECT last_name, birth from president ORDER BY birth ASC LIMIT 1;

19) The following query will return the names of fist 5 states (in
descending order) in which the greatest number of presidents have been
born
mysql> SELECT state, count(*) AS times FROM president GROUP BY state
-> ORDER BY times DESC LIMIT 5;

20) The following query will select presidents who have been born
in the last 60 years
mysql> SELECT * FROM president WHERE(YEAR(now())- YEAR(birth)) < 60;
Useful function to retrieve parts of dates are: YEAR(), MONTH(), DAYOFMONTH(),TO_DAY().

21) The following query will sort presidents who have died by their
age and list the first 10 in descending order.
mysql> SELECT last_name, birth, death, FLOOR((TO_DAYS(death) - TO_DAYS(birth))/365) AS age
-> FROM president
-> WHERE death is not NULL ORDER BY age DESC LIMIT 10;

Working with Multiple Tables

22) Often it is useful to separate data in conceptually distinct groups and store them in separate tables. Assuming we have a table that contains students' personal information, and we have another table that contains test scores of students. We can create a common field in each table, say "ssn" and work with the two tables together as follows:

SELECT last_name, address, test_date, score FROM test, student WHERE test.ssn = student.ssn;


Related Tutorials:-

ACID properties of Database

SQL Statements : DDL, DML and DCL

Difference between delete, truncate and drop command in SQL

Wednesday 24 April 2013

Extract source code (Java and XML) from Android APK File

Not getting any idea how to make good layout in Android activity or not getting how any application doing that things which you want in your project but you don’t know how to implement it in your APK File. So, I came here with new technology & new thinking which can make you crazy in android world.

Now time for backtracking…start your time to do hacking. Do you know you can get source code of Android APK file? Time to break the code..Let’s learn step by step.

In this tutorial we will learn how to convert android APK file into source code. Android .apk file is a compressed form of a file which contains Java classes (in .dex form), XML files and all necessary files. So first we will learn how to get Java source File from android apk using dex2jar and Java decompiler tools and then we will learn how to get XML source file using apktool and apkinstall tools.

To get the source code from APK file, we will need these tools:

1. dex2jar
2. java decompiler
3. apktool
4. apkinstall

Steps to get source:-

Get Java files from APK:-

1. Rename the .apk file into .zip file (example SharedPr.apk into SharedPr.zip).
2. Extract SharedPr.zip file and copy classes.dex file from extracted folder.
3. Extract dex2jar.zip and paste classes.dex into dex2jar folder.
3. Open command prompt and change directory to the dex2jar folder. Then write dex2jar classes.dex and press enter. Now you will get classes.dex.dex2jar file in the same folder.

How To Get JAVA Code And XML Code From APK
Convert classes.dex to classes.dex.dex2jar
4. Now double click on jd-gui(Java decompiler) and click on open file. Then open classes.dex.dex2jar file from that folder. Now you will get class files and save all these class files (click on file then click “save all sources” in jd-gui) by src name.

How To Get JAVA Code And XML Code From APK
classes.dex.dex2jar will be in dex2jar folder


How To Get JAVA Code And XML Code From APK
Save All Java Files

Get XML files from APK:-

1. Extract apktool and apkinstall in a folder(Example : New Folder).
2. Put SharedPr.apk(your apk file) in same folder(i.e New Folder).

How To Get JAVA Code And XML Code From APK
Keep Android Apk File with apktool and apkinstall

3. Open the command prompt and go to the root directory(i.e New Folder).
4. Type command on command prompt: apktool d SharedPr.apk

How To Get JAVA Code And XML Code From APK
Get All XML Files In Resource Folder

5. This will generate a folder of name SharePr in current directory (here New Folder) and all XML files will be in res->layout folder.

How To Get JAVA Code And XML Code From APK
See All XML Files in new created Folder

Now you have source code. If you have any doubts please comment. Share and help others.

Note:- Video of this post is also available on YouTube, Watch video "How to get source code (Java code and XML code) From Android APK File".

Note:- I disabled comment option on this post because I was getting lots of comment on this post. I updated download links  & if anybody facing any problem than contact me directly.

For more related to Android tutorials see List of Android Tutorials.

Related Tutorials:-

Display Time using Broadcast Receiver

Warning: No DNS servers found in Android Eclipse

Run two or more instances of emulator at a time

Emulator error at runtime: std::bad_alloc

Swipe Left and Right using Gesture Detection

Run two or more Instances of Android Emulator

Sometimes we want to run two or more instances of android emulator like in chat program. In chat program or other applications we need two or more android emulator's instances to check android application. So, we have given solution below:-

......................................................Solution....................................................

1. Select your application -> right click -> Run As -> Run Configuration.

Run two or more instances of Android emulator at a time
Run project with selected device

2. Select your application -> Select Target -> Apply

Run two or more instances of Android emulator at a time
Select Target Device

3. Run your application.
4. Now again repeat this process and choose another target device and than run your application. It will run on another device(means another instance of emulator will run). Use this process again and again and run multiple instances of emulator.

For more Related to Android tutorials see List of Android Tutorials. Share and help others.

Related Tutorials:-

Get all mobile Contacts

Get battery level using Broadcast Receiver

Display Time using Broadcast Receiver

Warning: No DNS servers found in Android Eclipse

Extract APK File into source code (Java code and XML code)

Android emulator error at runtime: std::bad_alloc

Mostly Android users face this problem at run time when they use Android emulator:-

[2013-03-22 11:41:19 - Emulator] terminate called after throwing an instance of 'std::bad_alloc'

[2013-03-22 11:41:19 - Emulator] what(): std::bad_alloc

[2013-03-22 11:41:19 - Emulator]

[2013-03-22 11:41:19 - Emulator] This application has requested the Run-time to terminate it in an unusual way.

[2013-03-22 11:41:19 - Emulator] Please contact the application's support  team for more information.
.....................................................Solution.............................................................

Go to -> Window -> Android Virtual Device Manager

Android emulator error at runtime: std::bad_alloc
Window-> Android virtual device manager

Select your current Virtual Device -> Edit -> Disable 'Use Host GPU' -> Ok

Android emulator error at runtime: std::bad_alloc
Disable 'Use Host GPU' and Enable 'Snapshot'


The reason is that if we enable 'Use Host GPU' than it requires high capability of your system's graphics card but mostly user does not have high quality graphics card that's why it gives problem but it effects on performance of emulator. To increase the performance, enable the 'snapshot' option and now all is OK.

For more related to Android tutorial see List of Android Tutorials. Share this post to help others.

Related Tutorials:- 

Get battery level using Broadcast Receiver

display Time using Broadcast Receiver

Warning: No DNS servers found in Android Eclipse

Extract APK File into source code (Java code and XML code)

Run two or more instances of emulator at a time

C program that prints X with probability=0.1, Y with probability=0.3, and Z with probability=0.6

/*This program uses random function to generate random number which help
to calculate a probability of a occurrence of the specific condition. */

Source Code in java (ProbGen.java)

import java.util.Random;

class ProbGen

{

                public static void main(String ar[])

                {

                /*

                no_x,no_y,no_z are variables to count the no. of x,y and

                z respectevily in the output of the test.

                */

                 int i,no_x=0,no_y=0,no_z=0;

                 float rand=0;

                 for(i=0;i<10000;i++)

                 {

                 /*

                  Random.nextFloat() generates a float from 0.0 (inlcusive)

                  to 1.0 (exclusive).

                 */

                 rand = new Random().nextFloat(); // [0;1)

                 if(rand>=0.0 && rand<0.1)

                   {

                   System.out.print("x");

                   no_x++;

                   }

                   else if(rand>=0.1 && rand<0.4)

                    {

                     System.out.print("y");

                                 no_y++;

                    }else

                                 {

               System.out.print("z");

                                 no_z++;

                     }

                 }

                System.out.println("\nNo of x="+no_x+"\nNo of y="+no_y+"\nNo of Z="+no_z);

                }

}         

-------------------------------------------------------------------------------------------------------------------------

Source Code in C

#include <stdlib.h>

#include <stdio.h>

#include<conio.h>

int main(void)

{

   int i,no_x=0,no_y=0,no_z=0;

   float p;

   clrscr();

   printf("Ten random numbers from 0 to 99\n\n");

   for(i=0; i<10000; i++)

   {

      p= (float)(rand() % 10)/10;

      if(p>=0 && p<0.1)

       {printf("x"); no_x++;}

      else

      if(p>=0.1 && p<=0.4)

{printf("y");no_y++;}

      else

{printf("z");no_z++;}

   }

     printf("\nNo fo x=%d\No of y=%d\nNo of z=%d",no_x,no_y,no_z);

      getch();

   return 0;

}

 

C code to Convert Hexadecimal String to Decimal number

//This program takes a hexadecimal string and converts it into the decimal string//

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

int main()
{
char *str;
clrscr();
printf("\nEnter a hexadecimal string\n");
gets(str);

printf("\nthe corresponding decimal value is %d",htoi(str));
getch();
return(0);
}

int power (int a, int b) // utility function
{
int res = 1 ;
while( b>0 )
{
res *= a ;
b--;
}
return ( res );
}

int htoi ( char* s )
{
int result = 0,new_result;
//int value =0;
int len = strlen(s);
int exp = len;
char c;
int i;

  for( i=0; i<len; i++)
   {

    c = s[i];

     if ( c >='1' && c<='9')
new_result = (int)( (c - '0') * power(16, exp-1) );

     else
if (c >='A' && c<='F')
  new_result = (int)( (c - 55) * power(16, exp-1) );

    exp --;
    result += new_result;

   }

return (result);
}

C code to find 2's complement

//This program takes a binary string and converts it into the 2's complement. //

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

void revert(char *str,char *comp,int l);

int main()
{
  int i,found=0,l,stlen;
  char *str,*comp;

  clrscr();

printf("\nEnter a binary string\n");
gets(str);
stlen=strlen(str);
l=stlen;
l--;
       // printf("\nlength=%d..%c..",l,str[l]);
while(l)
{
if(found)
{
revert(str,comp,l);
break;
}
else
{
if(str[l]=='1')
found=1;
comp[l]=str[l];
printf("%c",str[l]);
l--;
}
}
printf("\ncopmlement is");
puts(comp);

getch();
return(0);
}


void revert(char *str,char *comp,int l)
{
while(l>=0)
{
if(str[l]=='1')
{
    printf("0");
    comp[l--]='0' ;}
else
{
   printf("1");
   comp[l--]='1';}
}
}



ACID Properties of Database

These are the ACID properties of Database:-

Atomicity:-

All changes to data are performed as if they are a single operation. That is, all the changes are performed, or none of them are.

For example, in an application that transfers funds from one account to another, the atomicity property ensures that, if a debit is made successfully from one account, the corresponding credit is made to the other account.

Consistency:-

Data is in a consistent state when a transaction starts and when it ends.
For example, in an application that transfers funds from one account to another, the consistency property ensures that the total value of funds in both the accounts is the same at the start and end of each transaction.

Isolation:-

The intermediate state of a transaction is invisible to other transactions. As a result, transactions that run concurrently appear to be serialized.

For example, in an application that transfers funds from one account to another, the isolation property ensures that another transaction sees the transferred funds in one account or the other, but not in both, nor in neither.

Durability:-

After a transaction successfully completes, changes to data persist and are not undone, even in the event of a system failure.

For example, in an application that transfers funds from one account to another, the durability property ensures that the changes made to each account will not be reversed.

Related Tutorials:-

Tutorials to understand SQL language

SQL Statements : DDL, DML and DCL

Difference between delete, truncate and drop command in SQL

Tuesday 23 April 2013

Java code for maintaining a student records database using File Handling

Java program for maintaining a student records database using File Handling.

import java.io.*;
class StudentRecords
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

 public void addRecords() throws IOException
 {
 // Create or Modify a file for Database
 PrintWriter pw = new PrintWriter(new BufferedWriter(new
 FileWriter("studentRecords.txt",true)));
 String name, Class, fname, mname, address, dob;
 int age;
 long telephoneNo;
 String s;
 boolean addMore = false;
 // Read Data
 do
 {
  System.out.print("\nEnter name: ");
  name = br.readLine();

  System.out.print("Father's Name: ");
  fname = br.readLine();

  System.out.print("Mother's Name: ");
  mname = br.readLine();

  System.out.print("Address: ");
  address = br.readLine();

  System.out.print("Class: ");
  Class = br.readLine();

  System.out.print("Date of Birth (dd/mm/yy) : ");
  dob = br.readLine();

  System.out.print("Age: ");
  age = Integer.parseInt(br.readLine());

  System.out.print("Telephone No.: ");
  telephoneNo = Long.parseLong(br.readLine());
  // Print to File
  pw.println(name);
  pw.println(fname);
  pw.println(mname);
  pw.println(address);
  pw.println(Class);
  pw.println(dob);
  pw.println(age);
  pw.println(telephoneNo);
  
  System.out.print("\nRecords added successfully !\n\nDo you want to add more records ? (y/n) : ");
  s = br.readLine();
  if(s.equalsIgnoreCase("y"))
  {
   addMore = true;
   System.out.println();
  }
  else
   addMore = false;
 }
 while(addMore);
 pw.close();
 showMenu();
 }
 public void readRecords() throws IOException
 {
 try
 {
  // Open the file
  BufferedReader file = new BufferedReader(new
  FileReader("studentRecords.txt"));
  String name;
  int i=1;
  // Read records from the file
  while((name = file.readLine()) != null)
  {
   System.out.println("S.No. : " +(i++));
   System.out.println("-------------");
   System.out.println("\nName: " +name);
   System.out.println("Father's Name : "+file.readLine());
   System.out.println("Mother's Name : "+file.readLine());
   System.out.println("Address: "+file.readLine());
   System.out.println("Class: "+file.readLine());
   System.out.println("Date of Birth : "+file.readLine());
   System.out.println("Age: "+Integer.parseInt(file.readLine()));
   System.out.println("Tel. No.: "+Long.parseLong(file.readLine()));
   System.out.println();
  }
  file.close();
  showMenu();
 }
 catch(FileNotFoundException e)
 {
  System.out.println("\nERROR : File not Found !!!");
 }
 }
 public void clear() throws IOException
 {
 // Create a blank file
 PrintWriter pw = new PrintWriter(new BufferedWriter(new
 FileWriter("studentRecords.txt")));
 pw.close();
 System.out.println("\nAll Records cleared successfully !");
 for(int i=0;i<999999999;i++); // Wait for some time
 showMenu();
 }
 public void showMenu() throws IOException
 {
 System.out.print("1 : Add Records\n2 : Display Records\n3 : Clear All Records\n4 : Exit\n\nYour Choice : ");
 int choice = Integer.parseInt(br.readLine());
 switch(choice)
 {
  case 1:
   addRecords();
   break;
  case 2:
   readRecords();
   break;
  case 3:
   clear();
   break;
  case 4:
   System.exit(1);
   break;
  default:
   System.out.println("\nInvalid Choice !");
   break;
 }
 }
 public static void main(String args[]) throws IOException
 {
 StudentRecords call = new StudentRecords();
 call.showMenu();
 }
}

Algorithm for Adding Records:-

1. Start

2. Open the database file.

3. Read data from the user.

4. Print the data to file.

5. Close the file.

6. End

Algorithm for Displaying Records:-

1. Start

2. Open the database file.

3. Read data from the filr.

4. Print the data on screen.

5. Close the file.

6. End

Algorithm for Clearing All Records:-

1. Start

2. Overwrite the database file with a blank file.

5. Close the file.

6. End

OUTPUT:-

Java code for maintaining a student records database using File Handling

1 : Add Records

2 : Display Records

3 : Clear All Records

4:  Exit

Your Choice : 1

Enter name : Mayank K. Rastogi

Father's Name : Surendra Kumar Rastogi

Mother's Name : Sushma Rastogi

Address : Vipul Khand, Gomti Nagar, Lucknow.

Class : 12 - C

Date of Birth (dd/mm/yy) : 01/10/91

Age : 18

Telephone No. : 9546354565

Records added successfully !

Do you want to add more records ? (y/n) : y

.........

.......

Related Programs:-

Insert,delete and display Dequeue

Insert,delete and display Circular Queue

Insert,delete and display Linear Queue

Insert,delete and display elements from Stack

Display the solution of Towers of Hanoi using recursion

Java code to insert,delete and display from Dequeue

/*
Java program to implement dequeue.
*/

import java.io.*;
class dequeue
{
int DQ[] = new int[100];
int n;
int front, rear;
static BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
public dequeue(int nn)
{
n = nn;
front = rear = 0;
}
public void pushrear(int v)
{
if((rear+1)<n)
{
rear++;
DQ[rear] = v;
}
else
System.out.println("Overflow from rear !");
}
public void pushfront(int v)
{
if(front>=0)
{
DQ[front] = v;
front--;
}
else
System.out.println("Overflow from front !");
}
public int popfront()
{
int v;
if(front!=rear)
{
front++;
v = DQ[front];
return v;
}
else
return -9999;
}
public int poprear()
{
int v;
if(front!=rear)
{
v = DQ[rear];
rear--;
return v;
}
else
return -9999;
}
public void display()
{
if(front!=rear)
{
for(int i=front+1;i<=rear;i++)
System.out.println(DQ[i]);
}
else
System.out.println("No element in queue !");
}
public static void main() throws IOException
{
System.out.print("Enter the size of the queue : ");
int size = Integer.parseInt(br.readLine());
dequeue call = new dequeue(size);
int choice;
boolean exit = false;
while(!exit)
{
System.out.print("\n1 : Push from Front\n2 : Push from
Rear\n3 : Delete from Front\n4 : Delete from Rear\n5 : Display\n6 :
Exit\n\nYour Choice : ");
choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1 :
System.out.print("\nEnter number to be added : ");
int num = Integer.parseInt(br.readLine());
call.pushfront(num);
break;
case 2 :
System.out.print("\nEnter number to be added : ");
int num2 = Integer.parseInt(br.readLine());
call.pushrear(num2);
break;
case 3 :
int popped = call.popfront();
if(popped != -9999)
System.out.println("\nDeleted : " +popped);
break;
case 4 :
int popped2 = call.popfront();
if(popped2 != -9999)
System.out.println("\nDeleted : " +popped2);
break;
case 5 :
call.display();
break;
case 6 :
exit = true;
break;
default :
System.out.println("\nWrong Choice !");
break;
}
}
}
}

/**
* Algorithm for Push from Front :
* -----------------------------
* 1. Start
* 2. If(front>=0) then
* 3. dq[front]=v;
* 4. front=front-1;
*
else
* 5. "overflow from front"
* 6. End
*
* Algorithm for Push from Rear :
* ----------------------------
* 1. Start
* 2. If ((rear+1)<n) then
* 3. rear=rear+1;
* 4. dq[rear]=v;
*
else
* 5. "overflow from rear"
* 6. End
*
* Algorithm for Pop from Front :
* ----------------------------
* 1. Start
* 2. If(front!=rear) then
* 3. front=front+1;
* 4. v=dq[front];
*
else
* 5. "dequeue empty from front"
* 6. End
*
* Algorithm for Pop from Rear :
* ---------------------------
* 1. Start
* 2. If(front!=rear) then
* 3. v=dq[rear];
* 4. rear=rear-1;
*
else
* 5. "dequeue is empty from rear"
* 6. End
*/

/*
OUTPUT :
------
Enter the size of the queue : 6
1:Push from Front
2:Push from Rear
3:Delete from Front
4:Delete from Rear
5:Display
6:Exit

Your Choice : 1
Enter number to be added : 2
....
...
...
......
...
*/


Java code to insert,delete and display from Circular Queue

/*
Program for realisation of Circular Queue
*/
import java.io.*;
class circularQ
{
int Q[] = new int[100];
int n, front, rear;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public circularQ(int nn)
{
n=nn;
front = rear = 0;
}
public void add(int v)
{
if((rear+1) % n != front)
{
rear = (rear+1)%n;
Q[rear] = v;
}
else
System.out.println("Queue is full !");
}
public int del()
{
int v;
if(front!=rear)
{
front = (front+1)%n;
v = Q[front];
return v;
}
else
return -9999;
}
public void disp()
{
int i;
if(front != rear)
{
i = (front +1) %n;
while(i!=rear)
{
System.out.println(Q[i]);
i = (i+1) % n;
}
}
else
System.out.println("Queue is empty !");
}
public static void main() throws IOException
{
System.out.print("Enter the size of the queue : ");
int size = Integer.parseInt(br.readLine());
circularQ call = new circularQ(size);
int choice;
boolean exit = false;
while(!exit)
{
System.out.print("\n1 : Add\n2 : Delete\n3 : Display\n4 :
Exit\n\nYour Choice : ");
choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1 :
System.out.print("\nEnter number to be added : ");
int num = Integer.parseInt(br.readLine());
call.add(num);
break;
case 2 :
int popped = call.del();
if(popped != -9999)
System.out.println("\nDeleted : " +popped);
else
System.out.println("\nQueue is empty !");
break;
case 3 :
call.disp();
break;
case 4 :
exit = true;
break;
default :
System.out.println("\nWrong Choice !");
break;
}
}
}
}

/**
* Algorithm for Push :
* ------------------
* 1. Start
* 2. if((rear+1)%n = front) then queue is full (overflow)
*
else
* 3. rear = (rear+1)%n;
* 4. Q[rear] = v;
* 5. End
*
* Algorithm for pop :
* -----------------
* 1. Start
* 2. if(front == rear) then queue is empty (underflow)
*
else
* 3. front = (front+1)%n;
* 4. v = Q[front];
* 5. End
*/

/*
OUTPUT :
------
Enter the size of the queue : 5
1:Add
2:Delete
3:Display
4:Exit
Your Choice : 1
Enter number to be added : 35
....
....
...
...
..
.
*/



Java code to insert,delete and display from Linear Queue

/*
Java program to implement Linear Queue.
*/
import java.io.*;
class queue
{
int Q[] = new int[100];
int n, front, rear;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public queue(int nn)
{
n=nn;
front = rear = 0;
}
public void add(int v)
{
if((rear+1) <= n)
Q[++rear] = v;
else
System.out.println("Queue is full !");
}
public int del()
{
int v;
if(front!=rear)
{
v = Q[++front];
return v;
}
else
{
System.out.println("\nQueue is empty !");
return -9999;
}
}
public void disp()
{
if(front==rear)
System.out.println("\nQueue is empty !");
else
{
for(int i = front+1; i<=rear;i++)
System.out.println(Q[i]);
}
}
public static void main() throws IOException
{
System.out.print("Enter the size of the queue : ");
int size = Integer.parseInt(br.readLine());
queue call = new queue(size);
int choice;
boolean exit = false;
while(!exit)
{
System.out.print("\n1 : Add\n2 : Delete\n3 : Display\n4 :
Exit\n\nYour Choice : ");
choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1 :
System.out.print("\nEnter number to be added : ");
int num = Integer.parseInt(br.readLine());
call.add(num);
break;
case 2 :
int popped = call.del();
if(popped != -9999)
System.out.println("\nDeleted : " +popped);
break;
case 3 :
call.disp();
break;
case 4 :
exit = true;
break;
default :
System.out.println("\nWrong Choice !");
break;
}
}
}
}


/**
* Algorithm for Linear Queue Addition :
* -----------------------------------
* 1. Start
* 2. if (rear+1>=n) then queue is full (overflow)
*
else
* 3. rear = rear+1;
* 4. Q[rear] = v;
* 5. End
*
* Algorithm for Linear Queue Deletion :
* -----------------------------------
* 1. Start
* 2. if(front == rear) then queue is empty (underflow)
*
else
* 3. front = front+1;
* 4. v = Q[front];
* 5. End
*/

/*
OUTPUT :
------
1:Add
2:Delete
3:Display
4:Exit
Your Choice : 3
8
3
4
25
.......
....
...
..
.
*/


Java code to insert,delete and display elements from stack

/*
Java program to implement stack.
*/
import java.io.*;
class stacks
{
int s[] = new int[100];
int top, n;
public stacks(int nn)
{
n=nn;
top=-1;
}
public void push(int v)
{
if(top<n-1)
{
top++;
s[top] = v;
}
else
System.out.println("\nStack is full !");
}
public int pop()
{
int v;
if(top>=0)
{
v = s[top];
top--;
return v;
}
else
{
System.out.println("\nStack is empty !");
return -9999;
}
}
public void display()
{
if(top>=0)
{
System.out.println();
for(int i=top;i>=0;i--)
System.out.println(s[i]);
}
else
System.out.println("\nStack is empty !");
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the size of the stack : ");
int size = Integer.parseInt(br.readLine());
stacks call = new stacks(size);
int choice;
boolean exit = false;
while(!exit)
{
System.out.print("\n1 : Push\n2 : Pop\n3 : Display\n4 :
Exit\n\nYour Choice : ");
choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1 :
System.out.print("\nEnter number to be pushed : ");
int num = Integer.parseInt(br.readLine());
call.push(num);
break;
case 2 :
int popped = call.pop();
if(popped != -9999)
System.out.println("\nPopped : " +popped);
break;
case 3 :
call.display();
break;
case 4 :
exit = true;
break;
default :
System.out.println("\nWrong Choice !");
break;
}
}
}
}

/**
* Algorithm for push :
* ------------------
* 1. Start
* 2. if(top>=n) then stack is full (overflow) (n = minimum capacity
of stack)
*
else
* 3. top = top+1;
* 4. s[top] = v;
* 5. End
*
* Algorithm for pop :
* -----------------
* 1. Start
* 2. if(top<0) then stack is empty (underflow)
*
else
* 3. v = s[top];
* 4. top = top-1;
* 5. End
*/
/*
OUTPUT :
------
Enter the size of the stack : 5
1:Push
2:Pop
3:Display
4:Exit
Your Choice : 1
Enter number to be pushed : 10
.....
....
..
..
.
*/


Java code to display the solution of Tower of Hanoi using recursion

/*
Program to display the solution of Tower of Hanoi using recursion.
*/
import java.io.*;
class towerOfHanoi
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
towerOfHanoi call = new towerOfHanoi();
System.out.print("Enter number of discs : ");
int n = Integer.parseInt(br.readLine());
System.out.print("\nLabel of 1st stick : ");
String a = br.readLine();
System.out.print("Label of 2nd stick : ");
String b = br.readLine();
System.out.print("Label of 3rd stick : ");
String c = br.readLine();
call.hanoi(n,a,b,c);
}
void hanoi (int n, String a, String b, String c)
{
if(n==1)
System.out.println("Move disc from " +a +" to " +c);
else
{
hanoi(n-1,a,c,b);
System.out.println("Move disc from " +a +" to " +c);
hanoi(n-1,b,a,c);
}
}
}


/**
* ALGORITHM :
* ---------
* 1. Start
* 2. Accept the number of discs from the user.
* 3. Ask for the labels of sticks A, B & and C.
* 4. Move n−1 discs from A to B. This leaves disc #n alone on stick A.
* 5. Move disc #n from A to C.
* 6. Move n−1 discs from B to C so they sit on disc #n.
* 7. Repeat steps 4 to 6 using recursion.
* 8. End
*/

/*
OUTPUT :
------
Enter number of discs : 4
Label of 1st stick : start
Label of 2nd stick : mid
Label of 3rd stick : end

Move disc from start to mid
Move disc from start to end
....
....
....
....

..
.
.

*/



Java code to convert a number into words

/*
Program to convert a number into words.
*/
import java.io.*;
class numerals2words
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
numerals2words call = new numerals2words();
System.out.print("Enter a number : ");
int n = Integer.parseInt(br.readLine());
call.convert(n);
}
public void convert(int n)
{
int c;
if(n!=0)
{
c = n%10;
convert(n/10);
num2words(c);
}
}
public void num2words(int n)
{
String words[] =
{"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE
"};
System.out.print(words[n] +" ");
}
}


/**
* ALGORITHM :
* ---------
* 1. Start
* 2. Accept a number from the user.
* 3. Extract a digit from the number.
* 4. Print the digit in words.
* 5. Using recursion repeat steps 3 and 4 till all the digits are
extracted.
* 6. End
*/

/*
OUTPUT :
------
Enter a number : 8496
EIGHT FOUR NINE SIX
*/


Java code to reverse a word or sentence ending with '.' using recursion

/*
Program to reverse a word or sentence ending with '.' using recursion
*/
import java.io.*;
class reverseWord
{
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public static void main(String args[]) throws IOException
{
reverseWord call = new reverseWord();
System.out.print("Enter characters & '.' to end : ");
call.print();
}
void print() throws IOException
{
char c = (char)br.read();
if(c!='.')
{
print();
System.out.print(c);
}
}
}


/**
* ALGORITHM :
* ---------
* 1. Start
* 2. Accept a sentence from user with full-stop(.) at the end.
* 3. Using recursion, print the sentence in reverse order.
* 4. End
*/

/*
OUTPUT :
------
Enter characters & '.' to end : stressed.
desserts
*/


Java code to convert Decimal to Octal

/*
Program to convert Decimal to Octal.
*/
import java.io.*;
class decimal2octal
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
decimal2octal call = new decimal2octal();
System.out.print("Enter a decimal number : ");
int n = Integer.parseInt(br.readLine());
System.out.print("\nOctal Equivalent : ");
call.dec2oct(n);
}
void dec2oct(int n)
{
int c;
if(n!=0)
{
c=n%8;
dec2oct(n/8);
System.out.print(c);
}
}
}


/**
* ALGORITHM :
* ---------
* 1. Start
* 2. Accept a decimal number from the user.
* 3. Using recursion, convert it to octal.
* 4. Print the Octal Equivalent.
* 5. End
*/

/*
OUTPUT :
------
Enter a decimal number : 25
Octal Equivalent : 31
*/


Java code to convert Decimal into Binary

Java program to convert Decimal into Binary.

import java.io.*;
class Decimal2binary
{
 public static void main(String args[]) throws IOException
 {
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 Decimal2binary call = new Decimal2binary();
 System.out.print("Enter a decimal number : ");
 int n = Integer.parseInt(br.readLine());
 System.out.print("Binary Equivalent : ");
 call.dectobin(n);
 System.out.print("\n");
 }
 void dectobin(int n)
 {
 int c;
 if(n!=0)
 {
  c=n%2;
  dectobin(n/2);
  System.out.print(c);
 }
 }
}

ALGORITHM:-

1. Start

2. Accept a decimal number from the user.

3. Using recursion, convert it to binary.

4. Print the Binary Equivalent.

5. End

OUTPUT:-

Java code to convert Decimal into Binary

Enter a decimal number : 25

Binary Equivalent : 11001

Related Programs:-

Convert Decimal to Octal

Print the Factorial of a number using recursion

Print the possible combination of a string

Generate Fibonacci series using recursion

Find the HCF & LCM of two numbers using recursion

Java code to calculate factorial of a number using recursion

Java program to calculate factorial of a number using recursion.

import java.io.*;
class Factorial
{
 public static void main(String args[]) throws IOException
 {
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 Factorial call = new Factorial();
 System.out.print("Enter a number : ");
 int n = Integer.parseInt(br.readLine());
 System.out.println("Factorial = " +call.fact(n));
 }
 int fact(int n)
 {
 if(n<2)
  return 1;
 else
  return n*fact(n-1);
 }
}

ALGORITHM:-

1. Start

2. Accept a number n from the user.

3. Using method of recursion, multiply all the numbers upto n.

4. Print the Factorial.

5. End

OUTPUT:-

Java code to print factorial of a number using recursion

Enter a number : 5
Factorial = 120

Related Programs:-

Generate Fibonacci series using recursion

Find the HCF & LCM of two numbers using recursion

Find the sum of the following series using recursion : 12 + 22 + 32 +.......+ n2

Find the sum of Natural numbers up to a given number using Recursion

Calculate the Power of a number using recursion

Java code to print possible Permutations of a String

Java Program to print the possible Permutations of a String.

import java.io.*;
class Combination
{
 public static void main(String args[]) throws IOException
 {
 Combination call = new Combination();
 BufferedReader br = new BufferedReader(new
 InputStreamReader(System.in));
 System.out.print("Enter a String : ");
 String n = br.readLine();
 call.comb("",n);
 }
 public void comb(String beg, String end) throws IOException
 {
 if (end.length()<=1)
 {
  System.out.println(beg+end);
 }
 else
 {
  for (int i=0;i<end.length();i++)
  {
   String n = end.substring(0,i)+end.substring(i+1);
   comb(beg + end.charAt(i),n);
  }
 }
 }
}

ALGORITHM:-

1. Start

2. Accept a string from the user.

3. Using recursion find all the combinations of the string.

4. Print the combinations.

5. End

OUTPUT:-

Java code to print possible Permutations of a String

Enter a String : TOP
TOP
TPO
OTP
OPT
PTO
POT

Related Programs:-

Convert Decimal to Octal

Convert Decimal to Binary

Print the Factorial of a number using recursion

Print the possible combination of a string

Generate Fibonacci series using recursion
Back to Top