Thursday, January 22, 2009

Compiling Programmatically

Following example uses the JavaCompiler interface in Java 6 to programmatically compile a Java class:

public class CompilerExample {
public static void main(String[] args) {
String fileToCompile = "test.java"
javax.tools.JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if (compilationResult == 0) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation Failed");
}
}
}

Dive Into Java

Dive into Java
View more presentations or upload your own. (tags: java programming)

Tuesday, January 06, 2009

Reversing a String in Java

The following code shows different methods of reversing a String in Java. The simplest being using the reverse() method of StringBuffer, while the other methods use char array and recursion:

public class StringReverse {<br />	public static void main(String[] args) {<br />		String s = "zyxwvutsrqponmlkjihgfedcba";<br />		System.out.println(charReverse(s));<br />		System.out.println(recursiveReverse(s , new StringBuffer()));<br />		System.out.println(recursiveReverse2(s, new StringBuffer()));<br />		System.out.println(bufferReverse(s));<br />	}<br />	<br />	public static String charReverse(String s) {<br />		char[] cArr = s.toCharArray();<br />		StringBuffer reversed = new StringBuffer();<br />		for(int i=cArr.length-1; i>=0; i--) reversed.append(cArr[i]);<br />		return reversed.toString();<br />	}<br />	<br />	public static String recursiveReverse(String s, StringBuffer t) {<br />		if(s.length() > 0) {<br />			t.append(s.substring(s.length()-1));<br />			recursiveReverse(s.substring(0, s.length()-1), t);<br />		}<br />		return t.toString();<br />	}<br />	<br />	public static String recursiveReverse2(String s, StringBuffer sb) {<br />		if (s.length() == 1){<br />			sb.append(s);<br />		}<br />		else{<br />			recursiveReverse2(s.substring(1, s.length()), sb);  <br />			sb.append(s.substring(0,1));<br />		}<br />		return sb.toString();<br />	}<br />	<br />	public static String bufferReverse(String s) {<br />		StringBuffer sb = new StringBuffer(s);<br />		return sb.reverse().toString();<br />	}<br />}

Monday, January 05, 2009

HSQLDB

HSQLDB is a 100% Java database which is embeddable. It has a small footprint and can be used for self-contained applications. The source files, the JAR file and support documents can be downloaded from hsqldb.org. It also provides a JDBC driver. HSQLDB is perfect for quick implementation and testing.

Following is a sample program which uses the JDBC driver for creating a table, inserting some data in the table and listing the rows from the table:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.PreparedStatement;

public class HSQLTest {
Connection conn;
Statement stmt;
PreparedStatement add_stmt, get_stmt;

static {
try{
Class.forName("org.hsqldb.jdbcDriver").newInstance();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(InstantiationException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
}

HSQLTest() {
try {
initializeDB();
createTable();
populateTable();
displayRows();
}
catch(SQLException e) {
e.printStackTrace();
}
}

void initializeDB() throws SQLException {
conn = DriverManager.getConnection("jdbc:hsqldb:db/test", "sa", "");
stmt = conn.createStatement();
}

public void createTable() throws SQLException {
String table_name = "sample_table";
DatabaseMetaData dbM = conn.getMetaData();
ResultSet rs = dbM.getTables(null, null, "%", null);
boolean found = false;
while(rs.next()) {
String s = rs.getString(3);
//System.out.println(s);
if(s.equalsIgnoreCase(table_name)) {
found = true;
break;
}
}

if(!found) {
String s = "CREATE TABLE " + table_name + "(id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1000) PRIMARY KEY, " +
"category VARCHAR(40), name VARCHAR(40))";
stmt.execute("SET WRITE_DELAY FALSE;");
stmt.executeUpdate(s);
}
}

public void populateTable() throws SQLException {
stmt.executeUpdate("insert into SAMPLE_TABLE (category, name) values ('E0', 'Ben')");
}

public void displayRows() throws SQLException {
ResultSet rs = stmt.executeQuery("SELECT * FROM SAMPLE_TABLE");
int numCols = rs.getMetaData().getColumnCount();
while(rs.next()) {
for(int i=1; i<=numCols; i++) {
System.out.println(rs.getString(i) + ": " + rs.getString(i));
}
}
}

public static void main(String[] args) {
HSQLTest hTest = new HSQLTest();
}
}

Top Java Developers Offer Advice to Students

* Joshua Bloch: Write Lots of Code

* Tor Norbye: Learn to Use Your Tools

* Chet Haase: Don't Put Your Entire Application in One Method

* Ben Galbraith: Interact With an Expert

* Masood Mortazavi: Start Simple and Keep Learning

* Raghavan Srinivas: Don't Be Overwhelmed

* Cay Horstmann: First, Don't Panic

* Arun Gupta: Try Different IDEs

* Rick Cattell: Good Technology Is Only 10% of Success

* Chuk-Munn Lee: Choose an Area of Your Immediate Need

* Tom Ball: Programming Is Still a Craft
 
 

Why A Laptop Is Better Than A Girlfriend!

10- Your Laptop is cool with Whatever Plans you Have for the Night
 
9- A Laptop isn’t all Ticked Off at you Three Days a Month for no Reason
 
8- Your Laptop won’t ask you Why You’re Afraid of Commitment
 
7- You can turn your Laptop on with the Click of a Button
 
6- Your Laptop Doesn’t Get Jealous of your iPhone and your Xbox
 
5- Your Laptop doesn’t make you listen to Sucky Music/Watch Sucky Movies
 
4- Your Laptop Stays the Same Size she was when you got her
 
3- Your Laptop Doesn’t Mind if YOU Put on Some Weight
 
2- If you see your Laptop with Another Guy, you can call the Police
 
1- Your Laptop can run the Newest Games
 
 
(from http://www.geekwithlaptop.com/why-a-laptop-is-better-than-a-girlfriend/)

Friday, January 02, 2009

OOP Principles

In the process-oriented model, programs are written around "what is happening". This approach characterizes a program as a series of linear steps. This can be thought of as code acting on data.

But, object-oriented programming organizes a program around its data, i.e., objects, and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

Following are the three mechanisms that are required to implement the object-oriented model:

Encapsulation
  • It is the mechanism that binds together code and the data it manipulates
  • It keeps both code and data safe from outside interference and misuse
  • The basis of encapsulation is the class
  • A class defines the structure and behavior (of code and data) that will be shared by a set of objects
  • Each object of a given class contains the structure and behavior defined by the class
  • A class is a logical construct, whereas an object has physical reality
  • The purpose of a class is to encapsulate complexity
  • There are mechanisms for hiding the complexity of the implementation inside the class
  • Each method or variable in a class may be marked private or public
  • The public interface of a class represents everything that external users of the class need to know, or may know
  • The private methods and data can only be accessed by code that is a member of the class
  • Any other code that is not a member of the class cannot access a private method or variable

Ineritance
  • It is the process by which one object acquires the properties of another object
  • It supports the concept of hierarchical classification
  • Without the use of hierarchies, each object would need to define all of its characteristics explicitly
  • However, by use of inheritance, an object need only define those qualities that make it unique within its class
  • It can inherit its general attributes from its parent
  • It is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case
  • If a given class  encapsulates some attributes, then any subclass will have the same attributes plus any that it adds as part of its specialization
  • This lets object-oriented programs grow in complexity linearly rather than geometrically

Polymorphism
  • Polymorphism is a feature that allows one interface to be used for a general class of actions
  • The specific action is determined by the exact nature of the situation
  • It can be expressed by the phrase - one interface, multiple methods
  • It is possible to design a generic interface to a group of related activities
  • This helps reduce complexity by allowing the same interface to be used to specify a general class of action
  • It is the compiler's job to select the specific action as it applies to each situation
  • There are three distinct forms of polymorphism
    • Method overloading
    • Method overriding through inheritance
    • Method overriding through the Java interface
  • Which overloaded method to call is decided at compile time through the reference type passed
  • The other two forms are part of runtime polymorphism
  • With runtime polymorphism, the decision as to which version of a method will be executed is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is invoked
  • The decision as to which version of the method to invoke cannot be made at compile time
  • That decision must be deferred and made at runtime
  • This is sometimes referred to as late binding or dynamic method binding
Another essential element of object-oriented programming is abstraction.
  • A powerful way to manage abstraction is through the use of hierarchical classifications
  • This allows us to layer the semantics of complex systems, breaking them into more manageable pieces
  • The complicated implementation details are hidden from the user
  • The user is given a simple interface to interact with, whereas inside the actual implementation of the interface there may be many complicated details


(Compiled from Java 2: The Complete Reference)