Behavior, Content, Money – 3 Things you should never give away for free!!!

BCmoney MobileTV

The Getting Started in JAVA Guide (That I Wish I Had In University)

Posted by bryan on September 24, 2012 in Java with 5 Comments


No Gravatar
History Language Installing Examples
Compiling Running Programs IDEs
Java (programming language)

Java (programming language) (Photo credit: Wikipedia)

The Java programming language is one of the most widely used and widely supported programming languages in the world (in terms of total number of devices and systems running it). Since its inception, it has also been the subject of several major lawsuits (i.e. Oracle .vs. Google, Google .vs. Oracle countersuit,  US Gov .vs. Microsoft, Apple .vs. Android OEMs – Samsung, Motorola, HTC and  Sun .vs. Microsoft) due in no small part thanks to its aforementioned widespread use in just about every major device from mobile phones to back-end server infrastructure and from individual desktops/laptops to large-scale distributed computing grids (like Amazon’s AWS & EC2).

Java didn’t set out to be a better C for every programmer, and in fact had an identity crisis early in its life. It started out in 1991 as a language called “Oak”, part of a small project called the “Green Team” initiated by Patrick Naughton, Mike Sheridan, and James Gosling, who is primarily credited with the design of the language that became Java. (Bryan Youmans has a page on the history of Java, with some interesting thoughts on the language design. There’s also an official version of the history from Sun/Oracle.)

History

TV Set-Top Boxes

The original goal of the Green Team was to produce a single operating environment that could be used for controlling a wide range of consumer devices such as video games and TV set-top boxes. A key part of the environment would be a programming language that was completely independent of the processor it ran on.

As it turned out, targeted industries such as cable TV were not ready for the concepts the Green Team was selling, but the kind of active, user-selected content they had envisioned was emerging in a new medium: The Internet.

So in 1995, Java found a market “Delivering a new level of interactivity to client browsers on the World Wide Web”. Its ability to run the same code on any processor (“write once, run anywhere” as has long been the Java slogan) was exactly what was needed to download chunks of code called “applets” to be run on a heterogeneous universe of client architectures.[6]

Why do we need Java?

While I won’t give a detailed look at how the hardware or operating systems work, I will try to simplify (at the risk of over-simplifying) how computers work so that you can understand at a basic level what’s going on inside. Computers are interconnected chips with specialized purposes (i.e. CPU, GPU, RAM, ROM, Network adapters, Peripherals, etc), so they can’t speak a human language like you and me. Instead, computers need to receive really basic instructions such as “add: 1 + 2”, “read: MemoryA” or “connect: a to b”. This low-level language is commonly referred to as an Assembly language. To do all the complex things we expect computers to do today, such as high-volume stock trading or financial transactions, playing music or streaming videos, or even just posting text comments on a blog, message board or social network whose servers are in a different country from you, half way around the world and having that instantly visible to other people, we would need to write an impossibly large amount of this “low-level” Assembly code to deal with every possible use-case. Instead, researchers devised ways to program at a higher level (so called high-level programming languages), whose more human-readable structure is then compiled and/or interpreted into low-level code instructions for the various hardware and operating systems on which it is run. This is where the need for Java emerged. It was difficult, time-consuming, resource-intensive and thus costly to create these compilers and interpreters fr each and every new computing device that came out. When there is a cost-based incentive to create a more efficient and portable method of compiling and running code, you can rest assured that the industry will innovate, enter Java and its promises of portability.

Portability

“Write Once, Run Anywhere” is the motto for the Java programming language. In order to accomplish this primary design goal, the first implementations of Java used an interpreted virtual machine. These implementations produced programs that ran more slowly than programs compiled to native executables, for instance written in C or C++, so the language suffered a reputation for poor performance as a trade-off for portability. More recent JVM implementations produce programs that run significantly faster than before, using multiple techniques.

The first technique is to simply compile directly into native code like a more traditional compiler, skipping bytecodes entirely. This achieves good performance, but at the expense of portability. Another technique, known as just-in-time compilation (JIT), translates the Java bytecodes into native code at the time that the program is run which results in a program that executes faster than interpreted code but also incurs compilation overhead during execution. More sophisticated VMs use dynamic recompilation, in which the VM can analyze the behavior of the running program and selectively recompile and optimize critical parts of the program. Dynamic recompilation can achieve optimizations superior to static compilation because the dynamic compiler can base optimizations on knowledge about the runtime environment and the set of loaded classes. JIT compilation and dynamic recompilation allow Java programs to take advantage of the speed of native code without losing portability.[7]

Learning the Java Language

Having been forced to learn at least basic proficiency in over 30 computer languages in the span of 12 years since I took my first computer science courses, I know firsthand that learning any new language or platform can be a daunting task. At first, you feel very inferior or at least somehow limited by your lack of knowledge. The many terms, keywords and unique styles of coding can make code you’ve seen for the first time look like a totally complex and indecipherable alien language. For this reason, I will take it from the top, introducing the reader to the very basics of the Java programming language. At the same time, I will also show some practical examples (because hey, let’s admit what’s on everyone’s mind, the usual “Hello World” nonsense gets old real quick). On that point I do think the main reason other than “frustration over complexity” that causes people to give up on learning a language is the “inabilty to acquire a proficient status in the language quickly enough to create things”. Creating things maintains your interest, and the quicker you work with easy but practical and fun examples, the sooner you can feel confident enough to start writing your own code.

There will likely be some initial hurdles to overcome in understanding the way to lay out a program in Java, as well as the various design patterns of Object-Oriented Programming in general. “Object-oriented” is a fancy way of saying that you break up code into separate groupings (objects), which makes the code more manageable and reusable. A “class” is a file formatted in Java and having the extension “.java”. Classes are Java’s way of putting an “object” into code that the computer can compile into something called “bytecode” which is a form of low-level code it actually understands, thanks to the JVM. When the computer receives low-level instructions (which is compiled bytecode such as a “Something.class” file version of the original “Something.java”) it can then perform the expected tasks. For example, if I am writing a Payroll program in Java that has to pay out a salary to an employee on behalf of an employer, I would create a separate “class” for at least the Employee, the Employer, the Employee’s Salary and their Pay representing an event whereby a portion of the Salary would be dispensed (obviously a real HR/Payroll application would have many more requirements, such as tying into the Employer’s existing HR, ERP, accounting and/or auditing software, but you could accomplish a very basic pay system using this example). To get your head around the concept of “Object-Oriented design patterns” I highly recommend the following books which serve as more of an intro to programming:


Or, the following which focus more specifically on learning the ins & outs and all the nitty-gritty details of the Java programming language:

Alternatively, if you are on a tight budget this article is a good start and could be used alongside this tutorial and a good reference site which has lots of good examples. Before we get too ahead of ourselves though, we should get a basic understanding of Java’s “syntax”, which is just a fancy way of saying the various keywords that are available to you as part of the language, as well as the order they can be used in and various ways they can be combined.

Syntax
First off, you should get familiar with (i.e. not be scared of) the syntax of Java which is similar to many languages but identical to none (or as they say: “often imitated but never duplicated”). The following table will summarize the most important notes on syntax, which is a convention or style of programming that must be followed in order to write programs that compile and run:

Simple Data Types
byte 8 -128..127
short 16 -32,768..32,767
int 32 -2,147,483,648.. 2,147,483,647
long 64 -9,223,372,036,854,775,808..
9,223,372,036,854,775,807
float 32 3.4e-0.38.. 3.4e+0.38
double 64 1.7e-308.. 1.7e+308
char 16 Complete Unicode Character Set
Boolean true, false
decare a variable:
type identifier [= value];
Arrays
int array_name[ ];
array_name=new int[100 ];
declare an integer array and allocate
100 elements of memory.
int array_name[ ] = new int [
100];
int array_name [ ] = {1, 2, 3, 4};
declare and allocate an integer array in
one statement.
int array_name[] = new
int[10][20];
multidimensional array.
null for reference type (class, array).
Class
{public|final|abstract} class name
{ [class_variable_declarations]
public static void main{String[] args) {statements}
[methods]
}this, super
Methods
{public | private } [static] {type | void} name(arg, …, arg ) {statements}
Variable
{public | private } [static] type name [= expression];
Arithmetic Operators
+, -, *, /
%, ++, —
addition, subtraction, multiplication, division
modulus, increment, decrement.
Relational Operators
==, !=, >, <,
>=, <=
equal, not equal, greater, less,
greater or equal, less or equal.
Logical Operators
&, |, !, ^, ||, &&, AND, OR, NOT, XOR, short -circuit OR, AND
Bitwise Operators
&, |, ~, ^,
>>, >>>, <<
AND, OR, NOT, XOR
shift right, shift right zero fill, shift left.

Keywords
Keyword Description Example
abstract an abstract class or method abstract class Writable { public abstract void write(Writer out); public void save(String filename) { … } }
assert with assertions enabled, throws an error if condition not fulfilled assert param != null;
Note: Run with -ea to enable assertions
boolean the Boolean type with values true and false boolean more = false;
break breaks out of a switch or loop while ((ch = in.next()) != -1) { if (ch == ‘n’) break; process(ch); }
Note: Also see switch
byte the 8-bit integer type byte b = -1;
Note: Not the same as 0xFF. Be careful with bytes < 0
case a case of a switch see switch catch the clause of a try block catching an exception see try char the Unicode character type char input = ‘Q’;
class defines a class type class Person { private String name; public Person(String aName) { name = aName; } public void print() { System.out.println(name); } }
continue continues program flow at the end of a loop while ((ch = in.next()) != -1) { if (ch == ‘ ‘) continue; process(ch); }
default the default clause of a switch see switch do the top of a do/while loop do { ch = in.next(); } while (ch == ‘ ‘);
double the double-precision floating-number type double oneHalf = 0.5;
else the else clause of an if statement … else { //do something }
enum an enumerated type enum Mood { SAD, HAPPY };
extends defines the parent class of a class class Student extends Person { private int id; public Student(String name, int anId) { … } public void print() { … } }
final a constant, or a class or method that cannot be overridden
finally the part of a try block that is always executed see try
float the single-precision floating-point type float oneHalf = 0.5F;
for useful loop type used similarly to while, but can be less verbose and more versatile for (int i = 10; i >= 0; i–)
System.out.println(i);

for (String s : line.split(“s+”))
System.out.println(s);

Note: In the “generalized” for loop, the expression
after the : must be an array or an Iterable

if the primary conditional statement to check existence of a particular case or state of one or more variable(s) if (input == ‘Q’) {

System.exit(0);
}
else {
more = true;
}

implements defines the interface(s) that a class implements class Student implements Printable { … }
import imports an internal or external package to expose its public methods and variables import java.util.ArrayList; //imports ArrayList class from “util” package
import com.dzone.refcardz.*; //imports all classes in “refcardz” package, but not classes from children packages
instanceof tests if an object is an instance of a class if (fred instanceof Student) value = ((Student) fred).getId();
Note: null instanceof T is always false
int the 32-bit integer type int value = 0;
interface an abstract type with methods that a class can implement interface Printable { void print(); }
long the 64-bit long integer type long worldPopulation = 6710044745L;
native a method implemented by the host system new allocates a new object or array Person fred = new Person(“Fred”);
null a null reference Person optional = null;
package a package of classes package com.dzone.refcardz;
private a feature that is accessible only by methods of this class see class
protected a feature that is accessible only by methods of this class, its children, and other classes in the same package class Student {
protected int personalID;

}
public a feature that is accessible by methods of all classes see class
return returns from a method public int getId() { return id; }
short the 16-bit integer type short skirtLength = 24;
static a feature that is unique to its class, not to objects of its class public class WriteUtil {
public static void write(Writable[] ws, String filename);
public static final String DEFAULT_EXT = “.dat”;
}
strictfp Use strict rules for floating-point computations
super invoke a superclass constructor or method public Student(String name, int anId) {
super(name); id = anId;
}
public void print() {
super.print();
System.out.println(id);
}
switch a selection statement switch (ch) {
case ‘Q’:
case ‘q’:
more = false; break;
case ‘ ‘;
break;
default:
process(ch);
break;
}
Note: If you omit a break, processing continues with the next case.
synchronized a method or code block that is atomic to a thread public synchronized void addGrade(String gr) {
grades.add(gr);
}
this the implicit argument of a method, or a constructor of this class public Student(String id) {this.id = id;}

public Student() { this(“”); }

throw throws an exception if (param == null) {
throw new IllegalArgumentException();
}
throws the exceptions that a method can throw public void print()

throws PrinterException, IOException

transient marks data that should not be persistent class Student {
private transient Data cachedData;

}
try a block of code that traps exceptions try {
try {
fred.print(out);
}
catch (PrinterException ex) {
ex.printStackTrace();
}
} finally {
out.close();
}
void denotes a method that returns no value public void print() { … }
volatile ensures that a field is coherently accessed by multiple threads class Student {
private volatile int nextId;

}
while the primary looping mechanism, to repeat certain segments of code (usually in combination with certain conditions and exit cases) while (in.hasNext()) {
process(in.next());
}

Apart from this very quick overview, you can find out what native APIs are available in each version of Java’s generated javadocs. Javadocs are comments structured in a particular manner, and are used to generate standardized and easily browsable documentation of your program’s various APIs and methods, what parameters types they can accept, what values they should return and additional metadata such as author, date, last modified, and assorted info about the code. You can still find the Java API docs for the following Java versions:

Lastly, the following Java syntax reference as well as this “Java API cheat sheet” and of course the original Sun/Oracle Java tutorials can come in quite handy as you start to develop your own programs.

Install

Before you can do anything in the language, you need to verify that Java is running on your system. There are two ways of doing this:

EASY WAY:
All Platforms

  • Navigate to the Java install site in your browser –> click “Do I have Java?” –> click “Verify Java Version” –> click “Install latest version” as suggested:
    http://www.java.com/en/download/installed.jsp
    (works similar to Flash or Silverlight update sites by verifying current version then suggesting upgrade or install of latest stable version, if required)

HARD WAY:

  • WINDOWS
    • Start –> Run –> type “cmd“, hit Enter (launches Command Prompt window) –> type “java -version
    • download latest stable Java version from URL
      wget “http://java”
    • Unzip “java.zip”
    • Move extracted “java” folder to “C://APPS/Java/”
    • Open new foler “C://APPS/Java”
    • Run “java-<VERSION>.exe” install file

MAC

  • Open Console –> type “java -version
  • Download installation file from URL:
    wget “”
  • Unzip “java.tar”
  • Move extracted ‘java” directory to “/Apps/Java/<VERSION>”
  • Run “java-<VERSION>.app” install file

LINUX

  • Launch Terminal (Bash/Shell command window) –> type “java -version
  • Download installation file from URL:
  • Unzip “java.tar.gz”
  • Move extracted “java” directory to “//<USER>/Apps/Java/<VERSION>”
  • Run “java-<VERSION>.bin” -or- “Java.sh” (depending on platform) install file

Setting Environment Variables
After installing Java there are some environment variables that needs to be set.

  • CLASSPATH : This env variable should be declared in system variable. This env variable points the location of JDK home directory. It can also contains the address to folder from which you want jars to get loaded by classloader(For more details of ClassLoader visit here)
  • JAVA_HOME : This env variable should point to the location of Java home directory.

How to set env variable in different platforms:
Windows XP
To set env variable in windows XP right click “My Computer” icon and select properties. From property windows

Windows Vista / 7
To set env variable in windows Vista / 7 right click “Computer” and select properties. From property windows select “ADVANCED SYSTEM SETTINGS”. In System Properties window select “ADVANCE” tab and then click “ENVIORNMENT VARIABLES”. In next window enter enviornment variable under user/system variables settings.

MAC

LINUX
First, add an environment variable JAVA_HOME :

export JAVA_HOME=/usr/java/j2sdk1.4.2_04
export PATH=$JAVA_HOME/bin:$PATH

Then, insert the following lines in your .bash_profile (for example .bashrc):

CLASSPATH=:/$JAVA_HOME/jre/lib/jsse.jar:/$JAVA_HOME/jre/lib:
export CLASSPATH

Examples

Ok, so I know I promised to deliver a little more than the common HelloWorldboring examples, but, for the sake of having some very simple examples to work with while getting your head around how to compile Java programs via the command-line (and even more easily, via an IDE), here are three necessary evils showing three different types of basic stand-alone HelloWorld application:

[snippet id=66769]

Each of these four examples are in fact a fully functional, standalone Java application (although, calling them an application seems like a bit overstatement, that’s technically what they are, so consider them your very first Java applications). The first application in the examples requires no special inputs, and simply outputs the phrase “Hello World!” when compiled and run. The second application requires some input at runtime, when you actually issue the command to run you can specify after the (see running)

Compiling

You can compile the basic examples as follows:

javac HelloWorld.java

Here, javac is the Java Compiler for your installed Java version (or preferred Java version, if multiple versions are installed). On Windows, it is an executable file (i.e. a file called
javac.exe“) and on Unix-based systems it is a runnable file with no extension (i.e. a file called “javac“).

Useful javac Options
Option Purpose
-cp or -classpath Sets the class path, used to search for class files.
The class path is a list of directories, JAR files, or expressions of the form:
directory/’*’ (Unix) or directory* (Windows)
The latter refers to all JAR files in the given directory.
Class path items are separated by
: (Unix) or ; (Windows).
If no class path is specified, it is set to the current
directory. If a class path is specified, the current directory is not
automatically included—add a . item if you want to include it.
-sourcepath Sets the path used to search for source files. If source and class files
are present for a given file, the source is compiled if it is newer. If no
source path is specified, it is set to the current directory.
-d Sets the path used to place the class files. Use this option to separate
.java and .class files.
-source Sets the source level. Valid values are 1.3, 1.4, 1.5, 1.6, 5, 6
-deprecation Gives detail information about the use of deprecated features
-Xlint:unchecked Gives detail information about unchecked type conversion warnings

Running

You can run the basic examples as follows:

java HelloWorld

When this code runs, the compiled “HelloWorld.class” class file will be interpreted as raw bytecode and result in the corresponding machine assembly code to be run to execute the required operations. In this case, the simple operations involve displaying a particular string of text on a screen (i.e. in the prompt/console/terminal in which the command was run).

Useful java Options
Option Purpose
-cp or -classpath Sets the class path, used to search for class files. See the previous
table for details. Note that javac can succeed when java fails if the
current directory is on the source path but not the class path.
-ea or -enableassertions Enable assertions. By default, assertions are disabled.
-Dproperty=value Sets a system property that can be retrieved by System.

getProperty(String)

-jar Runs a program contained in a JAR file whose manifest has a
Main-Class entry. When this option is used, the class path is ignored.
-verbose Shows the classes that are loaded. This option may be useful to
debug class loading problems.
-Xmssize
-Xmxsize
Sets the initial or maximum heap size. The size is a value in bytes.
Add a suffix k or m for kilobytes or megabytes, for example, -Xmx10m

Packaging
Arguably, the most important part of running and deploying full Java applications is packaging. In Java, packaging is done using one of three primary application deployment formats:

  • JAR: Java Application aRchive
  • WAR: Web Application aRchive
  • EAR: Enterprise Application aRchive

Looking at each of these in-depth is beyond the scope of this tutorial, but I will summarize “.jar” files in particular, since they are the most common means of deploying, integrating and using libraries and reusable Java APIs.

JAR File creation
Option Description
c Creates a new or empty archive and adds files to it. If any of the specified file
names are directories, the jar program processes them recursively.
C Temporarily changes the directory. For example,
jar cvfC myprog.jar classes *.class
changes to the classes subdirectory to add class files.
e Creates a Main-Class entry in the manifest
jar cvfe myprog.jar com.mycom.mypkg.MainClass files
f Specifies the JAR file name as the second command-line argument. If this
parameter is missing, jar will write the result to standard output (when creating a
JAR file) or read it from standard input (when extracting or tabulating a JAR file).
i Creates an index file (for speeding up lookups in a large archive)
m Adds a manifest to the JAR file.
jar cvfm myprog.jar mymanifest.mf files
M Does not create a manifest file for the entries.
t Displays the table of contents.
jar tvf myprog.jar
u Updates an existing JAR file
jar uf myprog.jar com/mycom/mypkg/SomeClass.class
v Generates verbose output.
x Extracts files. If you supply one or more file names, only those files are
extracted. Otherwise, all files are extracted.
jar xf myprog.jar

Sample Programs

Inheritance

Letter-Grade Calculator

GPA

WordCount
This example shows how to perform File I/O and String manipulations.

Data Structure
LinkedList, Array, Map

Inheritance
Abstract, Collection/Set, Protected, Reflection

Interface
Polymorphism, Overriding .vs. Overloading, super

Inheritance

IDEs

Now that you have a basic understanding of the Java programming language, you are almost prepared to create the next great application. To help you along your journey, I will conclude this tutorial with information about how to build a more complete (and manageable) project inside of an Integrated Development Environment (IDE). The IDE is one of the modern programmer’s key tools in creating and managing large-scale applications, and you can basically think of it as a text editor on steroids. The best IDE has many programming language-specific features such as:

  • code analysis – which is a fancy way of saying “hints” are available for automatically finding/fixing errors & warnings
  • code completion – common code based on already defined APIs can be “auto-filled” as you type
  • code generation – common code automatically using point and click or “User Interface Designer” tools
  • code compilation – code gets compiled dynamically, as you edit and/or save, so that when you run next all code will be up-to-date
  • code building – the steps of compiling, managing de build tool such as ant or ivy
  • code refactoring –  the ability to rename variables, functions and other core application components across an entire project by making the change once)
  • code debugging – you can step through your code line-by-line using a debugger to troubleshoot errors
  • code testing- you can use language-specific testing tools, such as jUnit, EasyMock, phpUnit, etc
  • code coverage – you can generate reports on what portion of the code has test cases so far
  • dependency management – there is a mechanism for aiding in the use of external libraries

While back in the day I learned how to program Java on good old IDEs like JBuilder and BlueJay, today, the two most popular IDEs for Java (and arguably any languages’) software development are:

  • Netbeans – open source IDE started by Sun, taken over by Oracle
  • Eclipse – open source IDE started by independent community of Java developers

I hope this has been a useful tutorial in introducing the Java programming language. Later, I intend to take more in-depth looks at the most popular configuration management (i.e. Maven + Ant), continuous integration (i.e. Hudson/Jenkins) and testing (i.e. jUnit + EasyMock + Cobertura) platforms within the context of both Netbeans and Eclipse. Depending on how RIM’s new BlackBerry 10 SDK turns out, I may also focus on that platform for creating Mobile applications in Java in the new year. If it doesn’t improve much from versions 4 to 9 (which had infamously difficult to work with SDKs), then I may focus on Android or Google AppEngine instead. Java Mobile app development is really a story unto itself and may require several posts.