There's some good advice in other comments about scoping of variables. I have another related remark. I often notice developers getting confused with instance/static variables due to starting off with the main(String arg) method. Because this method is static, one tends to not bother with creating an instance, and ends up with only static methods and fields. This is no problem for a tiny piece of test code, but as soon as you need multiple classes and an Object-Oriented design, it becomes a nuisance very quickly.
A useful way to avoid this would be to not start off with the main method, but with a unit test:
import junit.framework.Assert;
import junit.framework.TestCase;
public class MyAppTest extends TestCase {
public void testCreateMessage() {
MyApp myApp = new MyApp("Always write a Te");
String message= myApp.createMessage("stackoverflow");
assertEquals("Always write a Test", message);
}
}
Remember to put tests in a separate source directory, i.e. src/test/java vs src/main/java for your application code. This makes it easier to run and deploy your application code separately and follows the Maven 2 default layout.
Then your class could look like this (slightly modified to suit my explanation):
public class MyApp {
// constants always like this
private static final int COLUMN_ONE = 0;
private static final int COLUMN_TWO = 1;
// make instance variables final if possible
private final String name;
public MyApp(String name) {
this.name = name;
}
public void String createMessage(String arg) {
return name + arg.charAt(COLUMN_ONE) + arg.charAt(COLUMN_TWO);
}
}
Now just run your unit test. In Eclipse, right-click on the class MyAppTest and choose "Run as JUnit test". In this way you will start off on the right Object-Oriented foot.
If you later want to make your application executable, you can either add a main method to MyApp, or create a small bootstrap class to do the work:
public class MyAppStarter {
public static void main(String[] args) {
MyApp myApp = new MyApp(args[0]);
System.out.println(myApp.createMessage("!!"));
}
}
The nice thing of this solution is that you can keep the parsing of commandline arguments and other operational details of starting your application separated from the business code.