Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts
Send SMS Through JAVA/JSP/ SERVLETS

Send SMS Through JAVA/JSP/ SERVLETS

Hi, Friends with this post i will show to how to send an sms through JAVA/JSP/SERVLETS

For sending sms I am using mvayoo.

First what is mVaayoo, It  is a cost effective End-to-End Enterprise Mobile Messaging Service with high service level availability, that is unmatched in the industry. mVaayoo provides both 1-Way & 2-Way SMS communication including SMS Push, short code and long code services, SMS gateway with APIs, SMS Excel plugin, SMS contest, voting & polling and Voice SMS services.

URL : http://www.mvayoo.com


You first register in this website and continue your tutorial ...
 
------------------------------------------------------------------------------------------------------------
Note  : We can send only 20 sms with the free account... If you want more choose the premium plan or register with another account.

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

coming to the program...;


import java.io.*;
import java.security.*;

import java.net.*;

public class SMS  //Save the file with the name "SMS.java"
{
    public static void main(String[] args)
    {
        String phnum= "9292929292";   // Example Phone Number
        String message = "Hai, How are you ..."; //Example Message
        try{ 



//http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=USERNAME:PASSWORD&senderID=TEST SMS&receipientno=RECEIPIENTNO&dcs=0&msgtxt=This is Test message&state=4              

   URL myurl = new URL("http://api.mvaayoo.com/mvaayooapi/MessageCompose?user=USERNAME:PASSWORD&senderID=TEST%20SMS&receipientno="+phnum+"&dcs=0&msgtxt="+message+"");
 
  BufferedReader in = new BufferedReader(new InputStreamReader(myurl.openStream())); 
  String inputLine;

 while ((inputLine = in.readLine())!= null)
          System.out.println(inputLine);


in.close();
}
catch(Exception e){
            System.out.println("error"+e);


}
 

}

}

OUTPUT :

Hai, How are you ...

Status=0,ins37_14066345089954

Observe the output, in output "Hai, How are you ..." is our message and the second line is for status indication if your message is send successful it shows the output like "Status=0", Other wise it will not send ..


------------------------------------------------------------------------------------------------------------
NOTE : INTERNET Connection must required for sending an sms ...


------------------------------------------------------------------------------------------------------------
Retrieval Image From DataBase and Display on WebPage by Using Servlets.

Retrieval Image From DataBase and Display on WebPage by Using Servlets.

Hi Frnds, This Session I will Explain you to "How Retrive Image from DataBase Using Servlets and Display it on WebPage"

The below code is useful for Retrive Image from DataBase Using Servlets and Display it on WebPage.

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;

@WebServlet("/ImageDis")

public class ImageDis extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response)  throws IOException,ServletException
{
 response.setContentType("image/jpeg");

Blob image = null;
Connection con = null;
byte[ ] imgData = null ;
Statement stmt = null;
ResultSet rs = null;

try {

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DbName","UserName","Password");
stmt = con.createStatement();
// Retrieve Image from DataBase using MySQL Query Based on Condition...;
rs = stmt.executeQuery("select imge from empde where id='12'");

if (rs.next()) {
                               //Getting Image From DataBase...;
image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());

} else {
System.out.println("Display Blob Example");
System.out.println("image not found for given id>");

}
// display the image...;

ServletOutputStream out1 = response.getOutputStream();
BufferedOutputStream bout = new BufferedOutputStream(out1);
   
bout.write(imgData);

} catch (Exception e) {
System.out.println("Unable To Display image");
System.out.println("Image Display Error=" + e.getMessage());
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Check the OutPut If you have any Doubts Leave your Comments Below...;

Have a Gr8 Day Frnds...;)

Displaying Text directly beside an image


Hi, Today i wanna show you how to Displaying Text With An Image Within HTML Code...;

If you're trying to place text directly beside an image within your web page HTML code, you may have discovered it's not as easy as it appears. When you place your image HTML code and text within your HTML code, instead of the text and image displaying side by side like a newspaper, it will display like this:


To enable your image and text to display properly together, you will need to add an ALIGN attribute to your image HTML code.

Following is an example image displaying on the left with the text wrapping around the image to the right.

To align your image to left and your text to the right, add ALIGN="left" to your image HTML code like this:

<img border="0" align="left" src="image.jpg"> Hai Frnds,How are You


Following is an example image displaying on the right with the text wrapping around the image to the left.

To align your image to right and your text to the left, add ALIGN="right" to your image HTML code like this:

<img border="0" align="Right" src="image.jpg"> Hai Frnds,How are you



Wrapping your text around your image will enable you to give your content a much more professional look.

Source : http://www.web-source.net/

Try It...,

Have a nice-day...;
JavaScript to Start and Stop the Time

JavaScript to Start and Stop the Time

Hi Frnds, I waana Show you how to Start and Stop the Time Using JavaScript...;

The Below Code is used to Start and Stop the Time Using JavaScript

<!DOCTYPE html>
<html>
<body>

<p>A script on this page Starts and Stops clock:</p>

<p id="demo"></p>

<div>
<form><input type = "submit" value = "Start Time" style = "float:left"></form>

<input type = "submit" value = "Stop Time" style = "margin-left:10px" onclick="myStopFunction()" ></div>

<script>
var myVar = setInterval(function(){ myTimer() }, 1000);

function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
clearInterval(myVar);
}
</script>

</body>
</html>

Observe carefully this code

<p id = “demo”></p>
var myVar = setInterval(function(){ myTimer() }, 1000);

function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}

This code is used to display the Current System time, when page is loaded.

<input type = "submit" value = "Stop Time" style = "margin-left:10px" onclick="myStopFunction()" >

function myStopFunction() {
clearInterval(myVar);

When we click the “Stop Time” Button, the myStopFunction() is called. It Stops the Time.

<form><input type = "submit" value = "Start Time" style = "float:left"></form>

When we click the “Start Time” Button, the Page will refresh so the time will start again.

Try it...,


Have Nice Day...;

TIRE Architectures.

Three-tier or multi-tier architecture is often used when describing how clients connect to database servers. But what does it all mean?

Let me try to explain this in non-technical terms (or as close to it I can get).

Software

Let’s first take a look how a database software program (the software) works.

There are three major tiers to the software:

-User Interface (UI). This is what you see when you work with the software. You interact with it. There  might be buttons, icons, text boxes, radio buttons, etc. The UI passes on clicks and typed information to the Business Logic tier.

-Business Logic (BL). The business logic is code that is executed to accomplish something. When a user clicks a button it will trigger the BL to run some code. The BL can send information back to the UI, so the user can see the result of clicking a button or typing something in a field. For instance when you enter something in a cell in Excel, the BL will recalculate other cells once you hit Enter and the UI will present the new information to you. The BL also needs to be able to store and retrieve data and that is handled in the Database tier.

-Database (DB). The database is where the data is stored and where the BL can retrieve it again.

1-Tier Architecture

This architecture has the UI, the BL, and the DB in one single software package. Software applications like MS Access, MS Excel, QuickBooks, and Peachtree all have the same in common: the application handles all three tiers (BL, UI, and DB). The data is stored in a file on the local computer or a shared drive. This is the simplest and cheapest of all the architectures, but also the least secure. Since users have direct access to the files, they could accidentally move, modify, or even worse, delete the file by accident or on purpose. There is also usually an issue when multiple users access the same file at the same time: In many cases only one can edit the file while others only have read-only access.

Another issue is that 1-tier software packages are not very scalable and if the amount to data gets too big, the software may be very slow or stop working.

So 1-tier architecture is simple and cheap, but usually unsecured and data can easily be lost if you are not careful.




2-Tier Architecture

This architecture is also called Client-Server architecture because of the two components: The client that runs the application and the server that handles the database back-end. The client handles the UI and the BL and the server handles the DB. When the client starts, it establishes a connection to the server and communicates as needed with the server while running the client. The client computer usually can’t see the database directly and can only access the data by starting the client. This means that the data on the server is much more secure. Now users are unable to change or delete data unless they have specific user rights to do so.

The client-server solution also allows multiple users to access the database at the same time as long as they are accessing data in different parts of the database. One other huge benefit is that the server is processing data (DB) that allows the client to work on the presentation (UI) and business logic (BL) only. This mean that the client and the server are sharing the workload and by scaling the server to be more powerful than the client, you are usually able to load many clients to the server allowing more users to work on the system at the same time and at a much greater speed.


3-Tier Architecture

In this architecture all three tiers are separated onto different computers. The UI runs on the client (what the user is working with). The BL is running on a separate server, called the business logic tier, middle tier, or service tier. Finally the DB is running on its own database server.

In the client-server solution the client was handling the UI and the BL that makes the client “thick”. A thick client means that it requires heavy traffic with the server, thus making it difficult to use over slower network connections like Internet and Wireless (4G, LTE, or Wi-Fi).

By introducing the middle tier, the client is only handling presentation logic (UI). This means that only little communication is needed between the client and the middle tier (BL) making the client “thin” or “thinner”. An example of a thin client is an Internet browser that allows you to see and provide information fast and almost with no delay.

As more users access the system a three-tier solution is more scalable than the other solution because you can add as many middle tiers (running on each own server) as needed to ensure good performance (N-tier or multiple-tier).

Security is also the best in the three-tier architecture because the middle tier protects the database tier.

There is one major drawback to the N-tier architecture and that is that the additional tiers increase the complexity and cost of the installation.



1-Tier2-TierMulti-Tier
BenefitsVery simple
Inexpensive
No server needed
Good security
More scalable
Faster execution
Exceptional security
Fastest execution
“Thin” client
Very scalable
IssuesPoor security
Multi user issues
More costly
More complex
“Thick” client
Very costly
Very complex
UsersUsually 1 (or a few)2-10050-2000 (+)


Source : http://blog.simcrest.com/
Framework

Framework

A framework, or software framework, is a platform for developing software applications. It provides a foundation on which software developers can build programs for a specific platform. For example, a framework may include predefined classes and functions that can be used to process input, manage hardware devices, and interact with system software. This streamlines the development process since programmers don't need to reinvent the wheel each time they develop a new application.

A framework is similar to an application programming interface (API), though technically a framework includes an API. As the name suggests, a framework serves as a foundation for programming, while an API provides access to the elements supported by the framework. A framework may also include code libraries, a compiler, and other programs used in the software development process.

Several different types of software frameworks exist. Popular examples include ActiveX and .NET for Windows development, Cocoa for Mac OS X, Cocoa Touch for iOS, and the Android Application Framework for Android. Software development kits (SDKs) are available for each of these frameworks and include programming tools designed specifically for the corresponding framework. For example, Apple's Xcode development software includes a Mac OS X SDK designed for writing and compiling applications for the Cocoa framework.

In many cases, a software framework is supported natively by an operating system. For example, a program written for the Android Application Framework will run on an Android device without requiring other additional files to be installed. However, some applications require a specific framework in order to run. For example, a Windows program may require Microsoft .NET Framework 4.0, which is not installed on all Windows machines (especially PCs running older versions of Windows). In this case, the Microsoft .NET Framework 4 installer package must be installed in order for the program to run.

NOTE: While frameworks generally refer to broad software development platforms, the term can also be used to describe a specific framework within a larger programming environment. For example, multiple Java frameworks, such as Spring, ZK, and the Java Collections Framework (JCF) can be used to create Java programs. Additionally, Apple has created several specific frameworks that can be accessed by OS X programs. These frameworks are saved with a .FRAMEWORK file extension and are installed in the /System/Library/Frameworks directory. Examples of OS X frameworks include AddressBook.framework, CoreAudio.framework, CoreText.framework, and QuickTime.framework.

Source : http://techterms.com

Auto Refresh Code In HTML


Auto Refresh Code in HTML using JavaScript, meta tags and JQuery

                There are several ways to refresh the CURRENT WEB page or FRAME or Specific HTML element (any specific Div or Span or any HTML element) after a given time interval, that we can refresh any specific part/element of HTML page without reloading the complete page.

--> Using JavaScript.
--> Using meta tags.
--> Using JQuery.

JavaScript:
             You can refresh a web page using JavaScript location.reloadmethod. This code can be called automatically upon an event or simply when the user clicks on a link.

By Simply click the Refresh link.

                        <a href = "javascript:location.reload(true)">Refresh Page</a>

Refresh the page automatically after a given time period

Try it.

<html>
<head>
<script type="text/JavaScript">

function AutoRefresh() {
setTimeout("location.reload(true);", 1000); // this will reload page after every 1 sec
}

</script>
</head>
<body onload="AutoRefresh();">
<p>This page will refresh every 5 seconds.</p>
</body>
</html>

Note: 1000 = 1 sec, if you want to 5 sec 1000*5 = 5000 ie., 5 sec

meta tags :
            
                 Meta refresh is a method of instructing a web browser to automatically refresh the current web page or frame after a given time interval, using an HTML meta element with the http-equiv parameter set to "refresh" and a content parameter giving the time interval in seconds. It is also possible to instruct the browser to fetch a different URL when the page is refreshed, by including the alternative URL in the content parameter. By setting the refresh time interval to zero (or a very low value), this allows meta refresh to be used as a method of URL redirection.

Examples

Place inside <head> to refresh page after 5 seconds:

<meta http-equiv="refresh" content="5">
Redirect your web Page(Eg: http://example.com/) after 5 seconds:

<meta http-equiv="refresh" content="5; url=http://example.com/">
Redirect to http://example.com/ immediately:

<meta http-equiv="refresh" content="0; url=http://example.com/">

Jquery:

Refresh HTML element (Div/Span) on HTML page after specific time:

In this part we will use JQuery to perform the task, as its provides few of the best options that can help us.

Suppose you have a span with ID as result similar to following:

<span id = “result”></span>

Then the JQuery code will be as follows:

<script>
function autoRefresh_div()
{
$("#result").load("example.html");// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
</script>

Example :

<html>
<head>
<script>
function autoRefresh_div()
{
$("#result").load("example.html");// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
</script>
</head>
<body>
<span id = "result"></span>
</body>
</html>


Display the current time (the setInterval() method will execute the function once every 1 second, just like a digital watch). 

<html>
<body>

<p>A script on this page starts this clock:</p>

<p id="demo"></p>

<script>
var myVar = setInterval(function(){ myTimer() }, 1000);

function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

</script>

</body>
</html>

Sample Output :


Generates Random Integers in a Specific Range

Generates Random Integers in a Specific Range

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {
 
  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");
   
    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }
   
    log("Done.");
  }
 
  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if (aStart > aEnd) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);  
    log("Generated : " + randomNumber);
  }
 
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
}


An example run of this class:
Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
Generates Random Floating Point Numbers

Generates Random Floating Point Numbers

import java.util.Random;

/**
 Generate pseudo-random floating point values, with an
 approximately Gaussian (normal) distribution.

 Many physical measurements have an approximately Gaussian
 distribution; this provides a way of simulating such values.
*/
public final class RandomGaussian {

  public static void main(String... aArgs){
    RandomGaussian gaussian = new RandomGaussian();
    double MEAN = 100.0f;
    double VARIANCE = 5.0f;
    for (int idx = 1; idx <= 10; ++idx){
      log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
    }
  }
 
  private Random fRandom = new Random();

  private double getGaussian(double aMean, double aVariance){
    return aMean + fRandom.nextGaussian() * aVariance;
  }

  private static void log(Object aMsg){
    System.out.println(String.valueOf(aMsg));
  }
}


An example run of this class:
Generated : 99.38221153454624
Generated : 100.95717075067498
Generated : 106.78740794978813
Generated : 105.57315286730545
Generated : 97.35077643206589
Generated : 92.56233774920052
Generated : 98.29311772993057
Generated : 102.04954815575822
Generated : 104.88458607780176
Generated : 97.11126014402141
Generate random numbers

Generate random numbers

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
 
  public static final void main(String... aArgs){
    log("Generating 10 random integers in range 0..99.");
   
    //note a single Random object is reused here
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      int randomInt = randomGenerator.nextInt(100);
      log("Generated : " + randomInt);
    }
   
    log("Done.");
  }
 
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
}

Example run of this class:
Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Done.
Sending Email through Gmail Server Using JavaServlets

Sending Email through Gmail Server Using JavaServlets

import java.io.*;
import java.net.*;

import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

public class SendEmail extends HttpServlet {

 protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
                   throws IOException, ServletException {

        final String err = "/error.jsp";
        //final String succ = "/success.jsp";

        String from = "abc@gmail.com"    // Sender Email-Id
        String to = "xyz@gmail.com"     // Receiver Email-Id

System.out.println("mail : "+to);
        String subject = "Subject";          //Your Subject.
        String message = "Message"    Your Message

        String login = "abc@gmail.com";        //Sender Mail_Id
        String password = "xyx"; //Sender Mail Password

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props,auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
            return;

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
            return;
        } catch (MessagingException ex) {
           request.setAttribute("ErrorMessage", ex.getMessage());
       
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
            return;
        }
            RequestDispatcher dispatcher = request.getRequestDispatcher("/success.jsp?email="+to);
            dispatcher.forward(request, response);
            return;
    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    protected void doPost(HttpServletRequest request,
                         HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }

 
}

Java Date and Time

Java Date and Time

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SimpleDateFormatExample {
public static void main(String[] args) {

Date curDate = new Date();

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

String DateToStr = format.format(curDate);
System.out.println(DateToStr);

format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
DateToStr = format.format(curDate);
System.out.println(DateToStr);

format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
DateToStr = format.format(curDate);
System.out.println(DateToStr);

format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
DateToStr = format.format(curDate);
System.out.println(DateToStr);

try {
Date strToDate = format.parse(DateToStr);
System.out.println(strToDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:

2014/12/19
19-12-2014 04:54:26
19 December 2014 India Standard Time
Fri, 19 Dec 2014 16:54:26 IST
Fri Dec 19 16:54:26 IST 2014


Java Program to print Circular (Spiral) Matrix

Question:

            Write a Program in Java to fill a square matrix of size ‘n*n” in a circular fashion (clockwise) with natural numbers from 1 to n*n, taking ‘n’ as input.

For example: if n = 4, then n*n = 16, hence the array will be filled as given below




Note: This program is also known as Spiral Matrix

Solution:

import java.io.*;


class Circular_Matrix

    {

        public static void main(String args[])throws IOException

        {

            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter the number of elements : ");

            int n=Integer.parseInt(br.readLine());



            int A[][]=new int[n][n];

            int k=1, c1=0, c2=n-1, r1=0, r2=n-1;



            while(k<=n*n)

                {

                    for(int i=c1;i<=c2;i++)

                    {

                        A[r1][i]=k++;

                    }



                    for(int j=r1+1;j<=r2;j++)

                    {

                        A[j][c2]=k++;

                    }



                    for(int i=c2-1;i>=c1;i--)

                    {

                        A[r2][i]=k++;

                    }



                    for(int j=r2-1;j>=r1+1;j--)

                    {

                        A[j][c1]=k++;

                    }



                 c1++;

                 c2--;

                 r1++;

                 r2--;

                }

 

            /* Printing the Circular matrix */

            System.out.println("The Circular Matrix is:");

            for(int i=0;i<n;i++)

                {

                    for(int j=0;j<n;j++)

                        {

                            System.out.print(A[i][j]+ "\t");

                        }

                 System.out.println();

                }

        }

    }

Working:



    
            We will take a variable ‘k’ which will begin with 1 and will do the work of filling. i.e. for every cell, it will increase by 1. The below given processes will repeat till the value of ‘k’ becomes ‘n*n’

C1 denotes the index of the column from where we have to begin. Hence its initial value will be 0.
C2 denotes the index of the column where we have to end. Hence its initial value will be ‘n-1′ (n is the size of the matrix).
R1 denotes the index of the row from where we have to begin. Hence its initial value will be 0.
R2 denotes the index of the row where we have to end. Hence its initial value will be ‘n-1′ (n is the size of the matrix).
The filling up of the matrix in circular fashion will consist of 4 different steps which will continue till the matrix is filled completely.

Step 1: We will fill the elements of Row 0 (R1), starting from Column 0 (C1) till ‘n-1′ (C2). The cells which will be filled are marked in the image above in yellow color.
The elements will be accessed as follows: A[R1][i], where ‘i’ will go from C1 to C2 (A[ ][ ] is the array)

Step 2: Now, we will fill the elements of Column ‘n-1′ (C2), starting from Row R1+1 till R2. The cells which will be filled are marked in the image above in grey color.
The elements will be accessed as follows: A[j][C2], where ‘j’ will go from R1+1 to R2 (A[ ][ ] is the array)

Step 3: Next we will fill the elements of Row ‘n-1′ (R2), starting from Column C2-1 till C1. The cells which will be filled are marked in the image above in green color.
The elements will be accessed as follows: A[R2][i], where ‘i’ will go from C2-1 to C1 (A[ ][ ] is the array)

Step 4: Now, we will fill the elements of Column C1, starting from Row R2-1 till R1+1. The cells which will be filled are marked in the image above in blue color.
The elements will be accessed as follows: A[j][C1], where ‘j’ will go from R2-1 to R1+1 (A[ ][ ] is the array)

The above 4 steps will now repeat with the inner matrix which is marked in white color in the above image. For the inner matrix,
C1 will increase by 1 i.e. it will be C1+1.
C2 will decrease by 1 i.e. it will be C2-1.
R1 will increase by 1 i.e. it will be R1+1.
R2 will decrease by 1 i.e. it will be R2-1.

The above processes will repeat till we have filled in ‘n*n’ values.
  
Output:



Convert Binary TO String Using JAVA.........

Convert Binary TO String Using JAVA.........

Hi Friends This Program Will Demonstrate the Logic of Binary TO String Conversion....

Save The File BinarytoStr.java

import java.math.BigInteger;
class BinarytoStr
{
public static void main(String[] args)
{
String z = "0100100001100101011011000110110001101111";
int len = z.length()/8;
String orgstring = "";
byte[] bval = new BigInteger(z, 2).toByteArray();
for(int t = 0;t<len;t++)
{
char c1 = (char)bval[t];
orgstring = orgstring.concat(String.valueOf(c1));
}
System.out.println("Original String : " + orgstring);
}
}

OUTPUT : 

Original String : Hello



I hope this logic will helpful to all...........
Convert String to Binary AND Binary To String Using Java......

Convert String to Binary AND Binary To String Using Java......

Hi Friends this program will demonstrate the logic for "How To Convert Sting to Binary AND Binary To Original String" 

Save The file Binary.java

class Binary
{
public static void main(String[] args)
{
String msg = "Hello";   //coverted String...

               //conversion of String To Binary.......

byte[] bytes = msg.getBytes();        //getting byte values
StringBuilder binary = new StringBuilder();
int msgg = 0;

for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);

   val <<= 1;

}

}

System.out.println("'" + msg + "' to binary: " + binary);
               
               //Conversion of Binary to Original String..........

                String origmsg = "";

int count = binary.length()/8;
     
char a[]=msg.toCharArray();
                int i=0;
     
for( i=0;i<count;i++)
               {
                    a[i]=msg.charAt(i);
           origmsg = origmsg.concat(String.valueOf(a[i]));
                }

System.out.println("original message : " + origmsg);
}
}


OUTPUT : 

'Hello' to binary: 0100100001100101011011000110110001101111
original message : Hello

I hope this logic will helpful to all...........
String To Binary Conversion using java.....

String To Binary Conversion using java.....

Hi Friends, Here the logic for "String to Binary(8 bit)" conversion

Save the file Binary.java

class Binary
{
public static void main(String[] args)
{
String msg = "Hello";           //coverted String...

byte[] bytes = msg.getBytes();             //getting byte values

StringBuilder binary = new StringBuilder();

int msgg = 0;

for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);

   val <<= 1;

}

}

System.out.println("'" + msg + "' to binary: " + binary);
       }
}

I hope it is usefulll....