Intro to Memtech: Java - Java Syntax

In the last post, we setup an Android development environment. We also setup our first Android app in "Hello, World" in cut and paste fashion.  That's all fine and good if you already have a good handle on Java syntax, but what if you're still in the dark on that subject? In this post, we'll cover the basics of Java syntax.

//this is a comment
int i;  //this is a primitive integer variable declaration
i = 2 + 2; //this is an assignment statement

Java has a C-style syntax, so chances are it already looks pretty familiar. It is a statically typed language and uses infix notation for most operations. Semicolons delimit the end of statements, so it is possible to stack multiple operations on one line, but not usually recommended.

String s = "This string is immutable."; //Strings are objects, not primitives
String s = "This assignment creates a new string." 
//The old string is garbage collected by the JVM

Java is an object oriented language.  Two other important features are that Strings are immutable and unreferenced objects are automatically deleted by the Garbage Collector.  Garbage collection can be expensive, especially in real-time applications.  So performance can take a dive on something something like:

String s = "";
/*This "for loop" repeats this block of code 99 times
  It subtracts 1 from the initial value of 99 assigned to 'i' on each pass.
  It exits when the boolean operation 'i  > 0' equates to false */
for(int i = 99; i  > 0;  i--)
  //The '+' operator appends strings.
  s = s + i + " bottles of beer on the wall. " + i + " bottles of beer. \n";
  //The primitive i is automatically converted to a string.
  s = s + " Take one down, pass it around. " + i + " bottles of beer on the wall. \n";
  //Notice the '\n' end line character

Each time we make an assignment to 's' we create a new unreferenced string which must be garbage collected. Java does have a few primitive types, such as integers. Luckily, primitives each have a Wrapper class that allows you to use it when you need it to act like an object. In the last example we get the 'i.toString()' method called each time we concatenate 'i' with a string. Some additional syntactic sugar known as auto-boxing makes other conversions invisible.

int primitiveInt = 42;
Integer integerObject = new Integer(13); 
//Create a new Integer object that wraps a value of 13
integerObject = primitiveInt;
System.out.println(integerObject);  //prints 42 in the console

If you've noticed we also snuck in Console output, a control structure (the for loop), and a boolean operation ('i > 0' or 'i' is greater than zero).  Chances are that all looks familiar and you had no trouble reading it, even if you don't 'know' Java. In the next post I'll go into how to get a running program with these types of statements, what the 'System.out' means in the last example, and an explanation of packages, classes, and methods.