Monday, April 21, 2008

Const Array create how?

JAVA Code:
final int array[]={1,2,4};
array[0]=5;
System.out.println(array[0]);

output: 5 // Becoz final keyword will not yield the desired effect, because it will just make the variable not be able to point to another object (like a const pointer) - it will not make the object referred by it constant.


JAVA Code: //to make an constant Array
import java.util.*;
public class Test
{
static Object array[] = {new Integer(1), new Integer(2), new Integer(4)};
public static final List CONST =
Collections.unmodifiableList(Arrays.asList(array));
public static void main(String args[])
{
CONST.set(0, new Integer(5));
System.out.println(CONST.get(0));
}
}
JAVA Code:Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.set(Collections.java:1141)
at Test.main(Test.java:12)

Get num of rows in ResultSet -JDBC

public static void main(String[] args)

{

System.out.println("Count records example using prepared statement!");

Connection con = null;

int records = 0; try{

Class.forName ("com.mysql.jdbc.Driver").newInstance ();

con = DriverManager.getConnection ("jdbc:mysql://localhost/adportal", "root", "admin");

con.setAutoCommit(true);

try{

String sql = "SELECT COUNT(*) FROM postmessage";

PreparedStatement prest = con.prepareStatement(sql);

ResultSet rs = prest.executeQuery();

while (rs.next())

{

records = rs.getInt(1);

}

System.out.println("Number of records: " + records);

con.close(); }

catch (SQLException s){ System.out.println("Table does not exist in the database!");

}

}

catch (Exception e){ e.printStackTrace(); }

}

Return more than one values from a method !!

//returns student first name, last name, age given the ssn
public Map getStudentInfo(String ssn){
String fName = null;
String lName = null;
int age = 0;
Hashtable info = new Hashtable();

//pretend we looked up the information rather than hardcoding it and place
//items in a Hashtable in this case

info.put("FName", "Jean-Luc");
info.put("LName", "Pickard");
info.put("Age", new Integer(52)); //age is of type int; like all primitives, it must be wrapped

//return the object
return info;
}
In the calling method you need to get the items out of the Map and cast to what you needMap stuInfo = getStudentInfo("123-45-6789");
String firstName = (String)stuInfo.get("FName");
String lastName = (String)stuInfo.get("LName");
int stuAge = ((Integer)stuInfo.get("Age")).intValue(); //Get the value of the wrapper object

...