Archive for the ‘Java’ Category

Convert String to Int in Java

Converting a string variable to an integer variable in Java is easy. There are actually two different approaches, both equally simply. Below is an example of both approaches, with both use the same string variable to output to various integer variables.

String myVariable = “12345″;

Approach 1:
int approach1 = Integer.parseInt(myVariable);

Approach 2:
int approach2 = Integer.valueOf(myVariable);

If you have any opinion on why you use one approach over the other, let the community know!

Comparisons in Java

When comparing objects, it is useful to know the difference between  == and the equals() method.

The == comparsion is used to compare the values of two objects to see if they refer to the same object.  Note there are 8 primitives in Java:  boolean, byte, char, double, float, int, long, and short. In the example below, you will see why a String comparison will not work for the == comparison. This is because the == comparison is used as an equality operator to compare two like primitive values.

Ex 1:

if( a == "abc")  // FALSE

Ex 2:

String a = "abc";
String b = "abc";
if(a == b) // FALSE because they are two separate String objects

Ex 3:

int i = 1;
int j = 1;
if( i == j)  // TRUE

The equals() method is used to compare two object values to see if they are identical. This method is not used on primitive values.

For example,

String name = "abc";
if(name.equals("abc")) // TRUE

Using PreparedStatement in Java

PreparedStatements are used in Java to set up SQL statements. They can be used to insert a set of data to the database or retrieve a set of data from the database.  You can visit the Java API here:  http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html

This is how I’ve used the prepared statement to insert data to the database:

First, import the necessary package:

import java.sql.*;

Create the PreparedStatement object:

PreparedStatement pstmt = null;

Create a  String for your SQL statement. For example:

String insert = "INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (?, ?, ?)";

The question marks represent values being passed into the statement.

Create a Connection to the database. Usually the URL, username and password are stored in a config file but for simplicity, the following can be done:

Connection con = DriverManager.getConnection("<URL>", "<username>", "<password>");

The URL is something like “jdbc:odbc:<db>”. Username is the schema name, and password is the password.

Then, in a try/catch block,

try (
  pstmt = con.prepareStatement(insert);
  pstmt.setString(1, valCol1);  //valCol1 is the String value being inserted for COL1 in the table MYTABLE
  pstmt.setString(2, valCo2);
  pstmt.setString(3, valCo3);
  pstmt.executeQuery();  //executeQuery() is the method used to run the SQL statement
  con.commit();  //commit() will commit the data into MYTABLE
} catch (SQLException e){
  error("Error inserting into db " + e.getMessage());
}

To retrieve data from the db is similar:

This time, you will need to create a ResultSet object to store the retrieved data:

ResultSet rs = null;

This is an example:

public String[] getData(Connection con, String col3) {
  String select = "SELECT COL1, COL2 FROM MYTABLE WHERE COL3 = ?";
  PreparedStatement ps = null;
  ResultSet rs = null;
  List<String> dataArray = new ArrayList<String>(); //This will contain the data from the db
  try{
    ps = con.prepareStatement(select);
    ps.setString(1,  col3); // col3 is the value being set in the SQL statement
    rs = ps.executeQuery(); //this will execute the query and store the result in rs
    while(rs.next()) {
      dataArray.add(rs.getString(1));
    }
  } catch(SQLException e) {
    error("Unable to get data " , e);
  }
  ps.close()  //close the prepared statement
  con.close()  //close the connection
}