Sabado, Enero 26, 2013

Arithmetic Operators and Operator Precedence


Arithmetic Operators and Operator Precedence

There are five arithmetic operators:

+          addition
-           subtraction
*          multiplication
/           division
%         mod (modulus) operator

You can use these operators with both integral and floating-point data types. Integral division truncates any fractional part; there is no rounding.

An arithmetic expression is constructed by using arithmetic operators and numbers. The numbers in the expression are called operands. Moreover, the numbers used to evaluate an operator are called the operands for that operator. Operators that have only one operand are called unary operators.  Operators that have two operands are called binary operators.


Order of Precedence

Java uses operator precedence rules to determine the order in which operations are performed to evaluate the expression.  According to the order of precedence rules for arithmetic operators, *, /, and % have a higher level of precedence than + and -. 

Because arithmetic operators are evaluated from left to right, unless parentheses are present, the associativity of arithmetic operators is said to be from left to right.

Since the char data type is also an integral data type, Java allows you to perform arithmetic operations on char data.


Expressions

If all operands in an expression are integers, the expression is called an integral expression. If all operands in an expression are floating-point numbers, the expression is called a floating-point or decimal expression

Evaluating an integral or a floating-point expression is straightforward. When operators have the same precedence, the expression is evaluated from left to right. To avoid confusion you can always use parentheses to group operands and operators.

boolean Data Type, Floating-Point Data Types


boolean Data Type

The data type boolean has only two values: true and false. These are called thelogical (Boolean) values. The central purpose of this data type is to manipulate logical (Boolean) expressions.

An expression that evaluates to true or false is called a logical (Boolean) expression.


Floating-Point Data Types

The floating-point data type deals with decimal numbers.  To represent real numbers, Java uses a form of scientific notation called floating-point notation

The data types float and double are used to manipulate decimal numbers. Floats represent any real number between –3.4E+38 and 3.4E+38.  The memory allocated for the float data type is 4 bytes. Doubles are used to represent any real number between –1.7E+308 and 1.7E+308. The memory allocated for the double data type is 8 bytes.

The maximum number of significant digits in float values is 6 or 7, while the maximum number of significant digits in double values is 15.

int Data Type, char Data Type


int Data Type

Positive integers do not have to have a + sign in front of them. No commas are used within an integer.


char Data Type

The char data type is used to represent single characters such as letters, digits, and special symbols. It can represent any key on your keyboard. Each character represented is enclosed within single quotation marks. Only one symbol can be placed between the single quotation marks.

Java uses the Unicode character set, which contains 65536 values numbered 0 to 65535. Each of the 65536 values of the Unicode character set represents a different character. Each character has a predefined ordering, which is called acollating sequence, in the set.  This is used when you compare characters

Primitive Data Types,


Primitive Data Types

There are three primitive data types: integral, floating-point, and boolean.

The integral data type deals with integers, or numbers without a decimal part.  It is classified into five categories: char, byte, short, int, long. The int data type can represent integers between
-2147483648 and 2147483647. The data type short is used to represent integers between –32768 and 32767.

The floating-point data type deals with decimal numbers.

The boolean data type deals with logical values.

Identifiers, and Data Types


Identifiers


Identifiers are names of things, such as variables, constants, and methods, that appear in programs. A Java identifier consists of letters, digits, the underscore character ( _), and the dollar sign ($), and must begin with a letter, underscore, or the dollar sign.


Data Types

The objective of a Java program is to manipulate data.  Data type is a set of values together with a set of operations. Only certain operations can be performed on a particular type of data.

Special Symbolsm and Word Symbols


Special Symbols

The following are special symbols in Java.

+          -           *          /
.           ;           ?          ,
<=        !=         ==        >=

The first row of symbols includes mathematical symbols for addition, subtraction, multiplication, and division. In Java, commas are used to separate items in a list. Semicolons are used to end a Java statement.  The symbols in the third row are used for comparisons.


Word Symbols

Word symbols are called reserved words or keywords. Examples include int, float, double, char, void, public, static, throws, return.

The Basics of a Java Program


The Basics of a Java Program


A programming language is a set of rules, symbols, and special words.  Thesyntax rules of a language determine which instructions are valid.  The semantic rules determine the meaning of the instructions.  Together these rules enable you to write programs to solve problems.

The smallest individual unit of a program written in any programming language is called a token. Java’s tokens are divided into special symbols, word symbols, and identifiers.

Computer Program

Computer Program

A computer program, or a program, is a sequence of statements whose objective is to accomplish a task. Programming is a process of planning and creating a program.  Learning a programming language requires direct interaction with the tools. You must have a fundamental knowledge of the language, and you must test your programs on the computer to make sure that each program does what it is supposed to do.

Java Core Training of Prof. Erwin M. Globio

Java Core Training of Prof. Erwin M. Globio





Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about JavaProgramming Secrets. 






For more free information about Java and Java Training visit the following sites: http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.

Running HelloWorld


Running HelloWorld

If the build worked perfectly you now have a HelloWorld.jar and a HelloWorld.jad file pair in your dist directory. Using your emulator, instruct it to open the JAD file and you should see something similar to the below image…
Image of Hello World running in MPowerPlayer
helloworld-emulator.png

In Closing
In this article you learned how to develop, deploy and test your first MIDlet. But this is just the beginning of your journey to become a great J2ME developer. This site continues to grow and provide tips and techniques for both beginners and experts alike and I also recommend theJ2MEForums for finding quick answers from programmers of all calibres.

JAD Updating, and Automating the build process with ANT


JAD Updating

The JAD file has its contents updated to reflect the properties of the JAR file.

Automating the build process with ANT

ANT can be used to perform all of the build steps in sequence saving you much time and effort. The source code download also includes a sample ANT build script.
build.xml
<project name="helloworld" default="dist" basedir="." >
        <property name="app.name" value="helloworld" />
        <property name="app.path" value="/${app.name}"  />
        <property name="build.home" value="${basedir}/build" />
        <property name="lib.home" value="${basedir}/lib" />
        <property name="dist.home" value="${basedir}/dist" />
        <property name="src.home" value="${basedir}/src" />
        <property name="compile.debug" value="true" />
        <property name="compile.deprecation" value="false" />
        <property name="compile.optimize" value="true" />

        <target name="all" depends="dist" description="Clean build and dist directories, then compile" />

        <target name="clean" description="Delete old build directory">
               <delete dir="${build.home}" />
        </target>

        <target name="compile" description="Compile Java sources">
               <javacsrcdir="${src.home}" destdir="${build.home}" debug="${compile.debug}" deprecation="${compile.deprecation}" optimize="${compile.optimize}">
                       <classpath>
                               <filesetdir="${lib.home}" includes="*.jar,*.zip" />
                       </classpath>
                       <include name="**/*.java"/>
               </javac>
        </target>

        <target name="bundle" depends="compile" description="Takes the built objects and makes a JAR file.">
               <mkdirdir="${build.home}/META-INF"/>
               <copy todir="${build.home}/META-INF">
                       <filesetdir="META-INF" includes="**/*.MF" />
               </copy>
               <jar jarfile="${dist.home}/HelloWorld.jar" basedir="${build.home}" includes="**/*.class" />
        </target>

        <target name="preverify" depends="bundle" description="Preverifies the JAR file.">
               <exec dir="${dist.home}" executable="<path-to-project>/dist/preverify">
                       <arg line="-d ${dist.home} -classpath ${lib.home}/cldcapi11.jar:${lib.home}/midpapi20.jar ${dist.home}/HelloWorld.jar"/>
               </exec>
        </target>

        <target
               name="dist"
               depends="preverify"
               description="Create binary distribution">

               <exec dir="${dist.home}" executable="java">
                       <arg line="-cp %CLASSPATH%;.;.. -jar JammedUp.jar HelloWorld.jad -b -d -s"/>
               </exec>

        </target>

</project>

Preverification


Preverification

Unlike J2SE classes J2ME classes must have their contents preverified prior to execution on the device. This is compensation for the limited processing power of mobile devices. This stage includes checks for illegal bytecode or constructs not supported by J2ME.
The preverify tool comes with most emulators and for Mac users the MPowerPlayer offers an OS X compatible binary.

Rewind :: The Build Process Compilation, and JARing


Rewind :: The Build Process
Compilation

Either performed automatically by an IDE or done by hand or automated via ANT. The end result is a set of class files. In this example there should be two files: HelloWorld.class, and HelloWorldCanvas.class.


JARing
The project classes, the manifest and resource files are bundled into one file: HelloWorld.jar.

Directory Structure


Directory Structure

If you are intending on using the ANT build script I provide below to automate your project’s build then all of these files must appear in a particular hierarchy. Below is an image of that hierarchy. Ensure that the files are placed in the proper directories.
The Directory Structure
helloworld-folder-layout.png
Although I discuss each of build steps in detail below I want to briefly explain the directory structure’s purpose.
The src directory is where the two java files are located.
When compiled the resulting class files will be placed in the build directory along with the MANIFEST.MF file which is copied from the META-INF directory.
The lib directory houses the two main J2ME library JAR files that are needed for our project.
Upon JARring the project, the files located in the build folder will be archived and the resulting JAR files will be placed in the dist folder where the JAD file is normally housed. It is here that preverify and JammedUp process the JAR file and update the JAD file.
This is by no means the only way to layout your project’s files but it’s a basic one that has worked well for me many times.

Fast forward :: The structure of a Completed MIDlet: The Manifest


3. The Manifest

All MIDP compatible MIDlets must include a MANIFEST.MF file residing in the META-INF directory of the JAR file. This file reasserts some of the basic settings found in the JAD file for validation purposes and is provided in the properties file format.
MANIFEST.MF
MIDlet-Name: HelloWorld
MIDlet-Version: 1.0
MIDlet-Vendor: VENDOR-NAME-HERE
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
MIDlet-1: HelloWorld,,HelloWorld
At this point you don’t need to worry too much about the contents of the JAD and manifest files. I’ll be devoting an article to their maintenance in the near future. For the purposes of this article you need only know that they are essential files for running any MIDlet.

Fast forward :: The structure of a Completed MIDlet: The JAD file


2. The JAD file

A JAD file is a lightweight proprties file in the which is offered to the target device prior to commiting to the full JAR download. It informs the device of the size of the MIDlet and any expectations and requirements it has of the device.
As the JAR files size must be mentioned and since it always changes during development it is advised to use JammedUp to automate this process with each build.
HelloWorld.jad
MIDlet-Name: HelloWorld
MIDlet-Version: 1.0
MIDlet-Vendor: VENDOR-NAME-HERE
MIDlet-Jar-URL: HelloWorld.jar
MIDlet-Jar-Size: 1523
MIDlet-1: HelloWorld,,HelloWorld
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
MIDlet-Data-Size: 0
build: 1
Last-Modified: 2007-04-09 08:17:25

Fast forward :: The structure of a Completed MIDlet: The JAR file


Fast forward :: The structure of a Completed MIDlet

Besides java files there are a minimum of 3 files required to build a MIDlet.

1. The JAR file
Anyone who has created a WebStart application or a server-side web application in Java will have come into contact with JAR files. They are essentially the same as ZIP archives and in the J2ME world they serve to compress the MIDlet as best as possible. They include the classes that constitute the MIDlet, and any resources such as images and data files used.

Connecting the Canvas to the MIDlet.


Connecting the Canvas to the MIDlet.

Since the entry class of any MIDlet must extend the MIDlet class it cannot extend the Canvas class we just created (no multiple inheritence in Java).
We need a MIDletimplementor class like the one below…
HelloWorld.java
importjavax.microedition.lcdui.Display;
importjavax.microedition.midlet.MIDlet;
importjavax.microedition.midlet.MIDletStateChangeException;

public class HelloWorld extends MIDlet {

        publicHelloWorld() {

        }

        protected void destroyApp(boolean conditional)
                       throwsMIDletStateChangeException {

        }

        protected void pauseApp() {

        }

        public void startApp() throws MIDletStateChangeException {

               Display.getDisplay(this).setCurrent(new HelloWorldCanvas());
        }
}
To recap, our entry class HelloWorld has its start method executed which sets our Canvas class HelloWorldCanvas to the currently displayed canvas (a MIDlet can have more than one Canvas). It then tells the canvas to begin drawing itself.

The canvas code

The canvas code

Translating the steps above to Java code gives us this…
HelloWorldCanvas.java
importjavax.microedition.lcdui.Canvas;
importjavax.microedition.lcdui.Graphics;

public class HelloWorldCanvas extends Canvas {

        protected void paint(Graphics g) {

               g.setColor(0, 0, 0);
               g.fillRect(0, 0, getWidth(), getHeight());
               g.setColor(255, 255, 255);
               g.drawString("Hello World!", 20, 20, Graphics.LEFT | Graphics.BOTTOM);
        }
}

Drawing Hello World :: The Rendering Process (in plain English)


Drawing Hello World :: The Rendering Process (in plain English)

Below are the steps required to draw “Hello World” on screen.
1. Set the current color to black
2. Fill the entire screen (using the current color)
3. Set the current color to white
4. Print “Hello World!” (using the current color and font)
So that Hello World’s font’s color is different from that of the screen we explicitly set both prior to filling the screen and printing our text. 

Getting Started: “Hello World” in J2ME


Getting Started: “Hello World” in J2ME

Whereas you write applications for the desktop and Applets for web browsers you write MIDlets for mobile devices.

Just as J2SE applications have an entry point (any class with a main() method) MIDlets have a class which extends the abstract MIDlet class. This class offers the startApp() method which will serve as the entry point to your MIDlet.

In J2SE, Hello World consists of merely System.out.println()-ing the static String “Hello World”. Unlike J2SE many J2ME devices do not have the concept of an on-screen console and as such we cannot avail ourselves of the System.out.println() method to print “Hello World” for us.

We must instead draw “Hello World” to a graphical canvas which we will then assign to be the currently displayed screen. If you’ve dabbled in AWT or Swing you likely have seen the Graphics object which acts as our paintbrush when painting to the Canvas. For those not familiar, the Graphics object is state-object with a current color, line-thickness, font etc…