Monday 8 September 2014

Program to Reverse a Number in Java



Reverse a Number :

Since every digit when divided by 10 gives the remainder equal to the unit place digit of that number and we need to set that unit place digit of number to the last place digit of the number than again set the 100’s digit of that number to the second last place of the given number and so on.

To get the remainder of a number, a modulus (%) operator is used in the program. The program is shown below :

 import java.util.Scanner;  
   
 class ReverseNumber  
 {  
      public static void main(String[] args)  
      {  
           Scanner scan = new Scanner(System.in);  
   
           //scan for the number  
           System.out.println("Enter the number you want to reverse");  
           int n = scan.nextInt();  
   
           //initialize a variable to zero in which we will store reverse no.  
           int reverse = 0;  
   
           //make a while loop till the number will zero  
           while(n != 0)  
           {  
                //first multiply the reverse no. with 10 to shift its digit to next place  
                reverse = reverse * 10;  
                //add the remainder of number/10 to the reverse no.  
                reverse = reverse + n%10;  
                  
                //divide the number by 10 to reduce its one place  
                n = n/10;  
   
                //if n==0 than exit from the loop else repeat  
           }  
   
           //print the reverse number  
           System.out.println("The reverse number is "+reverse);  
      }  
 }  

Output :



In this program we repeatedly find the remainder or unit digit of number by modulus operation with 10 and than reduce the digits by dividing  the number with 10  to get the next unit digit of the given number.
Read more

Auto Complete Text View Tutorial in Android



Auto Complete Text View :


In Auto Complete Text View whenever we start writing a text in the Edit View than it will automatically show the available options related to that text as you stored in an array or in a database. You can see the example shown in the following screenshot :

In this example, I am storing the available options in the array and than just set the adapter for simple dropdown list available in android environment with that list.

To make this type of application you need to use the AutoCompleteTextView class available in android environment rather than simple TextView or EditView.

Let’s start coding by creating a project in Eclipse : File => New => Android Application Project and give a package name as com.javalanguageprogramming.autocompletetextdemo.

Copy the code for activity_main.xml as shown below :

   
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   >  
   
   <AutoCompleteTextView  
     android:id="@+id/autoText"  
     android:layout_width="220dp"  
     android:layout_height="50dp"  
     android:layout_marginLeft="40dp"  
     android:layout_marginTop="50dp"  
     />  
   
 </LinearLayout>  
   


In this xml file I am using AutoCompleteTextView for completing of text automatically from String array.

Now consider the code for Main.java as shown below :

 package com.javalanguageprogramming.autocompletetextdemo;  
   
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.widget.ArrayAdapter;  
 import android.widget.AutoCompleteTextView;  
   
   
 public class MainActivity extends Activity {  
   
      AutoCompleteTextView autoText;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
             
           //initialize auto complete text view  
           autoText = (AutoCompleteTextView)findViewById(R.id.autoText);  
             
           //make an array for the suggestions  
           String[] suggest = {"aa", "all", "auto", "ask", "bb", "bat", "bad", "back", "ball", "cat", "java", "Program", "tutorial"};  
             
           //make an array adapter for viewing string array  
           ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, suggest);  
             
           //set the adapter to the auto complete text view  
           autoText.setAdapter(adapter);  
      }  
 }  
   


In this Activity, a String array named as “suggest” is used to provide the available options and ArrayAdapter for providing the views to the drop down list.
Read more

Sunday 7 September 2014

Matrix Multiplication Program in Java



Matrix Multiplication Program :


To multiply two matrices we need to first check whether the two matrices can be multiplied or not. For that compare the first matrix column with the rows of second matrix, if they are equal than only the two matrices can be multiplied with each other.

For example :

Let the first matrix be of the order 3X3 and second matrix be of the order of 3X2. Since both the no. of columns in first matrix and no. of rows in second matrix are equal i.e. 3, the two matrices can be multiplied with each other and the resultant matrix will be of the order 3X2 (rows in first matrix and columns in second matrix).

In general,
M(ixj) * M(jxk) = M(ixk)

To multiply the two matrices we need to multiply the rows of first matrix to the columns of second matrix as shown below in the diagram.



Now let’s consider the program of matrix multiplication in which the two matrices are multiplied with the use of three nested loops.

 import java.util.Scanner;  
   
 class MatrixMulDemo  
 {  
      public static void main(String[] args)  
      {  
           //make a scanner for rows and columns  
           Scanner scan = new Scanner(System.in);  
   
           System.out.println("Enter the number of rows for first matrix");  
   
           //store rows in a variable  
           int rowsFirst = scan.nextInt();  
           System.out.println("Enter the number of columns for first matrix / rows of   
   
 second matrix (they must be same for matrix multiplication");  
             
           //store columns in a variable  
           int colFirstRowSec = scan.nextInt();  
   
           System.out.println("Enter the columns for second matrix");  
           //store columns of second matrix in a variable  
           int colSec = scan.nextInt();  
   
           //make two dimensional arrays for storing the matrices elements  
   
           int[][] first = new int[rowsFirst][colFirstRowSec];  
           int[][] second = new int[colFirstRowSec][colSec];  
   
           System.out.println("Enter the values of first matrix");  
           for(int i=0; i<first.length; i++)  
           {  
                for(int j=0; j<first[0].length; j++)  
                {  
                     first[i][j] = scan.nextInt();  
                }  
           }  
   
           System.out.println("Enter the values of second matrix");  
           for(int i=0; i<second.length; i++)  
           {  
                for(int j=0; j<second[0].length; j++)  
                {  
                     second[i][j] = scan.nextInt();  
                }  
           }  
   
           //define the third resultant matrix  
           int result[][] = new int[rowsFirst][colSec];  
   
           //multiply the two matrices using three nested loops  
           for(int i=0; i<rowsFirst; i++)  
           {  
                for(int j=0; j<colSec; j++)  
                {  
                     for(int k=0; k<colFirstRowSec; k++)  
                     {  
                          result[i][j] = result[i][j] + first[i][k] * second  
   
 [k][j];  
                     }  
                }  
           }  
   
           //print all the elements of result matrix  
           System.out.println("Product of two matrices ");  
           for(int i=0; i<result.length; i++)  
           {  
                for(int j=0; j<result[0].length; j++)  
                {  
                     System.out.print(result[i][j] + " ");  
                }  
                //for line gap  
                System.out.println();  
           }  
      }  
 }  

Output :

Read more

Transfer data from one Activity to Another Activity in Android



Transfer data with Intents :


We can easily transfer data from one activity to another activity with the use of Intents in Android Application. In this example I am sending the name (set in edit text) from one activity and will use that name in another activity.


Create a new project in Eclipse : File => New => Android Application Project and give the package name as com.javalanguageprogramming.datatransferfromactivitydemo.

Copy the code in activity_main.xml shown below :


 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical"  
   android:background="#ced3e2"  
    >  
   
   <LinearLayout  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:orientation="horizontal" >  
   
     <TextView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_marginLeft="20dp"  
       android:layout_marginTop="10dp"  
       android:text="Your Name"  
       android:textSize="18sp" />  
   
     <EditText  
       android:id="@+id/nameEdit"  
       android:layout_width="180dp"  
       android:layout_height="40dp"  
       android:layout_marginLeft="20dp"  
       android:layout_marginTop="10dp" />  
   </LinearLayout>  
   
   <Button  
     android:id="@+id/sendButton"  
     android:layout_width="100dp"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center"  
     android:layout_marginTop="10dp"  
     android:text="Send" />  
   
 </LinearLayout>  

In the above xml file a text view is used to give the label “your name” and edit text is used for entering the name and a button is used to send the name to another activity.

Copy the code in activity_receive_data.xml shown below :

 <?xml version="1.0" encoding="utf-8"?>  
   
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical"  
   android:background="#ced3e2"  
    >  
   
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center"  
     android:layout_marginTop="30dp"  
     android:gravity="center"  
     android:text="Hey!"  
     android:textSize="23sp" />  
   
   <TextView  
     android:id="@+id/nameText"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center"  
     android:layout_marginTop="10dp"  
     android:gravity="center"  
     android:textSize="25sp"  
     android:textStyle="bold" />  
   
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center"  
     android:layout_marginTop="10dp"  
     android:gravity="center"  
     android:text="Welcome to"  
     android:textSize="23sp" />  
   
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center"  
     android:layout_marginTop="10dp"  
     android:gravity="center"  
     android:text="http://javalanguageprogramming.blogspot.in"  
     android:textSize="20sp" />  
   
 </LinearLayout>  


In the above code 4 text views are used, out of one is used for the name which is coming from MainActivity.

Copy the code in MainActivity.java shown below :

 package com.javalanguageprogramming.datatransferfromactivitydemo;  
   
 import android.app.Activity;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.EditText;  
   
   
 public class MainActivity extends Activity {  
   
      EditText name;  
      Button send;  
        
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
             
           //initialize variables  
           name = (EditText)findViewById(R.id.nameEdit);  
           send = (Button)findViewById(R.id.sendButton);  
             
           //set on click listener on button  
           send.setOnClickListener(new OnClickListener() {  
                  
                @Override  
                public void onClick(View v) {  
                     // check if the edit text is empty or not  
                     if(name.getText() != null || !name.getText().equals("")){  
                          //make an intent  
                          Intent intent = new Intent(MainActivity.this, ReceiveDataActivity.class);  
                          //put data in intent  
                          intent.putExtra("NAME", name.getText().toString());  
                          //clear the edit text so that after user come back he will again enter text  
                          name.setText("");  
                          //start another activity  
                          startActivity(intent);  
                     }  
                }  
           });  
      }  
 }  
   


In this activity, putExtra method of Intent type is used to send the data from this activity to another activity.

Copy the code of ReceiveDataActivity.java shown below :

 package com.javalanguageprogramming.datatransferfromactivitydemo;  
   
 import android.app.Activity;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.widget.TextView;  
   
   
 public class ReceiveDataActivity extends Activity{  
   
      TextView nameText;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           // TODO Auto-generated method stub  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_receive_data);  
             
           //initialize text view  
           nameText = (TextView)findViewById(R.id.nameText);  
             
           //get the intent  
           Intent intent = getIntent();  
           //get the name with the use of intent  
           String name = intent.getStringExtra("NAME");  
             
           //set the text view  
           nameText.setText(name);  
      }  
   
 }  
   


In this activity, getStringExtra method of intent type is used to receive data in this activity that came from previous activity.

Do not forget to add ReceiveDataActivity in AndroidManifest. The code of AndroidManifest is shown below :

 <?xml version="1.0" encoding="utf-8"?>  
   
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.javalanguageprogramming.datatransferfromactivitydemo"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   
   <uses-sdk  
     android:minSdkVersion="8"  
     android:targetSdkVersion="19" />  
   
   <application  
     android:allowBackup="true"  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
     <activity  
       android:name="com.javalanguageprogramming.datatransferfromactivitydemo.MainActivity"  
       android:label="@string/app_name" >  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
   
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
     <activity  
       android:name="com.javalanguageprogramming.datatransferfromactivitydemo.ReceiveDataActivity"  
       android:label="@string/app_name" >  
         
     </activity>  
   </application>  
   
 </manifest>  
   

Read more

Friday 5 September 2014

Inheritance in Java



DEFINITION OF INHERITANCE :

Inheritance is one of the cornerstones of Object Oriented Programming (OOP) which means to inherit the properties of one class and extends according to the need. The two keywords used in inheritance are extends (for class) and implements (for interface).

Inheritance allows the creation of hierarchical classifications. In inheritance a general class is used to define the common methods and variables that can be used in other class. The class which inherits the general class will get all the public methods and variables present in the general class. Now, general class is called super class or base class and the class which inherits its properties is knows as sub class or child class.

To understand the concept of inheritance, consider an example :

Suppose you want to calculate the area of a square, a rectangle, a circle having same radius as length of square than by using the same length available in the base class Shape you can easily extends that class to Square class or rectangle class or circle class by the use of extends keyword.

 class Shape  
 {  
      //define a length which is public and can be used in square,   
      //rectangle and circle classes  
      public int length = 10;  
 }  
   
 //inherit the properties of Shape class with the use of extends keyword  
   
 class Square extends Shape  
 {  
      void area()  
      {  
           //calculate area of square  
           int area = length * length;  
   
           //print it on the screen  
           System.out.println("Area of square : "+area);  
      }  
 }  
   
 class Rectangle extends Shape  
 {  
      void area()  
      {  
           //define a breadth  
           int breadth = 7;  
           //calculate area of rectangle  
           int area = length * breadth;  
           //print on the screen  
           System.out.println("Area of rectangle : "+area);  
      }  
 }  
   
 class Circle extends Shape  
 {  
      void area()  
      {  
           //calculate area of circle using length of the shape class as radius  
           float area = 3.14f * length * length;  
           //print on the screen  
           System.out.println("Area of circle : "+area);  
      }  
 }  
   
 //make a entry class which contains main method  
 class InheritanceDemo  
 {  
      public static void main(String[] args)  
      {  
           //object of child class square  
           Square sq = new Square();  
           //object of child class rectangle  
           Rectangle rec = new Rectangle();  
           //object of child class circle  
           Circle cir = new Circle();  
             
           //call the area methods of all child class to   
           //get the area of different objects  
           sq.area();  
           rec.area();  
           cir.area();  
      }  
 }  

Output :




Why we use Inheritance?

Inheritance is used because it provides the Reusability of the code like in the above example we used the same length from the Shape class thrice in different three classes.

Types of Inheritance in Java :

There are three general types of inheritance in java. These are :

1.  Simple Inheritance : In simple inheritance there is one base class and a single child class which extends the properties of base class.

     2. Multilevel Inheritance : In multilevel inheritance there is single parent and a child class and a further sub child class which inherit properties of child class.

Hierarchical Inheritance : In this type of inheritance many child classes inherit the properties of the same child class like the example used in this blog post.


Note : Multiple Inheritance in which a class inherits properties of more than one class is not present in Java to remove the ambiguity in the code.

Read more

Thursday 4 September 2014

Alert Dialog Tutorial in Android



Alert Dialog :


Alert Dialog is used to display a pop up or dialog in the Activity. It is generally used to ask question from a user with the help of popup dialog at certain event.




Creating an Alert Dialog is very easy in Android with the use of AlertDialog class.

Create a new project in Eclipse : File => New => Android Application Project and give a package name as com.javalanguageprogramming.alertdialogdemo.

Copy the code of activity_main.xml file as shown below :

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   >  
   
   <Button  
     android:id="@+id/alertButton"  
     android:layout_width="200dp"  
     android:layout_height="wrap_content"  
     android:text="Get Alert Dialog"   
     android:layout_gravity="center"  
     android:layout_marginLeft="50dp"  
     />  
   
 </LinearLayout>  
   


In this file we are creating a button which show a dialog when clicked and ask from user that you want to exit from application or not.

Copy the code of MainActivity.java as shown below :

 package com.javalanguageprogramming.alertdialogdemo;  
   
 import android.app.Activity;  
 import android.app.AlertDialog;  
 import android.app.AlertDialog.Builder;  
 import android.content.DialogInterface;  
 import android.content.DialogInterface.OnClickListener;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.Toast;  
   
   
 public class MainActivity extends Activity {  
   
      Button alertButton;  
      Builder dialog;  
   
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
   
           // initialize button variable  
           alertButton = (Button) findViewById(R.id.alertButton);  
   
           // initialize alert dialog  
           dialog = new AlertDialog.Builder(MainActivity.this);  
             
           //if button is clicked than set the alert dialog.  
           alertButton.setOnClickListener(new View.OnClickListener() {  
                  
                @Override  
                public void onClick(View v) {  
                     // call the alertDialogSetup method when button is clicked  
                     alertDialogSetup();  
                       
                }  
           });  
   
      }  
   
      private void alertDialogSetup() {  
           // set a title  
           dialog.setTitle("Exit Application");  
   
           // set a message  
           dialog.setMessage("Are you sure?");  
   
           // set positive button with OnClickListener for positive response  
           dialog.setPositiveButton("Yes", new OnClickListener() {  
   
                @Override  
                public void onClick(DialogInterface dialog, int which) {  
                     // Exit application when user click on yes  
                     System.exit(0);  
   
                }  
           });  
             
           // set negative button with OnClickListener for negative response  
           dialog.setNegativeButton("NO", new OnClickListener() {  
                  
                @Override  
                public void onClick(DialogInterface dialog, int which) {  
                     //cancel the dialog on negative button with the use of DialogInterface reference  
                     dialog.cancel();  
                       
                }  
           });  
             
           //there is one more button in alert dialog in the center called neutral button  
           dialog.setNeutralButton("Neutral", new OnClickListener() {  
                  
                @Override  
                public void onClick(DialogInterface dialog, int which) {  
                     // make a toast that neutral button is clicked  
                     Toast.makeText(MainActivity.this, "Neutral button is clicked", Toast.LENGTH_LONG).show();  
                       
                }  
           });  
             
           //you can use image with the text in the dialog  
           dialog.setIcon(R.drawable.ic_launcher);  
             
           // Now show the dialog on the activity  
           dialog.show();  
      }  
 }  
   


In this Activity, we are creating three buttons (Positive => Yes, Negative => No, Neutral => Cancel) in the dialog. You can create single button or two buttons dialog.
Read more

Wednesday 3 September 2014

Concept of Encapsulation in Java



Concept of Encapsulation in Java :

Encapsulation is one of the Object Oriented Programming fundamental means wrapping (encapsulating) up of data or fields in a single method, make each field private (access specifier) and give the access of method to users (by making the method public) and in this way we can save each field from outside world.

If we provide each single data to outside world than anyone can change its values which will result in breaching of security.

Encapsulation is sometimes called Data Hiding that means we hide single field and provide the method to user for accessing that data or field.

To understand encapsulation see the diagram shown below :



Why we need Encapsulation :

Encapsulation is needed to restrict the access of raw data to outside world. To understand this statement, let’s take an example :

Suppose I have a bank account which is maintained on a software system and if I want to do a transaction than I can directly access all the variables relating to the account.

Let’s say there is a field, myBalance of integer type which is public. Now I can change or access its value by the object of Account class.

Now, consider the case when I withdraw some cash from my account, say 500 than I have to change the value of myBalance by decreasing the amount by 500 by this statement :

 obj.myBalance = myBalance – 500;  
 // where obj is an object of type Account.  


If I can directly access this variable than rather subtracting this amount, I can add double of that amount to myBalance or even add any balance that I want by the use of below statement :

 obj.myBalance = myBalance + 1000;  
   


That means I can freely change my balance which results in big loss to banks and here the concept of Encapsulation comes into the picture.

Through the use of encapsulation we can provide debit method to user and credit method to user for withdrawing cash and crediting cash respectively in account and also make the variable myBalance private.

For e.g.

 private int myBalance;  
   
 public int debitCash(int cash)  
 {  
      myBalance = myBalance – cash;  
      return myBalance;  
 }  
   
 public int creditCash(int cash)  
 {  
      myBalance = myBalance + cash;  
      return myBalance;  
 }  
   

I hope you guys are clear that why we use encapsulation.
Read more