Tuesday, 16 October 2012

how smart is your android smart phone

1.0 Introduction Mobile phones are no longer devices restricted to making voice calls they can run most of the processes that one expects from a desktop computer. Mobile phones are equipped with applications such as e-mail clients, chat clients, short messaging service (SMS), and multimedia messaging service (MMS). Most smartphones are equipped with cameras so that one can have personal pictures and videos on the phone. Communication between two mobile devices is no longer limited to the services of a GSM provider. One can have two mobile phones communicate with the help of Bluetooth, external media cards, or the Internet. Thanks to the efforts of the World Wide Web Consortium (W3C) and Open Mobile Alliance (OMA), being away from one’s laptop does not mean being disconnected from the rest of the Internet world The first mobile phone virus, Cabir, was created in 2004 and targeted for Symbian OSbased phones. This virus replicated itself on Bluetooth wireless networks [1]. Since then, there have been many similar versions of the virus and a few new ones. However, the number of mobile phone viruses is significantly fewer than computer viruses. One major difference between PC and mobile phone viruses has been that it is more difficult for mobile virus infections to spread as fast as computer viruses can. This is due to thevariety of

Saturday, 1 September 2012

how to count selected word from a sentence in java?


how to count selected word from a sentence in java?

 

Output:

 

java contents  3 times.

 

package com.swain.cell;

 

import java.util.HashMap;

import java.util.StringTokenizer;

 

public class DuplicateString {

 

       /**

        * @param args

        */

       public static void main(String[] args) {

              // TODO Auto-generated method stub

 

        String str = "java java android android java example";

        String selectedword="java";

        

        StringTokenizer t = new StringTokenizer(str);

        HashMap<String,Integer> hms=new HashMap<String,Integer>();

       

              while(t.hasMoreTokens())

              {

                    

                     String word = t.nextToken();

                      hms.put(word,(hms.get(word)==null?1:hms.get(word)+1));

             

              }

              System.out.println(selectedword+" contents  " + hms.get(selectedword)+ " times.");

       

   

       }

 

}

Why Prepared Statements are important and how to use them "properly"


Databases have a tough job. They accept SQL queries from many clients concurrently and execute the queries as efficiently as possible against the data. Processing statements can be an expensive operation but databases are now written in such a way so that this overhead is minimized. However, these optimizations need assistance from the application developers if we are to capitalize on them. This article shows you how the correct use of PreparedStatements can significantly help a database perform these optimizations.

How does a database execute a statement?


Obviously, don't expect alot of detail here; we'll only examine the aspects important to this article. When a database receives a statement, the database engine first parses the statement and looks for syntax errors. Once the statement is parsed, the database needs to figure out the most efficient way to execute the statement. This can be computationally quite expensive. The database checks what indexes, if any, can help, or whether it should do a full read of all rows in a table. Databases use statistics on the data to figure out what is the best way. Once the query plan is created then it can be executed by the database engine.
It takes CPU power to do the access plan generation. Ideally, if we send the same statement to the database twice, then we'd like the database to reuse the access plan for the first statement. This uses less CPU than if it regenerated the plan a second time.

Statement Caches


Databases are tuned to do statement caches. They usually include some kind of statement cache. This cache uses the statement itself as a key and the access plan is stored in the cache with the corresponding statement. This allows the database engine to reuse the plans for statements that have been executed previously. For example, if we sent the database a statement such as "select a,b from t where c = 2", then the computed access plan is cached. If we send the same statement later, the database can reuse the previous access plan, thus saving us CPU power.
Note however, that the entire statement is the key. For example, if we later sent the statement "select a,b from t where c = 3", it would not find an access plan. This is because the "c=3" is different from the cached plan "c=2". So, for example:
For(int I = 0; I < 1000; ++I)
{
        PreparedStatement ps = conn.prepareStatement("select a,b from t where c = " + I);
        ResultSet rs = Ps.executeQuery();
        Rs.close();
        Ps.close();
}
Here the cache won't be used. Each iteration of the loop sends a different SQL statement to the database. A new access plan is computed for each iteration and we're basically throwing CPU cycles away using this approach. However, look at the next snippet:
PreparedStatement ps = conn.prepareStatement("select a,b from t where c = ?");
For(int I = 0; I < 1000; ++I)
{
        ps.setInt(1, I);
        ResultSet rs = ps.executeQuery();
        Rs.close();
}
ps.close();
Here it will be much more efficient. The statement sent to the database is parameterized using the '?' marker in the sql. This means every iteration is sending the same statement to the database with different parameters for the "c=?" part. This allows the database to reuse the access plans for the statement and makes the program execute more efficiently inside the database. This basically let's your application run faster or makes more CPU available to users of the database.

PreparedStatements and J2EE servers


Things can get more complicated when we use a J2EE server. Normally, a prepared statement is associated with a single database connection. When the connection is closed, the preparedstatement is discarded. Normally, a fat client application would get a database connection and then hold it for its lifetime. It would also create all prepared statements eagerly or lazilyEagerly means that they are all created at once when the application starts. Lazily means that they are created as they are used. An eager approach gives a delay when the application starts but once it starts then it performs optimally. A lazy approach gives a fast start but as the application runs, the prepared statements are created when they are first used by the application. This gives an uneven performance until all statements are prepared but the application eventually settles and runs as fast as the eager application. Which is best depends on whether you need a fast start or even performance.
The problem with a J2EE application is that it can't work like this. It only keeps a connection for the duration of the request. This means that it must create the prepared statements every time the request is executed. This is not as efficient as the fat client approach where the prepared statements are created once, rather than on every request. J2EE vendors have noticed this and designed connection pooling to avoid this performance disadvantage.
When the J2EE server gives your application a connection, it isn't giving you the actual connection; you're getting a wrapper. You can verify this by looking at the name of the class for the connection you are given. It won't be a database JDBC connection, it'll be a class created by your application server. Normally, if you called close on a connection then the jdbc driver closes the connection. We want the connection to be returned to the pool when close is called by a J2EE application. We do this by making a proxy jdbc connection class that looks like a real connection. It has a reference to the actual connection. When we invoke any method on the connection then the proxy forwards the call to the real connection. But, when we call methods such as close instead of calling close on the real connection, it simply returns the connection to the connection pool and then marks the proxy connection as invalid so that if it is used again by the application we'll get an exception.
Wrapping is very useful as it also helps J2EE application server implementers to add support for prepared statements in a sensible way. When an application calls Connection.prepareStatement, it is returned a PreparedStatement object by the driver. The application then keeps the handle while it has the connection and closes it before it closes the connection when the request finishes. However, after the connection is returned to the pool and later reused by the same, or another application, , then ideally, we want the same PreparedStatement to be returned to the application.

J2EE PreparedStatement Cache


J2EE PreparedStatement Cache is implemented using a cache inside the J2EE server connection pool manager. The J2EE server keeps a list of prepared statements for each database connection in the pool. When an application calls prepareStatement on a connection, the application server checks if that statement was previously prepared. If it was, the PreparedStatement object will be in the cache and this will be returned to the application. If not, the call is passed to the jdbc driver and the query/preparedstatement object is added in that connections cache.
We need a cache per connection because that's the way jdbc drivers work. Any preparedstatements returned are specific to that connection.
If we want to take advantage of this cache, the same rules apply as before. We need to use parameterized queries so that they will match ones already prepared in the cache. Most application servers will allow you to tune the size of this prepared statement cache.

Name the different types of Statements? How we can you use PreparedStatement.


The different types of Statements are

• Regular statement (uses createStatement method)
• prepared statement (uses prepareStatement method) 
• callable statement (uses prepareCall)


PreparedStatement :

• PreparedStatement is derived from the class Statement.

• To execute a Statement object several times a PreparedStatement object is required.

• The PreparedStatement object contains not only a compiled SQL statement, but also a precompiled SQL statement too. 

Code: 

PreparedStatement updateSales =con.prepareStatement("UPDATE account = ? WHERE CON_NAME ?");

How can we retrieve data from the ResultSet?


• JDBC returns back the results in a ResultSet object. 

• So we have to declare an instance of the class ResultSet to keep the results.

• The following code declares the ResultSet object rs.

ResultSet rs = stmt.executeQuery (”SELECT COF_NAME, PRICE FROM COFFEES”);
String s = rs.getString (”NAME”);

• The method getString calls ResultSet object rs, So getString() retrieves the value stored in the column NAME in the row Ssrs.

How JDBC Statements are used?


• A Statement is an object, by which we send an SQL statement to the DBMS. 

• We create a Statement object and then execute it.

• For a SELECT Statement, the method used is executeQuery. 

• The Statement that creates or modifies a table is executeUpdate.

• For creating a Statement object an instance of an active connection is required.

• In the following code, we use our Connection object con to create the Statement object

Statement stmt = con . createStatement();

Differentiate between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE.


• We will get a scrollable ResultSet object if we specify either one of the ResultSet constants.

• The difference between the two depends on, whether a resultset is showing fv changes or not.

• This difference depends on certain methods which are called to detect changes or not. 

• The resultset TYPE_SCROLL_INSENSITIVE does not show the change to it but the ResultSet srs = TYPE_SCROLL_SENSITIVE will show the change. 


The following code explains the difference :

Statement stmt =

con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet srs =

stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

srs.afterLast();

while (srs.previous())
{

String name = srs.getString("COF_NAME");
float price 1= srs.getFloat("PRICE");
System.out.println(name + " " + price1);

}

What are the utilities of the callable statements?


• Callable statements are mainly used in the JDBC applications.

• Callable statements are used to invoke stored procedures

• This is mainly used in functions.

Explain how to Make Updates to the Updatable ResultSets.


• The JDBC 2.0 API can update rows in a ResultSet using the methods in the Java rather than using a SQL command. 

• But before doing that, we create a ResultSet object which is updatable. 

• For doing this, we give the ResultSet CONCUR_UPDATABLE in the createStatement method.

Code:
Connection con =
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =
stmt.executeQuery("SELECT COF_NAME, PRICE ");

Name the types of JDBC drivers.


The four types of drivers defined by JDBC are:

• Type 1: JDBC/ODBC—This requires an ODBC (Open Database Connectivity) driver for the databases to be installed. This type of drivers work by converting the submitted queries into an equivalent ODBC queries and forwarding them via native API which invokes directly to the ODBC driver. It provides host less redirection capability too.

• Type 2: Native type API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API for interacting with the database. An example of such an API is Oracle OCI (Oracle Call Interface). 

• Type 3: Open Net Protocol —This is vendor non-specific and works by forwarding database requests using a net server component. The net server accesses the database. The client driver connects with the server using a database-indifferent protocol and the server translates this protocol into database calls. 

• Type 4: Proprietary Protocol-Net(pure Java driver)—This is same as per configuration as type 3 driver while it uses a wire protocol directed towards a particular vendor and so it can access only that vendor's database.

How do I find whether a parameter exists in the request object?


• The following code implies it

boolean hasFo = !(request.getParameter("fo") == null

|| request.getParameter("fo").equals("")); 


Or

boolean hasParameter =

request.getParameterMap().contains(theParameter);

What are the factors that the JDBC driver performance depends on?


The JDBC driver performance depends on:

• The driver code quality 

• The driver code size 

• The database server & its load capability

• The network topology

• The number of times the request is being translated to a different API.

How can you make a connection?


• To establish a connection we need to have an appropriate driver, connected to the DBMS.

• The below line of code illustrates the idea:

Code:

String url = “jdbc:odbc: rima”;

Connection con = DriverManager.getConnection(url, “rima”, “J8?);

What Class.forName does, while loading the drivers?


• It is used for creating an instance of a driver 

• It is used for registering with theDriverManager.

• When we have loaded a driver, it connects with the DBMS.

How do we load the drivers?


• To Load the driver or drivers we need to use a very simple one line of code. 

• If we want to use the JDBC/ODBC Bridge driver, the following code will load it:

Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);

• The driver documentation gives the class name to use. 

• For example, if the class name is jdbc.DriverXYZ, we can load the driver using the below line of code:

Code:

Class.forName(”jdbc.DriverXYZ”);

How can we move the cursor in a scrollable result set?


• The new features added in the JDBC 2.0 API are able to move a resultset’s cursor backward & forward also.

• There are some methods that let you direct the cursor to a particular row and checking the position of the cursor.

Code :

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 

ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery(”SELECT COF_NAME, Sale _COFFEE”);

• Three constants can be added to the ResultSet API for indicating the kind 

of the ResultSet object. The constants are:

- TYPE_FORWARD_ONLY

- TYPE_SCROLL_INSENSITIVE

- TYPE_SCROLL_SENSITIVE. 

• The ResultSet constants for specifying whether a resultset is read-only or updatable are:

- CONCUR_READ_ONLY

- CONCUR_UPDATABLE.

Explain the types of JDBC Drivers and name them.


The 4 types of JDBC Drivers are:

• Pure Java Driver JDBC Net

• Bridge Driver JDBC-ODBC 

• Network protocol Driver

• Partly Java Driver Native API

. What is SQLWarning and discuss the procedure of retrieving warnings?


• SQLWarning objects, a subclass of SQLException is responsible for the database access warnings.

• Warnings will not stop the execution of an specific application, as exceptions do.

• It simply alerts the user that something did not happen as planned. 

• A warning may be reported on the Connection object, the Statement object (including PreparedStatement and CallableStatement objects) or on the ResultSet object.

• Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object:

Code :
SQLWarning waring = stmt.getWarnings();
if (warning != null)
{
System.out.println("n---Warning---n");
while (warning != null)
{
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.println("Vendor error code: ");
System.out.println(warning.getErrorCode());
System.out.println("");
warning = warning.getNextWarning();
}
}

How do we call a stored procedure from JDBC?


• The foremost step is to create a CallableStatement object. 

• With the Statement and PreparedStatement object ,it is done with an open
Connection object. 

• A CallableStatement object contains a call to a stored procedure.

Code:

CallableStatement cs = con.prepareCall("{call SHOW_Sales}");
ResultSet rs = cs.executeQuery();

How do we call a stored procedure from JDBC?


• The foremost step is to create a CallableStatement object. 

• With the Statement and PreparedStatement object ,it is done with an open
Connection object. 

• A CallableStatement object contains a call to a stored procedure.

Code:

CallableStatement cs = con.prepareCall("{call SHOW_Sales}");
ResultSet rs = cs.executeQuery();


or


• PL/SQL stored procedures are called from the JDBC programs by creating the prepareCall() in the Connection object. 

• A call to the method prepareCall() carries out variable bind parameters as input parameters, output variables & makes an object instance of the CallableStatement class.

• The following line of code implies this:

Callable Statement stproc_ stmt = conn.prepareCall("{call procname(?,?,?)}");

where conn is the instance of the Connection class.

What is the function of setAutoCommit?


• When a connection is created, it is in auto-commit mode.

• This means that each individual SQL statement is to be treated as a single transaction .

• The setAutoCommit will be automatically committed just after getting executed. 

• The way by which two or more statements are clubbed into a transaction to disable the auto-commit mode is :

con.setAutoCommit (false);

• Once auto-commit mode is disabled, no SQL statements will be committed until we call the method ‘commit’ explicitly.

Code :

con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEE SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

Differentiate between a Statement and a PreparedStatement.


• A standard Statement is used for creating a Java representation for a literal SQL statement and for executing it on the database. 

• A PreparedStatement is a precompiled Statement. 

• A Statement has to verify its metadata in the database every time. 

• But ,the prepared statement has to verify its metadata in the database only once.

• If we execute the SQL statement, it will go to the STATEMENT. 

• But, if we want to execute a single SQL statement for the multiple number of times, it’ll go to the PreparedStatement.

Define PreparedStatement.


• A Preparedstatement is an SQL statement which is precompiled by the database.

• By precompilation, the prepared statements improve the performance of the SQL commands that are executed multiple times (given that the database supports prepared statements). 

• After compilation, prepared statements may be customized before every execution by the alteration of predefined SQL parameters.

Code:

PreparedStatement pstmt = conn.prepareStatement("UPDATE data= ? WHERE vl = ?");
pstmt.setBigDecimal(1, 1200.00);
pstmt.setInt(2, 192);

What is a Statement ?


• The Statement acts just like a vehicle via which SQL commands are sent.

• By the connection objects, we create the Statement kind of objects.

Statement stmt = conn.createStatement();

• This method returns the object, which implements the Statement interface.

What is represented by the connection object?


• The connection object represents the communication context.

• All the communication with the database is executed via the connection objects only.

• Connection objects are used as the main linking elements.

What does the JDBC Driver interface do?


• The JDBC Driver interface provides vendor-specific customized implementations of the abstract classes. 

• It is provided normally by the JDBC API. 

• For each vendor the driver provides implementations of the java.sql.Connection,
, PreparedStatement, Driver,Statement, ResultSet and CallableStatement.

How a database driver can be loaded with JDBC 4.0 / Java 6?


• By providing the JAR file , the driver must be properly configured.

• The JAR file is placed in the classpath. 

• It is not necessary to explicitly load the JDBC drivers by using the code like Class.forName() to register in the JDBC driver.

• The DriverManager class looks after this, via locating a suitable driver at the time when the DriverManager.getConnection() method is called. 

• This feature provides backward-compatibility, so no change is needed in the existing JDBC code.

Describe how the JDBC application works


A JDBC application may be divided into two layers:

• Driver layer

• Application layer

• The Driver layer consists of DriverManager class & the JDBC drivers.

• The Application layer begins after putting a request to the DriverManager for the connection.

• An appropriate driver is chosen and used for establishing the connection. 

• This connection is linked to the application layer.

• The application needs the connection for creating the Statement kind of objects by which the results are obtained.

Explain the life cycle of JDBC


The life cycle for a servlet comprises of the following phases:



• DriverManager : for managing a list of database drivers. 

• Driver : for communicating with the database. 

• Connection : for interfacing with all the methods for connecting a database.

• Statement : for encapsulating an SQL statement for passing to the database which had been parsed, compiled, planned and executed.

• ResultSet: for representing a set of rows retrieved for the query execution.


See Example Here:

http://java91.blogspot.in/2015/01/mysql-and-java-jdbc-connection-to.html

Briefly tell about the JDBC Architecture


The JDBC Architecture consists of two layers:

1.The JDBC API
2.The JDBC Driver API

• The JDBC API provides the application-JDBC Manager connection.

• The JDBC Driver API supports the JDBC Manager-to-Driver Connection.

• The JDBC API interacts with a driver manager, database-specific driver for providing transparent connectivity for the heterogeneous databases. 

• The JDBC driver manager authenticates that the correct driver has been used to access each data source.

• The driver manager supports multiple concurrent drivers connected to the multiple heterogeneous databases.

How do Java applications access the database using JDBC?


Java applications access the database using JDBC by : 

• Communicating with the database for Loading the RDBMS specific JDBC driver 

• Opening the connection with database 

• Sending the SQL statements and get the results back.

• Creating JDBC Statement object which contains SQL query.

• Executing statement to return the resultset(s) containing the tuples of database table which is a result of SQL query.

• Processing the result set.

• Closing the connection.

Name the new features added in JDBC 4.0.


The major features introduced in JDBC 4.0 are :

• Auto-loading by JDBC driver class. 

• Enhanced Connection management 

• RowId SQL enabled. 

• DataSet implemented by SQL by using Annotations

• Enhancements of SQL exception handling 

• Supporting SQL XML files.

Discuss the significances of JDBC.


The significances are given below:

• JDBC is the acronym stands for Java Database Connectivity.

• Java Database Connectivity (JDBC) is a standard Java API .

• It's purpose is to interact with the relational databases in Java. 

• JDBC is having a set of classes & interfaces which can be used from any Java application. 

• By using the Database Specific JDBC drivers, it interacts with a database without the applications of RDBMS.

How to send data one jsp page to another jsp page


Index.jsp


<%--
    Document   : index
    Created on : 21 Aug, 2012, 11:53:21 PM
    Author     : Himanshu
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
           <form action="sucess.jsp" method="get">
              Name :  <input type="text" name="name"><br>
            Age :  <input type="text" name="age"><br>
             Dob :   <input type="text" name="dob"><br>
                <input type="submit">

            </form>

        </table>
    </body>
</html>

sucess.jsp
<%--
    Document   : sucess
    Created on : 22 Aug, 2012, 12:35:55 AM
    Author     : Himanshu
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <% String name=request.getParameter("name");%>
        <h1>Name : <%=name%></h1>
         <% String age=request.getParameter("age");%>
        <h1>Name : <%=age%></h1>
         <% String dob=request.getParameter("dob");%>
        <h1>Name : <%=dob%></h1>

    </body>
</html>

for loop in jsp



<%--
    Document   : index
    Created on : 21 Aug, 2012, 11:53:21 PM
    Author     : himanshu
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%for(int i=0;i<10;i++){%>
        <h4><%=i+"->"%>Hello World!</h4>
        <%}%>
       
    </body>
</html>

Prime Numbers java program


Prime Numbers
Output
prime numbers are:
2
3
5
7
11

 Source code
Prime.java

package com.swain.cell;

public class Prime {
      
        public static void main(String args[])
          {
             int n, status = 1, num = 3;
               n=5;
             if ( n >= 1 )
             {
                System.out.println("prime numbers are: ");
                System.out.println(2);
             }
        
             for ( int count = 2 ; count <=n ;  )
             {
                for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
                {
                   if ( num%j == 0 )
                   {
                      status = 0;
                      break;
                   }
                }
                if ( status != 0 )
                {
                   System.out.println(num);
                   count++;
                }
                status = 1;
                num++;
             }        
          }

}



Factorial java program


Factorial
Output
Factorial of 5 is = 120
Source code
Factorial.java

package com.swain.cell;

public class Factorial {
      
       public static void main(String args[])
          {
             int n, c, fact = 1;
        
             n=5;
             if ( n < 0 )
                System.out.println("Number should be non-negative.");
             else
             {
                for ( c = 1 ; c <= n ; c++ )
                   fact = fact*c;
        
                System.out.println("Factorial of "+n+" is = "+fact);
             }
          }

}

String Palindrome java program


Output
Himanshu is not a palindrome.
Source code
StringPalindrome.java

package com.swain.cell;

public class StringPalindrome {
       public static void main(String args[])
          {
             String original="Himanshu";
             String rev="";
                      
             int length = original.length();
        
             for ( int i = length - 1 ; i >= 0 ; i-- )
                rev = rev + original.charAt(i);
        
             if (original.equals(rev))
                System.out.println(original+" is a palindrome.");
             else
                System.out.println(original+" is not a palindrome.");
        
          }
}


Palindrome java program


Palindrome
Output
Number is palindrome!

Source code
Palindrome.java

package com.swain.cell;

public class Palindrome {

       public static void main(String [] args){
                try{
               
                int num= 161;
                int n = num;
                int rev=0;
                for (int i=0; i<=num; i++){
                int r=num%10;
                num=num/10;
                rev=rev*10+r;
                i=0;
                }
                 if(n == rev){
                System.out.print("Number is palindrome!");
                }
                else{
                System.out.println("Number is not palindrome!");
                }
                }
                catch(Exception e){
                System.out.println("Error");
                }
                }
}