Wednesday, February 5, 2014

Button widgets in Android Programming

In this chapter of the Android development tutorial we will present button widgets. 

A Button class represents a push button widget in Android. The full package path for the button class is android.widgets.Button. Buttons are clicked to perform an action. A button can display text or an icon. Or both. Event handlers for Button click events are defined with the android:onClick attribute of the <Button> element or programatically by setting the setOnClickListener(View.OnClickListener).

Button

In the first example we define a button that closes an activity when pressed.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.zetcode.finish"
      android:versionCode="1"
      android:versionName="1.0">
 <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
    <activity android:name="MainActivity"
                android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
 </application>
</manifest>
This is the manifest file for the program.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <Button
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:layout_marginTop="10dip"
      android:text="@string/btnlabel"
      android:onClick="onClick" />
</LinearLayout>
In the main.xml layout file, we define one button widget with the <Button> element. The first two attributes define the size of the button so that it is big enough to show its content. The android:layout_marginTop="10dip" creates a margin between the title bar of the screen and the button widget. The dip (density independent pixel) is a unit of measurement that is used for Android layout management. It best reflects the rich diversity of resolutions and densities of various Android appliances. The android:text="@string/btnlabel" attribute defines a text for the button. The actual text resides in the strings.xml file, which we cover before long. Finally, the android:onClick="onClick" attribute creates a button event listener for the click event. All we need to do is to define the onClick() method in the relevant Java source file.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Finish button</string>
    <string name="btnlabel">Finish</string>
</resources>
In the strings.xml file we have two resource strings. The first is used in the manifest file to provide a name for the application and the main activity. The second is used in the layout file to provide a text label for the button widget.
MainActivity.java
package com.zetcode.finish;

import android.app.Activity;
import android.view.View;
import android.os.Bundle;

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    public void onClick(View view) 
    {
        finish();    
    }
}
This is the source file for the main activity. We have defined an onClick() method which reacts to the button click events. It must take a View as its sole parameter. The method calls the finish() method which closes the current activity. We are redirected back to the list of applications.
Button
Figure: Button
Clicking on the button we are redirected back to the list of applications.

Showing a toast

A toast is a view that contains a quick message for the user. Toasts can be displayed for a short or a long period of time. In our second application we create a button widget. It will show a toast message after being pressed.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.zetcode.toast"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" 
            android:icon="@drawable/ic_launcher">
        <activity android:name="MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
This is the manifest file.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <Button
        android:id="@+id/btnId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="@string/label" />
</LinearLayout>
In the main.xml layout file, we have one button widget inside the LinearLayout, which arranges widgets in a single row or column. In our case the button is in a single column. The button has a android:id="@+id/btnId" attribute. The attribute supplies an identifier name for the button. We will retrieve the button in the main activity using the findViewById() method. Widgets that are not being referenced do not need this attribute. The plus sign is used when we create the id of the element. Subsequent references to the element in the XML file would be used without the plus sign. (For example in layout managers.)
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Show Toast</string>
    <string name="label">Show</string>
</resources>
This is the strings.xml resource file. The button will have the 'Show' text label.
MainActivity.java
package com.zetcode.toast;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Gravity;
import android.widget.Button;
import android.widget.Toast;
import android.content.Context;

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initUI();
    }

    public void initUI()
    {
        Button btn = (Button) findViewById(R.id.btnId);

        btn.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View arg0) 
            {
                Context ctx = getApplicationContext();
                String msg = "Button was clicked";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(ctx, msg, duration);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        });
    }
}
When we click on the button widget, it will show a Toast message in the center of the screen. The toast will be displayed for a short period of time.
...
import android.view.View.OnClickListener;
import android.view.Gravity;
import android.widget.Button;
import android.widget.Toast;
import android.content.Context;
These are some of the new classes needed to be imported in this example.
initUI();
In the onCreate() method we call the initUI() method. It adds the OnClickListener() to the button widget.
Button btn = (Button) findViewById(R.id.btnId);
We get the reference to the button widget that we have specified in the main.xml file. We use the findViewById() method. The method finds a View (A button is a kind of a View) by the id attribute from the main.xml file. The id is located in the auto-generated R class. R stands for Resource. We can have a look at the R source code in the gen/com/zetcode/toast/R.java source file. There we will find the button id among others.
btn.setOnClickListener(new OnClickListener() 
{
    @Override
    public void onClick(View arg0) 
    {
        ...
    }
});
We add the OnClickListener to the button widged. Listeners can be set up in various ways. Here we use an anonymous inner class.
Context ctx = getApplicationContext();
String msg = "Button was clicked";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(ctx, msg, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
We set up and show the Toast view. We get the application context, create a message and the duration time. The gravity is the alignment of the view within its parent. We position the toast in the center of the screen. By default, the toasts are displayed at the bottom of the screen.
Showing toast
Figure: Showing toast

CheckBox

A CheckBox widget is a special kind of a button. It has two states. On and off. The on state is represented by a tick mark inside a rectangle.
java.lang.Object
  android.view.View
     android.widget.TextView
       android.widget.Button
         android.widget.CompoundButton
           android.widget.CheckBox
This is the inheritance hierarchy for the CheckBox widget. The Button widget is among its parents.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.zetcode.checkbox"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" 
            android:icon="@drawable/ic_launcher">
        <activity android:name="MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
The manifest file.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <CheckBox
      android:id="@+id/cb_id"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/cblabel" />
</LinearLayout>
The <CheckBox> element creates a CheckBox widget.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">CheckBox</string>
    <string name="cblabel">Show title</string>
</resources>
String resources.
MainActivity.java
package com.zetcode.checkbox;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;

public class MainActivity extends Activity
{
    private CheckBox cb;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initUI();
    }

  public void initUI() 
  {
      cb = (CheckBox) findViewById(R.id.cb_id);
      cb.setChecked(true);

      cb.setOnClickListener(new OnClickListener() 
      {
          @Override
          public void onClick(View v) 
          {          
              CheckBox cb = (CheckBox) v;

              if (cb.isChecked()) 
              {
                  setTitle("CheckBox");
              } else {
                  setTitle("");
              }
          }
      });
  }    
}
The CheckBox toggles the visibility of the screen title. When the CheckBox is in a checked state, the title is visible. Othervise it is not.
import android.widget.CheckBox;
We import the CheckBox class into the source file.
cb = (CheckBox) findViewById(R.id.cb_id);
We find the reference to the CheckBox widget, defined in the main.xml file.
cb.setChecked(true);
The title is visible by default, so the CheckBox must be in a checked state. We use the setChecked() method to change the state of the widget.
cb.setOnClickListener(new OnClickListener() 
{
    @Override
    public void onClick(View v) 
    {          
        CheckBox cb = (CheckBox) v;

        if (cb.isChecked()) 
        {
            setTitle("CheckBox");
        } else {
            setTitle("");
        }
    }
});
In the OnClickListener() we define the onClick() method. We determine the state of the widget using the isChecked() method. The title of the screen is modified with the setTitle() method. 

CheckBox widget
Figure: CheckBox widget

In this chapter of the Android development tutorial we have presented button widgets.

First Android application

In this chapter of the Android development tutorial we will create our first Android application. 

The application will just display a message on the screen.
$ mkdir First
$ cd First/
We create a First directory and make it the current working directory.
$ android create project --target android-17 --name First \
> --path . --activity MainActivity --package com.zetcode.first
Created directory /home/janbodnar/programming/android/First/src/com/zetcode/first
Added file ./src/com/zetcode/first/MainActivity.java
Created directory /home/janbodnar/programming/android/First/res
Created directory /home/janbodnar/programming/android/First/bin
...
We create a new Android project with the android create project command. The target option specifies the Android application framework version. The name option determines the name of the project. The path is the location of our project directory. The activity is the name of our default activity. Finally, the package is the name of the package namespace for our project. The command creates a Java file for the main activity, several directories and XML files.
$ ls 
AndroidManifest.xml  bin        libs              proguard-project.txt  res
ant.properties       build.xml  local.properties  project.properties    src
These are the files and directories created by the android create project command. The AndroidManifest.xml file describes the fundamental characteristics of the application. The source files of the application reside in the src directory. In the res directory, we have the application's resource files. The Android application archive file will be created in the bin directory. The libs directory is used to store additional libraries. The ant.properties and build.xml files are the Ant files used to build the project. Finally, the local.properties and the project.properties are property files of the Android project.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.zetcode.first"
      android:versionCode="1"
      android:versionName="1.0">
   <application android:label="@string/app_name"
                   android:icon="@drawable/ic_launcher">
       <activity android:name="MainActivity"
                 android:label="@string/app_name">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>
This is the project manifest file. It describes some basic characteristics of the Android project. The file provides the package name, which is com.zetcode.com in our case. It contains the name of the default activity. The @string/app_name and @drawable/ic_launcher are resource values. The string resource values are set from the strings.xml file located in the res/values subdirectory. The image resources are located in the drawable subdirectories of the res directory. The <intent-filter> element of the main activity declares its capabilities. It specifies what the activity can do. The two intents specify that the activity is a main entry point of the application, it can be the initial activity of a task and is listed in the top-level application launcher.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">First program</string>
    <string name="messsage">First Android program</string>
</resources>
In the strings.xml file we have one element which defines the resource value referenced from the AndroidManifest.xml file. The file is located in the res/values subdirectory. We change the value of the first element (from 'MainActivity' to 'First program'). The name of the application is shown in the list of the applications in the emulator. We add the second element. It is referenced from the main.xml file.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/message"
    />
</LinearLayout>
This is the main.xml file located in the res/layout subdirectory. It defines the layout of an Activity. The application loads the layout for an Activity in the onCreate() method. In our case we have a vertical linear layout with one TextView widget.
MainActivity.java
package com.zetcode.first;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
This is the MainActivity.java source file. When the activity is first created the onCreate() method is called. The method loads the activity layout defined in the main.xml file.

Building the application

We use the ant tool to build the Android application.
$ ant debug
We execute the ant debug command in the project root directory. There are two build targets. Debug and release. We will use the debug build target. The release build needs some additional work with signing.
$ ant debug install
It is possible to build and install the application in one step using the ant debug install command.
$ ls -1 bin
AndroidManifest.xml
AndroidManifest.xml.d
build.prop
classes
classes.dex
classes.dex.d
First.ap_
First.ap_.d
First-debug.apk
First-debug-unaligned.apk
First-debug-unaligned.apk.d
jarlist.cache
proguard.txt
res
The final Android package is created in the bin directory. The name of our archive file is First-debug.apk.

Running the application

We install the application to the emulator and start it from it.
$ emulator -avd AVD2 &
The emulator is started with a specific android virtual device.
$ adb install bin/First-debug.apk 
The adb install command installs the application on the emulator. 

First program
 
Figure: First program
We did not use a custom icon, so the built-in icon is used. From the applications list we select the First program application. The application is launched. 

First program
 
Figure: The First program screen
We can see the message that we have specified in the strings.xml file.
This chapter was an introduction Android application development.

Tuesday, February 4, 2014

Data Types in Java

In this part of the Java tutorial, we will talk about data types. 

Computer programs work with data. Spreadsheets, text editors, calculators or chat clients. Tools to work with various data types are essential part of a modern computer language. A data type is a set of values and the allowable operations on those values. 

Java programming language is a statically typed language. It means that every variable and every expression has a type that is known at compile time. Java language is also a strongly typed language, because types limit the values that a variable can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong static typing helps detect errors at compile time. Variables in dynamically typed languages like Ruby or Python can receive different data types over the time. In Java, once a variable is declared to be of a certain data type, it cannot hold values of other data types.
There are two fundamental data types in Java: primitive types and reference types. Primitive types are:
  • boolean
  • char
  • byte
  • short
  • int
  • long
  • float
  • double
There is a specific keyword for each of these types in Java. Primitive types are not objects in Java. Primitive data types cannot be stored in Java collections which work only with objects. They can be placed into arrays instead.
The reference types are:
  • class types
  • interface types
  • array types
There is also a special null type which represents a non-existing value.
In Ruby programming language, everything is an object. Even basic data types.
#!/usr/bin/ruby

4.times { puts "Ruby" }
This Ruby script prints four times "Ruby" string to the console. We call a times method on the 4 number. This number is an object in Ruby.
Java has a different approach. It has primitive data types and wrapper classes. Wrapper classes transform primitive types into objects. Wrapper classes are covered later in this chapter.

Boolean values

There is a duality built in our world. There is a Heaven and Earth, water and fire, jing and jang, man and woman, love and hatred. In Java the boolean data type is a primitive data type having one of two values: true or false.
Happy parents are waiting a child to be born. They have chosen a name for both possibilities. If it is going to be a boy, they have chosen Robert. If it is going to be a girl, they have chosen Victoria.
package com.zetcode;

import java.util.Random;

public class BooleanType {

    public static void main(String[] args) {
        
        String name = "";
        Random r = new Random();
        boolean male = r.nextBoolean();

        if (male == true) {
            
            name = "Robert";
        }

        if (male == false) {
            
            name = "Victoria";
        }

        System.out.format("We will use name %s%n", name);

        System.out.println(9 > 8);
    }
}
The program uses a random number generator to simulate our case.
Random r = new Random();
boolean male = r.nextBoolean();
These two lines randomly choose a boolean value.
if (male == true) {
    
    name = "Robert";
}
If the boolean variable male equals to true, we set the name variable to "Robert". The if keyword works with boolean values.
if (male == false) {
    
    name = "Victoria";
}
If the random generator chooses false than we set the name variable to "Victoria".
System.out.println(9 > 8);
Relational operators result in a boolean value. This line prints true to the console.
$ java com.zetcode.BooleanType 
We will use name Robert
true
$ java com.zetcode.BooleanType 
We will use name Victoria
true
$ java com.zetcode.BooleanType 
We will use name Victoria
true
Running the program several times.

Integers

Integers are a subset of the real numbers. They are written without a fraction or a decimal component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite.
In computer languages, integers are (usually) primitive data types. Computers can practically work only with a subset of integer values, because computers have finite capacity. Integers are used to count discrete entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can have 3.33 kilograms, 4.564 days, or 0.4532 kilomenters.
Type Size Range
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
char 16 bits 0 to 65,535
int 32 bits -2,147,483,648 to 2,147,483,647
long 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Table: Integer types in Java
These integer types may be used according to our needs. We can then use the byte type for a variable that stores the number of children a woman gave birth to. The oldest verified person died at 122, therefore we would probably choose at least the short type for the age variable. This will save us some memory.
Integer literals may be expressed in decimal, hexadecimal, octal, or binary notations. If a number has an ASCII letter L or l suffix, it is of type long. Otherwise it is of type int. The capital letter L is preffered for specifying long numbers, since lowercase l can be easily confused with number 1.
int a = 34;        
byte b = 120;
short c = 32000;
long d = 45000;
long e = 320000L;
We have five assignments. 34, 120, 32000 and 45000 are integer literals of type int. There are no integer literals for byte and short types. If the values fit into the destination type, the compiler does not protest and performs a conversion automatically. For long numbers smaller than Integer.MAX_VALUE, the L suffix is optional.
long x = 2147483648L;
long y = 2147483649L;
For long numbers larger than Integer.MAX_VALUE, we must add the L suffix.
When we work with integers, we deal with discrete items. For instance, we can use integers to count apples.
package com.zetcode;

public class Apples {

    public static void main(String[] args) {

        int baskets = 16;
        int applesInBasket = 24;

        int total = baskets * applesInBasket;

        System.out.format("There are total of %d apples%n", total);
    }
}
In our program, we count the total amount of apples. We use the multiplication operation.
int baskets = 16;
int applesInBasket = 24;
The number of baskets and the number of apples in each basket are integer values.
int total = baskets * applesInBasket;
Multiplying those values we get an integer too.
$ java com.zetcode.Apples 
There are total of 384 apples
This is the output of the program.
Integers can be specified in four different notations in Java. Decimal, octal, hexadecimal and binary. The binary notation was introduced in Java 7. Decimal numbers are used normally, as we know them. Octal numbers are preceded with a 0 character and followed by octal numbers. Hexadecimal numbers are preceded with 0x characters and followed by hexadecimal numbers. Binary numbers start with 0b and are followed by binary numbers.
package com.zetcode;

public class IntegerNotations {

    public static void main(String[] args) {
        
        int n1 = 31;
        int n2 = 0x31;
        int n3 = 031;
        int n4 = 0b1001;
        
        System.out.println(n1);
        System.out.println(n2);
        System.out.println(n3);
        System.out.println(n4);        
    }
}
We have four integer variables. Each of the variables is assigned a value with a different integer notation.
int n1 = 31;
int n2 = 0x31;
int n3 = 031;
int n4 = 0b1001;
The first is decimal, the second hexadecimal, the third octal and the fourth binary.
$ java com.zetcode.IntegerNotations 
31
49
25
9
We see the output of the com.zetcode.IntegerNotations program.
Big numbers are difficult to read. If we have a number like 245342395423452, we find it difficult to read it quickly. Outside computers, big numbers are separated by spaces or commas. Since Java SE 1.7, it is possible to separate integers with an underscore.
The underscore cannot be used at the beginning or end of a number, adjacent to a decimal point in a floating point literal, and prior to an F or L suffix.
package com.zetcode;

public class UsingUnderscores {
    
    public static void main(String[] args) {
        
        long a = 23482345629L;
        long b = 23_482_345_629L;

        System.out.println(a == b);                                                    
    }    
}
This code sample demonstrates the usage of underscores in Java.
long a = 23482345629L;
long b = 23_482_345_629L;
We have two identical long numbers. In the second one we separate every three digits in a number. Comparing these two numbers we receive a boolean true. The L suffix tells the compiler that we have a long number literal.
Java byte, short, int and long types are used do represent fixed precision numbers. Which means, that they can represent a limited amount of integers. The largest integer number that a long type can represent is 9223372036854775807. If we deal with even larger numbers, we have to use the java.math.BigInteger class. It is used to represet immutable arbitrary precision integers. Arbitrary precision integers are only limited by the amount of computer memory available.
package com.zetcode;

import java.math.BigInteger;

public class VeryLargeIntegers {

    public static void main(String[] args) {
        
        System.out.println(Long.MAX_VALUE);
        
        BigInteger b = new BigInteger("92233720368547758071");
        BigInteger c = new BigInteger("52498235605326345645");
               
        BigInteger a = b.multiply(c);
        
        System.out.println(a);            
    }
}
With the help of the java.math.BigInteger class, we multiply two very large numbers.
System.out.println(Long.MAX_VALUE);
We print the largest integer value which can be represented by a long type.
BigInteger b = new BigInteger("92233720368547758071");
BigInteger c = new BigInteger("52498235605326345645");
We define two BigInteger objects. They both hold larger values that a long type can hold.
BigInteger a = b.multiply(c);
With the multiply() method, we multiply the two numbers. Note that the BigInteger numbers are immutable. The operation returns a new value which we assign to a new variable.
System.out.println(a);
The computed integer is printed to the console.
$ java com.zetcode.VeryLargeIntegers 
9223372036854775807
4842107582663807707870321673775984450795
This is the example output.

Arithmetic overflow

An arithmetic overflow is a condition that occurs when a calculation produces a result that is greater in magnitude than that which a given register or storage location can store or represent.
package com.zetcode;

public class Overflow {

    public static void main(String[] args) {
        
        byte a = 126;

        System.out.println(a);
        a++;

        System.out.println(a);
        a++;

        System.out.println(a);
        a++;

        System.out.println(a);
    }
}
In this example, we try to assign a value beyond the range of a data type. This leads to an arithmetic overflow.
$ java com.zetcode.Overflow 
126
127
-128
-127
When an overflow occurs, the variable is reset to negative upper range value. In contrast, Visual Basic programming language would throw an exception.

Floating point numbers

Real numbers measure continuous quantities, like weight, height, or speed. Floating point numbers represent an approximation of real numbers in computing. In Java we have two primitive floating point types: float and double. The float is a single precision type which store numbers in 32 bits. The double is a double precision type which store numbers in 64 bits. These two types have fixed precision and cannot represent exactly all real numbers. In situations where we have to work with precise numbers, we can use the BigDecimal class.
Floating point numbers with an F/f suffix are of type float, double numbers have D/d suffix. The suffix for double numbers is optional.
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
package com.zetcode;

public class Sprinter {

    public static void main(String[] args) {
        
        float distance;
        float time;
        float speed;

        distance = 0.1f;
        
        time = 9.87f / 3600;

        speed = distance / time;

        System.out.format("The average speed of a sprinter is %f km/h%n", speed);
    }
}
In this example, it is necessary to use floating point values. The low precision of the float data type does not pose a problem in this case.
distance = 0.1f;
100m is 0.1km.
time = 9.87f / 3600;
9.87s is 9.87/60*60h.
speed = distance / time;
To get the speed, we divide the distance by the time.
$ java com.zetcode.Sprinter 
The average speed of a sprinter is 36.474163 km/h
This is the output of the com.zetcode.Sprinter program. A small rounding error in the number does not affect our understanding of the sprinter's speed.
The float and double types are inexact.
package com.zetcode;

public class FloatingInPrecision {

    public static void main(String[] args) {        
                
        double a = 0.1 + 0.1 + 0.1;
        double b = 0.3;
        
        System.out.println(a);
        System.out.println(b);
        
        System.out.println(a == b);        
    }
}
The code example illustrates the inexact nature of the floating point values.
double a = 0.1 + 0.1 + 0.1;
double b = 0.3;
We define two double values. The D/d suffix is optional. At first sight, they should be equal.
System.out.println(a);
System.out.println(b);
Printing them will show a very small difference.
System.out.println(a == b);  
This line will return false.
$ java com.zetcode.FloatingInPrecision 
0.30000000000000004
0.3
false
There is a small margin error. Therefore, the comparison operator returns a boolean false.
When we work with money, currency, and generally in business applications, we need to work with precise numbers. The rounding errors of the basic floating point types are not acceptable.
package com.zetcode;

public class CountingMoney {

    public static void main(String[] args) {
        
        float c = 1.46f;
        float sum = 0f;
        
        for (int i=0; i<100_000; i++) {
            
            sum += c;
        }
        
        System.out.println(sum);     
    }
}
The 1.46f represents 1 Euro and 46 Cents. We create a sum from 100000 such amounts.
for (int i=0; i<100_000; i++) {
    
    sum += c;
}
In this loop, we create a sum from 100000 such amounts of money.
$ java com.zetcode.CountingMoney 
146002.55
The calculation leads to an error of 55 Cents.
To avoid this margin error, we utilize the BigDecimal class. It is used to hold immutable, arbitrary precision signed decimal numbers.
package com.zetcode;

import java.math.BigDecimal;

public class CountingMoney2 {

    public static void main(String[] args) {
    
        BigDecimal c = new BigDecimal("1.46");
        BigDecimal sum = new BigDecimal("0");
        
        for (int i=0; i<100_000; i++) {
            
            sum = sum.add(c);
        }
        
        System.out.println(sum);                
    }
}
We do the same operation with the same amount of money.
BigDecimal c = new BigDecimal("1.46");
BigDecimal sum = new BigDecimal("0");
We define two BigDecimal numbers.
for (int i=0; i<100_000; i++) {
    
    sum = sum.add(c);
}
The BigDecimal number is immutable, therefore a new object is always assigned to the sum variable in every loop.
$ java com.zetcode.CountingMoney2 
146000.00
In this example, we get the precise value.
Java supports the scientific syntax of the floating point values. Also known as exponential notation, it is a way of writing numbers too large or small to be conveniently written in standard decimal notation.
package com.zetcode;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class ScientificNotation {

    public static void main(String[] args) {        
        
        double n = 1.235E10;                        
        DecimalFormat dec = new DecimalFormat("#.00");
        
        System.out.println(dec.format(n));        
        
        BigDecimal bd = new BigDecimal("1.212e-19");
        
        System.out.println(bd.toEngineeringString());
        System.out.println(bd.toPlainString());                          
    }
}
We define two floating point values using the scientific notation.
double n = 1.235E10;  
This is a floating point value of a double type, written in scientific notation.
DecimalFormat dec = new DecimalFormat("#.00");

System.out.println(dec.format(n));   
We use the DecimalFormat class to arrange our double value into standard decimal format.
BigDecimal bd = new BigDecimal("1.212e-19");

System.out.println(bd.toEngineeringString());
System.out.println(bd.toPlainString());  
The BigDecimal class takes a floating poing value in a scientific notation as a parameter. We use two methods of the class to print the value in the engineering and plain strings.
$ java com.zetcode.ScientificNotation 
12350000000.00
121.2E-21
0.0000000000000000001212
This is the example output.

Enumerations

Enumerated type (also called enumeration or enum) is a data type consisting of a set of named values. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. Enumerations make the code more readable. Enumerations are useful when we deal with variables that can only take one out of a small set of possible values.
package com.zetcode;

public class Enumerations {

    enum Days {

        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY,
        SUNDAY
    }

    public static void main(String[] args) {

        Days day = Days.MONDAY;

        if (day == Days.MONDAY) {
            
            System.out.println("It is Monday");
        }

        System.out.println(day);        

        for (Days d : Days.values()) {
            
            System.out.println(d);
        }
    }
}
In our code example, we create an enumeration for week days.
enum Days {

    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
An enumeration representing the days of a week is created with a enum keyword. Items of an enumeration are constants. By convention, constants are written in uppercase letters.
Days day = Days.MONDAY;
We have a variable called day which is of enumerated type Days. It is initialized to Monday.
if (day == Days.MONDAY) {
    
    System.out.println("It is Monday");
}
This code is more readable than if comparing a day variable to some number.
System.out.println(day);
This line prints Monday to the console.
for (Days d : Days.values()) {
    
    System.out.println(d);
}
This loop prints all days to the console. The static values() method returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants with the enhanced for statement. The enhanced for goes through the array, element by element, and prints them to the terminal.
It is Monday
MONDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
This is the example output.

Strings and chars

A String is a data type representing textual data in computer programs. A string in Java is a sequence of characters. A char is a single character. Strings are enclosed by double quotes.
Since strings are very important in every programming language, we will dedicate a whole chapter to them. Here we only drop a small example.
package com.zetcode;

public class StringsChars {

    public static void main(String[] args) {

        String word = "ZetCode";

        char c = word.charAt(0);
        char d = word.charAt(3);

        System.out.println(c);
        System.out.println(d);
    }
}
The program prints Z character to the terminal.
String word = "ZetCode";
Here we create a string variable and assign it "ZetCode" value.
char c = word.charAt(0);
The charAt() method returns the char value at the specified index. The first char value of the sequence is at index 0, the next at index 1, and so on.
$ java com.zetcode.StringsChars 
Z
C
The program prints the first and the fourth character of the "ZetCode" string to the console.

Arrays

Array is a complex data type which handles a collection of elements. Each of the elements can be accessed by an index. All the elements of an array must be of the same data type.
We dedicate a whole chapter to arrays; here we show only a small example.
package com.zetcode;

public class ArraysExample {

    public static void main(String[] args) {

        int[] numbers = new int[5];

        numbers[0] = 3;
        numbers[1] = 2;
        numbers[2] = 1;
        numbers[3] = 5;
        numbers[4] = 6;

        int len = numbers.length;

        for (int i = 0; i < len; i++) {
            
            System.out.println(numbers[i]);
        }
    }
}
In this example, we declare an array, fill it with data and then print the contents of the array to the console.
int[] numbers = new int[5];
We create an integer array which can store up to 5 integers. So we have an array of five elements, with indexes 0..4.
numbers[0] = 3;
numbers[1] = 2;
numbers[2] = 1;
numbers[3] = 5;
numbers[4] = 6;
Here we assign values to the created array. We can access the elements of an array by the array access notation. It consists of the array name followed by square brackets. Inside the brackets we specify the index to the element that we want.
int len = numbers.length;
Each array has a length property which returns the number of elements in the array.
for (int i = 0; i < len; i++) {
    
    System.out.println(numbers[i]);
}
We traverse the array and print the data to the console.
$ java com.zetcode.ArraysExample 
3
2
1
5
6
This is the output of the com.zetcode.ArraysExample program.

Java Basics

In this part of the Java tutorial, we will cover basic programming concepts of the Java language. We begin with some simple programs. We will work with variables, constants and basic data types. We will read and write to the console. We will mention variable interpolation. 

We start with a very simple code example. The following code is put into Simple.java file. The naming is important here. A public class of a Java program must match the name of the file.
package com.zetcode;

public class Simple {

    public static void main(String[] args) {
        
        System.out.println("This is Java");
    }
}
Java code is strictly organized from the very beginning. A file of a Java code may have one or more classes, out of which only one can be declared public.
package com.zetcode;
Packages are used to organize Java classes into groups, which usually share similar functionality. Packages are similar to namespaces and modules in other programming languages. For a simple code example, a package declaration may be omitted. This will create a so called default package. However, in this tutorial we will use a package for all examples. Another important thing is that a directory structure must reflect the package name. In our case the source file Simple.java with a package com.zetcode must be placed into a directory named com/zetcode/. The package statement must be the first line in the source file.
public class Simple {

   ...
}
A class is a basic building block of a Java program. The public keyword gives unrestricted access to this class. The above code is a class definition. The definition has a body that starts with a left curly brace { and ends with a right curly brace }. Only one class can be declared public in one source file. Also note the name of the class. Its name must match the file name. The source file is called Simple.java and the class Simple. It is a convention that the names of classes start with an uppercase letter.
public static void main(String[] args) {
    ...
}
The main() is a method. A method is a piece of code created to do a specific job. Instead of putting all code into one place, we divide it into pieces called methods. This brings modularity to our application. Each method has a body in which we place statements. The body of a method is enclosed by curly brackets. The specific job for the main() method is to start the application. It is the entry point to each console Java program. The method is declared to be static. This static method can be called without the need to create an instance of the Java class. First we need to start the application and after that, we are able to create instances of classes. The void keyword states that the method does not return a value. Finally, the public keyword makes the main() method available to the outer world without restrictions. These topics will be later explained in more detail.
System.out.println("This is Java");
In the main() method, we put one statement. The statement prints the "This is Java" string to the console. Each statement must be finished with a semicolon (;) character. This statement is a method call. We call the println() method of the System class. The class represents the standard input, output, and error streams for console applications. We specify the fully qualified name of the println() method.
$ pwd
/home/janbodnar/programming/java/basics/simple
$ javac com/zetcode/Simple.java
Java source code is placed into files with the .java extension. The javac tool is the Java compiler. We compile the Java source into Java classes. Note the directory structure. The structure must match the Java package.
$ ls com/zetcode/
Simple.class  Simple.java  Simple.java~
After we compile the source, we get a Java class file with the .class extension. It contains a Java bytecode which can be executed on the Java Virtual Machine (JVM). Simple.class is a Java program which can be executed with the java tool.
$ java com.zetcode.Simple 
This is Java
We execute the program with the java tool. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method. The parameter to the java tool is the fully qualified name of the Java class. Note that the .class extension is omitted.

Reading values

The second example will show, how to read a value from a console.
package com.zetcode;

import java.util.Scanner;

public class ReadLine {

    public static void main(String[] args) {
        
        System.out.print("Write your name:");

        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();

        System.out.println("Hello " + name);
    }
}
A prompt is shown on the terminal window. The user writes his name on the terminal and the value is read and printed back to the terminal.
import java.util.Scanner;
The Java standard library has a huge collection of classes available for programmers. They are organized inside packages. The Scanner class is one of them. When we import a class with the import keyword, we can refer later to the class without the full package name. Otherwise we must use the fully qualified name. The import allows a shorthand referring for classes. This is different from some other languages. For instance in Python, the import keyword imports objects into the namespace of a script. In Java, the import keyword only saves typing by allowing to refer to types without specifying the full name.
System.out.print("Write your name:");
We print a message to the user. We use the print() method which does not start a new line. The user then types his response next to the message.
Scanner sc = new Scanner(System.in);
A new instance of the Scanner class is created. New objects are created with the new keyword. The constructor of the object follows the new keyword. We put one parameter to the constructor of the Scanner object. It is the standard input stream. This way we are ready to read from the terminal. The Scanner is a simple text scanner which can parse primitive types and strings.
String name = sc.nextLine();
Objects have methods which perform certain tasks. The nextLine() method reads the next line from the terminal. It returns the result in a String data type. The returned value is stored in the name variable which we declare to be of String type.
System.out.println("Hello " + name);
We print a message to the terminal. The message consists of two parts. The "Hello " string and the name variable. We concatenate these two values into one string using the + operator. This operator can concatenate two or more strings.
$ java com.zetcode.ReadLine 
Write your name:Jan Bodnar
Hello Jan Bodnar
This is a sample execution of the second program.

Command line arguments

Java programs can receive command line arguments. They follow the name of the program when we run it.
package com.zetcode;

public class CommandLineArgs {

    public static void main(String[] args) {
        
        for (String arg : args) {
            
            System.out.println(arg);
        }
    }
}
Command line arguments can be passed to the main() method.
public static void main(String[] args)
The main() method receives a string array of command line arguments. Arrays are collections of data. An array is declared by a type followed by a pair of square brackets []. So the String[] args construct declares an array of strings. The args is an parameter to the main() method. The method then can work with parameters which are passed to it.
for (String arg : args) {
    
    System.out.println(arg);
}
 
We go through the array of these arguments with a for loop and print them to the console. The for loop consists of cycles. In this case, the number of cycles equals to the number of parameters in the array. In each cycle, a new element is passed to the arg variable from the args array. The loop ends when all elements of the array were passed. The for statement has a body enclosed by curly brackets {}. In this body, we place statements that we want to be executed in each cycle. In our case, we simply print the value of the arg variable to the terminal. Loops and arrays will be described in more detail later.
$ java com.zetcode.CommandLineArgs 1 2 3 4 5
1
2
3
4
5
We provide four numbers as command line arguments and these are printed to the console.
When we launch programs from the command line, we specify the arguments right after the name of the program. In Integraged Development Environments (IDE) like Netbeans, we specify these parameters in a dialog. In Netbeans, we rigth click on the project and select Properties. From the Categories list, we select the Run option. In the Arguments edit control, we write our arguments.
Command line arguments
Figure: Command line arguments

Variables

A variable is a place to store data. A variable has a name and a data type. A data type determines what values can be assigned to the variable. Integers, strings, boolean values etc. Over the time of the program, variables can obtain various values of the same data type. Variables in Java are always initialized to the default value of their type before any reference to the variable can be made.
package com.zetcode;

public class Variables {

    public static void main(String[] args) {
        
        String city = "New York";
        String name = "Paul"; int age = 34;
        String nationality = "American";

        System.out.println(city);
        System.out.println(name);
        System.out.println(age);
        System.out.println(nationality);

        city = "London";
        System.out.println(city);
    }
}
In the above example, we work with four variables. Three of the variables are strings. The age variable is an integer. The int keyword is used to declare an integer variable.
String city = "New York";
We declare a city variable of the string type and initialize it to the "New York" value.
String name = "Paul"; int age = 34;
We declare and initialize two variables. We can put two statements into one line. Since each statement is finished with a semicolon, the Java compiler knows that there are two statements in one line. But for readability reasons, each statement should be on a separate line.
System.out.println(city);
System.out.println(name);
System.out.println(age);
System.out.println(nationality);
We print the values of the variables to the terminal.
city = "London";
System.out.println(city);
We assign a new value to the city variable and later print it.
$ java com.zetcode.Variables 
New York
Paul
34
American
London
This is the output of the example.

Constants

Unlike variables, constants cannot change their initial values. Once initialized, they cannot be modified. Constants are created with the final keyword.
package com.zetcode;

public class Constants {

    public static void main(String[] args) {
        
        final int WIDTH = 100;
        final int HEIGHT= 150;
        int var = 40;

        var = 50;
        
        //WIDTH = 110;        
    }
}
In this example, we declare two constants and one variable.
final int WIDTH = 100;
final int HEIGHT= 150;
We use the final keyword to inform the compiler that we declare a constant. It is a convention to write constants in uppercase letters.
int var = 40;

var = 50;
We declare and initialize a variable. Later, we assign a new value to the variable. It is legal.
// WIDTH = 110;
Assigning new values to constants is not possible. If we uncomment this line, we will get a compilation error: "Uncompilable source code - cannot assign a value to final variable WIDTH".

String formatting

Building strings from variables is a very common task in programming. Java language has the System.format() method to format strings.
Some dynamic languages like Perl, PHP or Ruby support variable interpolation. Variable interpolation is replacing variables with their values inside string literals. Java language does not allow this. It has string formatting insted.
package com.zetcode;

public class StringFormatting 
{
    public static void main(String[] args) 
    {
        int age = 34;
        String name = "William";

        String output = String.format("%s is %d years old.", name, age);
        
        System.out.println(output);
    }
}
In Java, strings are immutable. We cannot modify an existing string. We must create a new string from existing strings and other types. In the code example, we create a new string. We also use values from two variables.
int age = 34;
String name = "William";
Here we have two variables, one integer and one string.
String output = String.format("%s is %d years old.", name, age);
We use the format() method of the built-in String class. The %s and %d are control characters which are later evaluated. The %s accepts string values, the %d integer values.
$ java com.zetcode.StringFormatting 
William is 34 years old.
This is the output of the example.

Monday, February 3, 2014

Lexical structure Java

Computer languages, like human languages, have a lexical structure. A source code of a Java program consists of tokens. Tokens are atomic code elements. In Java we have comments, identifiers, literals, operators, separators and keywords. 

Java programs are composed of characters from the Unicode character set.

Comments

Comments are used by humans to clarify source code. There are three types of comments in Java.
Comment typeMeaning
// commentSingle-line comments
/* comment */Multi-line comments
/** documentation */Documentation comments
If we want to add some small comment we can use single-line comments. For more complicated explanations, we can use multi-line comments. The documentation comments are used to prepare automatically generated documentation. This is generated with the javadoc tool.
package com.zetcode;

/*
  This is Comments.java 
  Author: Jan Bodnar
  ZetCode 2013
*/

public class Comments {

    // Program starts here
    public static void main(String[] args) {

        System.out.println("This is Comments.java");
    }
}
Comments are ignored by the Java compiler.
/*
  This is Comments.java 
/*  Author: Jan Bodnar */
  ZetCode 2013
*/
Comments cannot be nested. The above code does not compile.

White space

White space in Java is used to separate tokens in the source file. It is also used to improve readability of the source code.
int i = 0;
White spaces are required in some places. For example between the int keyword and the variable name. In other places, white spaces are forbidden. They cannot be present in variable identifiers or language keywords.
int a=1;
int b = 2;
int c  =  3;
The amount of space put between tokens is irrelevant for the Java compiler.

Identifiers

Identifiers are names for variables, methods, classes or parameters. Identifiers can have alphanumerical characters, underscores and dollar signs ($). It is an error to begin a variable name with a number. White space in names is not permitted. 

Identifiers are case sensitive. This means, that Name, name or NAME refer to three different variables. Identifiers also cannot match language keywords. 

There are also conventions related to naming of identifiers. The names should be descriptive. We should not use cryptic names for our identifiers. If the name consists of multiple words, each subsequent word is capitalized.
String name23;
int _col;
short car_age;
These are valid Java identifiers.
String 23name;
int %col;
short car age;
These are invalid Java identifiers.
The following program demonstrates that the variable names are case sensitive. Event though the language permits this, it is not a recommended practice to do.
package com.zetcode;

public class CaseSensitiveIdentifiers {

    public static void main(String[] args) {
        
        String name = "Robert";
        String Name = "Julia";

        System.out.println(name);
        System.out.println(Name);       
    }
}
Name and name are two different identifiers. In Visual Basic, this would not be possible. In this language, variable names are not case sensitive.
$ java com.zetcode.CaseSensitiveIdentifiers 
Robert
Julia

Literals

A literal is a textual representation of a particular value of a type. Literal types include boolean, integer, floating point, string, null, or character. Technically, a literal will be assigned a value at compile time, while a variable will be assigned at runtime.
int age = 29;
String nationality = "Hungarian";
Here we assign two literals to variables. Number 29 and string "Hungarian" are literals.
package com.zetcode;

public class Literals {

    public static void main(String[] args) {

        int age = 23;
        String name = "James";
        boolean sng = true;
        String job = null;
        double weight = 68.5;
        char c = 'J';

        System.out.format("His name is %s%n", name);
        System.out.format("His is %d years old%n", age);

        if (sng) {
            
            System.out.println("He is single");
        } else {
            
            System.out.println("He is in a relationship");
        }

        System.out.format("His job is %s%n", job);
        System.out.format("He weighs %f kilograms%n", weight);
        System.out.format("His name begins with %c%n", c);
    }
}
In the above example, we have several literal values. 23 is an integer literal. "James" is a string literal. The true is a boolean literal. The null is a literal that represents a missing value. 68.5 is a floating point literal. 'J' is a character literal.
$ java com.zetcode.Literals 
His name is James
His is 23 years old
He is single
His job is null
He weighs 68.500000 kilograms
His name begins with J
This is the output of the program.

Operators

An operator is a symbol used to perform an action on some value. Operators are used in expressions to describe operations involving one or more operands.
+    -    *    /    %    ^    &    |    !    ~
=    +=   -=   *=   /=   %=    ^=    ++    --
==   !=    <   >    &=  >>=   <<=   >=   <= 
||   &&    >>    <<    ?:
This is a partial list of Java operators. We will talk about operators later in the tutorial.

Separators

A separator is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data stream.
[ ]   ( )   { }   ,   ;   . 
String language = "Java";
The double quotes are used to mark the beginning and the end of a string. The semicolon (;) character is used to end each Java statement.
System.out.println("Java language");
Parentheses (round brackets) always follow a method name. Between the parentheses we declare the input parameters. The parentheses are present even if the method does not take any parameters. The System.out.println() method takes one parameter, a string value. The dot character separates the class name (System) from the member (out) and the member from the method name (println()).
int[] array = new int[5] { 1, 2, 3, 4, 5 };
The square brackets [] are used to denote an array type. They are also used to access or modify array elements. The curly brackets {} are also used to initiate arrays. The curly brackets are also used enclose the body of a method or a class.
int a, b, c;
The comma character separates variables in a single declaration.

Keywords

A keyword is a reserved word in Java language. Keywords are used to perform a specific task in the computer program. For example, define variables, do repetitive tasks or perform logical operations.
Java is rich in keywords. Many of them will be explained in this tutorial.
abstract        continue        for             new             switch 
assert          default         goto            package         synchronized
boolean         do              if              private         this
break           double          implements      protected       throw
byte            else            import          public          throws
case            enum            instanceof      return          transient
catch           extends         int             short           try
char            final           interface       static          void
class           finally         long            strictfp        volatile
const           float           native          super           while
In the following small program, we use several Java keywords.
package com.zetcode;

public class Keywords {

    public static void main(String[] args) {

        for (int i = 0; i <= 5; i++) {
            
            System.out.println(i);
        }
    }
}
The package, public, class, static, void, int, for tokens are Java keywords.

Conventions

Conventions are best practices followed by programmers when writing source code. Each language can have its own set of conventions. Conventions are not strict rules; they are merely recommendations for writing good quality code. We mention a few conventions that are recognized by Java programmers. (And often by other programmers too).
  • Class names begin with an uppercase letter
  • Method names begin with a lowercase letter
  • The public keyword precedes the static keyword when both are used
  • The parameter name of the main() method is called args
  • Constants are written in uppercase
  • Each subsequent word in an identifier name begins with a capital letter
In this part of the Java tutorial, we covered some basic lexis for the Java language.

Java language

Java is a high-level, general-purpose, object-oriented programming language. The main design goals of the language were robustness, portability, high performance and security. Java is a multithreaded and distributed programming language. It can be used to create console applications, GUI applications, web applications, both on PCs or embedded systems.

Java is a programming language created by Sun Microsystems in 1991. The first publicly available version of Java was released in 1995. Today, the language is developed by Oracle corporation.
Java excels in creating portable mobile applications, programming various appliances and in creating enterprise applications.

Popularity

There are currently several widely used programming languages. Java belongs to the most popular languages today. Several surveys put it into the top three languages in the world.

Java platforms

Java has four programming platforms:
  • Java Platform, Standard Edition (Java SE)
  • Java Platform, Enterprise Edition (Java EE)
  • Java Platform, Micro Edition (Java ME)
  • JavaFX
All Java platforms consist of a Java Virtual Machine (JVM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java applications. An API is a collection of software components that we can use to create other software components or applications.

Java SE is used for developing desktop applications. Java SE's API provides the core functionality of the Java programming language. It consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits used in Java applications. Java EE is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running web applications and large-scale, multi-tiered, scalable, reliable, and secure enterprise applications. Java ME is a subset of the Java SE. It provides an API and a small-footprint virtual machine for running Java applications on small devices, like mobile phones. JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. 

In our tutorial, we use the Java SE platform to create simple console applications.

JDK

Strictly speaking, Java SE is a platform specification. Java Platform, Standard Edition Development Kit (JDK) is an official implementation of the Java SE by Oracle. There are also other implementations. For example free and open source OpenJDK or IBM's J9.
$ ls jdk1.7.0_02/
bin        db       jre  LICENSE  README.html  src.zip
COPYRIGHT  include  lib  man      release      THIRDPARTYLICENSEREADME.txt
After we dowload and unpack the Oracles's JDK, we can see the contents of the JDK in the our jdk1.7.0_02 directory. The development tools are located in the bin/ subdirectory. The Java javac compiler and the java application launcher are located in this subdirectory. The jre/ subdirectory contains the JVM, class libraries and other files that help execute Java programs. The lib/ subdirectory has some additional class libraries and support files. The db/ subdirectory contains the Java DB, which is the Oracle's distribution of the Apache Derby database. In the include/ subdirectory we can find header files that support native-code programming. The src.zip file contains source files for all classes that make up the Java core API.

JVM

Java virtual machine (JVM) is a program that can execute Java bytecode. The JVM is included in the JDK. Java source code is written in files with the .java extension. The javac Java compiler will compile the Java source code into the Java bytecode; the compiled files have the .class extension. This bytecode is executed by JVM. The java tool is a launcher for Java applications. Oracle's JVM is called HotSpot. HotSpot is a Java virtual machine for desktops and servers. It has advanced techniques such as just-in-time compilation and adaptive optimization designed to improve performance.

Compiling a simple program

In order to develop Java applications, we need to dowloand a JDK. Oracle's official JDK can be downloaded from this dowload page.
$ mkdir -p com/zetcode
Inside the current working directory, we create a com/zetcode/ subdirectory. Java source files are organized in modules called packages. The packages must match the directory structure.
$ touch com/zetcode/SimpleExample.java
A SimpleExample.java source file is created in the com/zetcode/ subdirectory. Java source files have a .java extension.
package com.zetcode;

public class SimpleExample {

    public static void main(String[] args) {

        System.out.println("This is simple Java example.");
    }
}
This is a source code for a simple Java example. This example prints a message to the console.
package com.zetcode; 
The package name must correspond to the directory structure in which the source file is located.
public class SimpleExample { 
The public class name is required to match the file name.
$ javac com/zetcode/SimpleExample.java 
Using the javac compiler, we compile the source code.
$ ls com/zetcode/
SimpleExample.class  SimpleExample.java
The compiler generetes a Java bytecode, which is executed by the Java Virtual Machine. The bytecode has a .class extension.
$ java com.zetcode.SimpleExample 
This is simple Java example.
With the java application launcher, we execute the program. It starts a Java runtime environment, loading a specified class, and invoking that class's main method. The .class extension is excluded; it is assumed. The program name is a fully qualified name of the program - com.zetcode.SimpleExample. It includes the name of the program and its package.