+84 1649 660 740

Thursday 4 September 2014

* Question: Write a program in Java to check if a number is even or odd?
* Answer 1: Using the modulus operator.
(1). Create project: CheckEvenOddModulus 
(2). Create package: com.webmobileaz
(3). com.webmobileaz => File: Numbers.java



package com.webmobileaz;

import java.util.Scanner;

public class Numbers {
 public boolean isEven(int number) {
  return (number % 2 == 0);
 }
}

class Main {
 public static void main(String []args) {
  Scanner scan = new Scanner(System.in);
  System.out.print("Input a number: ");
  int number = scan.nextInt();
  
  Numbers num = new Numbers();
  if(num.isEven(number)) {
   System.out.println(number + " is Even");
  } else {
   System.out.println(number + " is Odd");
  } 
 }
}

Download Project: CheckEvenOddModulus 

* Answer 2You can use the modulus operator, but that can be slow. If it's an integer, you can use Bitwise AND operator
(1). Create project: CheckEvenOddBitwise
(2). Create package: com.webmobileaz
(3). com.webmobileaz => File: Numbers.java


package com.webmobileaz;

import java.util.Scanner;

public class Numbers {
 public boolean isEven(int number) {
  return ((number & 1) == 0);
 }
}

class Main {
 public static void main(String []args) {
  Scanner scan = new Scanner(System.in);
  System.out.print("Input a number: ");
  int number = scan.nextInt();
  
  Numbers num = new Numbers();
  if(num.isEven(number)) {
   System.out.println(number + " is Even");
  } else {
   System.out.println(number + " is Odd");
  } 
 }
}

Download Project: CheckEvenOddBitwise

Wednesday 3 September 2014


Android is everywhere: Phones, Tablets, TVs and set-top boxes powered by Google TV. Soon, Android will be in cars, in in-flight entertainment system on planes, and even in robots!

However, the general theme of Android devices will be smaller screens and/or no hardware keyboard. And, by the numbers, Android will probably be associated mostly with smartphones for the foreseeable future. For developers, this has both benefits and drawbacks.

On the plus side, Android-style smartphones are sexy. Offering Internet services over mobile devices dates back to the mid-1990s and Handheld Device Markup Language (HDML). However, only in recent years have phones capable of Internet access taken off. Now, thanks to trends like text messaging and products like Apple's iPhone, phones that can serve as Internet-access devices are rapidly gaining popularity. So, working on Android applications gives you experience with an interesting technology (Android) in a fast-moving market segment (Internet-enabled phones), which is always a good thing.

The problem comes when you actually have to program the darn things.

Anyone with experience in programming for PDAs or phones has felt the pain of phones simply being small in all sorts of dimensions:
  • Screens are small (you will not get comments like, "Is that a 24-inch LCD in your pocket, or...?").
  • Keyboards, if they exist, are small.
  • Pointing devices, if they exist, are annoying (as anyone who has lost their stylus will tell you) or inexact (large fingers and "multitouch" LCDs can sometimes be...problematic).
  • CPU speed and memory are always behind what's available on desktops and servers.
Moreover, applications running on a phone have to deal with the fact that they're on a phone.
People with mobile phones tend to get very irritated when those phones do not work. Similarly, those same people will get irritated if your program "breaks" their phones by:
  • Typing up the CPU such that call can't be received.
  • Not quietly fading into the background when a call comes in or needs to be placed, because the program doesn't work properly with the rest of the phone's operating system.
  • Crashing the phone's operating system, such as by leaking memory like a sieve.
Hence, developing programs for a phone is a different experience than developing desktop applications, web sites, or back-end server processes. The tools look different, the frameworks behave differently, and you have more limitations on what you can do with your programs.
What Android tries to do is meet you halfway:
  • You get a commonly used programming language (Java) with some commonly used libraries (e.g., some Apache Commons APIs), with support for tools you may be used to using (Eclipse).
  • You get fairly rigid and uncommon framework in which your programs need to run so they can be "good citizens" on the phone and not interfere with other programs or the operation of the phone itself.

Friday 29 August 2014

After you declare a variable, you must explicitly initialize it by means of an assignment statement - you can never use the value of an uninitialized variable. For example, the Java compiler flags the following sequence of statement as an error:

int vacationDays;
System.out.println(vacationDays); // Error - variable not initialized
You assign to previously declared variable by using the variable name on the left, an equal sign (=), and then some Java expression with an appropriate value on the right.

int vacationDays;
vacationDays = 12;
Finally, in Java you can put declarations anywhere in your code. For example, the following is valid code in Java:

double salary = 65000.0;
System.out.println(salary);
int vacationDays = 12; //OK to declare a variable here
In Java, it is considered good style to declare variables as closely as possible to the point where they are first used.

* Note: C/C++ distinguish between the declaration and definition of a variable. For example,

int i = 10;
is a definition, whereas

extern int i;
is a declaration. In Java, no declarations are separate from definitions.

Wednesday 27 August 2014

In Java, every variable has a type. You declare a variable by placing the type first, followed by the name of the variable. Here are some example:

double salary;
int vacationDays;
long earthPopulation;
boolean done;
Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.

A variable name must begin with a letter and must be a sequence of letters or digits. Note that the terms "letter" and "digit" are much broader in Java than is most languages. A letter is defined as 'A'  -  'Z', 'a' - 'z', '_', '$', or any Unicode character the denotes a letter in a language. For example, German users can use umlauts such as 'ä' in variable names; Greek speakers could use a π. Similarly, digit are '0' - '9' and any Unicode characters that denote a digit in a language. Symbols like '+' or '©' cannot be used inside variable names, nor can spaces. All characters in the name of a variable are significant and case is also significant. The length of a variable name is essentially unlimited.

* Note: If you are really curious as to what Unicode characters are "letters" as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.

* Note: Even though $ is a valid Java letter, you should not use it in your own code. It is intended for names that are generated by the Java compiler and other tools.

You also cannot use a Java reserved word for a variable name.

You can have multiple declarations on a single line:

 int i, j; //both are integers
However, we don'recommend this style. If you declare each variable separately, your programs are easier to read.

* Note: As you saw, names are case sensitive, for example, hireday and hireDay are two separate names. In general, you should not have two names that only differ in their letter case. However, sometimes it is difficult to come up with a good name for a variable. Many programmers then give the variable the same name as the type, for example:

 Box box; //"Box" is the type and "box" is the variable name
Other programmers perfer to use an "a" prefix for the variable:
 Box aBox;
The boolean type has two values, false and true. It is used for evaluating logical conditions. You cannot convert between integers and boolean values.

* Note: In C++, numbers and even pointers can be used in place of boolean values. The value 0 is equivalent to the bool value false, and a non-zero value is equivalent true. This is not the case in Java. Thus, Java programmers are shielded from accidents such as

 if (x = 0) // oops... meant x == 0
In C++, this test compiles and runs, always evaluating to false. In Java, the test does not compile because the integer expression x = 0 cannot be converted to a boolean value.

* Example:
=> File: booleanType.java

 package com.webmobileaz;

import java.util.Scanner;

public class booleanType {
 public static void main (String []args) {
  
  Scanner scran = new Scanner(System.in);
  boolean b = scran.nextBoolean();
  if(b == true) {
   System.out.println("Hello!");
  } else {
   System.out.println("Hehe Hihi!");
  }
 }
}

=> Result:
(1). If you input: true
 Hello!

(2). If you input: false
 Hehe Hihi!

(3). Other -> Exception
Exception in thread "main" java.util.InputMismatchException
 at java.util.Scanner.throwFor(Scanner.java:864)
 at java.util.Scanner.next(Scanner.java:1485)
 at java.util.Scanner.nextBoolean(Scanner.java:1782)
 at com.webmobileaz.booleanType.main(booleanType.java:9)


View Project

Download Project
The char type is used to describe individual characters. Most commonly, these will be character constants. For example, 'A' is a character constant with value 65. It is different from "A", a string containing a single character. Unicode code units can be expressed as hexadecimal values that run from \u0000 to \uFFFF. For example, \u03c0 is the Greek letter pi.

Besides the \u escape sequences that indicate the encoding of Unicode code units, there are several escape sequences for special characters.

Escape sequenceNameUnicode value
\bBackspace\u0008
\tTab\u0009
\nLinefeed\u000a
\rCarriage return\u000d
\"Double quote\u0022
\'Single quote\u0027
\\Backslash\u005c

You can use these escape sequences inside quoted character constants and strings, such as '\u2122' or "Hello\n". The \u escape sequence (but none of the other escape sequences) can even be used outside quoted character constants and strings. For example:

 public static void main(String \u0055B\u005D args)
is perfectly legal \u005B and \u005D are the encoding for [ and ].

To fully understand the char type, you have to know about the Unicode encoding scheme. Unicode was invented to overcome the limitations of traditional character encoding schemes. Before Unicode, there were many different standards: ASCII in the United States, ISO 8859-1 for Western European languages, KOI-8 for Russian, GB 8030 and BIG-5 for Chinese, and so on. This causes two problems: A particular code value corresponds to different letters in the different encoding schemes. Moreover, the encoding for language with large character sets have variable length: Some common characters are encoded as single bytes, others require two or more bytes.

Unicode was designed to solve these problems. When the unification effort started in the 1980s, a fixed 2-byte code was more than sufficient to encode all characters used in all languages in the world, with room to spare for future expansion - or so everyone thought at the time. In 1991, Unicode 1.0 was released, using slightly less than half of the available 65,536 code values. Java was designed from the ground up to use 16-bit Unicode characters, which was a major advance over other programming languages that used 8-bit characters.

Unfortunately, over time, the inevitable happened. Unicode grew beyond 65,536 characters, primarily due to the addition of a very large set of ideographs used for Chinese, Japanese, and Korean. Now, the 16-bit char type is insufficient to describe all Unicode characters.

We need a bit of terminology to explain how this problem is resolved in Java, beginning with Java SE 5.0. A code point is a code value that is associated with a character in an encoding scheme. In the Unicode standard, code points are written in hexadecimal and prefixed with U+, such as U+ 0041 for the code point of the Latin letter A. Unicode has code points that are grouped into 17 code planes. The first code plane, called the basic multilingual plane, consists of the "classic" Unicode characters with code points U+0000 to U+FFFF. Sixteen additional planes, with code points U+10000 to U+10FFFF, hold the supplementary characters.

The UTF-16 encoding represents all Unicode code points in a variable-length code. The characters in the basic multilingual plane are represented as 16-bit values, called code units. The supplementary characters are encoded as consecutive pairs of code units. Each of the values in such an encoding pair falls into a range of 2048 unused values of the basic multilingual plane, called the surrogates area (U+D800 to U+DBFF for the first code unit, U+DC00 to U+DFFF for the second code unit). This is rather clever, because you can immediately tell whether a code unit encodes a single character or it is the first or second part of a supplementary character. For example the mathematical symbol of the set of integers zz has code point U+1D56B and is encoded by the two code units U+D835 and U+DD6.

In Java, the char type describes a code unit in the UTF-16 encoding.

Our strong recommendation is not to use the char type in your programs unless you are actually manipulating UTF-16 code units. You are almost always better off treating strings as abstract data types.

* Example:

=> File: charType.java

package com.webmobileaz;

public class charType {
 public static void main(String \u005B\u005Dargs) {
  char ch = 'c';
  System.out.println(\u0022Hell0\u2122\uDC00\u0022 + ch);
 }
}

=> Result:

Sunday 17 August 2014

The floating-point types denote numbers with fractional parts. The two floating-point types:

TypeStorage RequirementRange(inclusive)
float4 bytesApproximately 1.4E-45 to 3.4028235E38 ( 6-7 significant decimal digits)
double8 bytesApproximately 4.9E-324 to 1.7976931348623157E308 ( 15 significant decimal digits)

The name double refers to the fact that these numbers have twice the precision of the float type (some people call these double-precision numbers). Here, the type to choose in most application is double. The limited precision of float is simply not sufficient for many situations. Seven significant (decimal) digits may be enough to precisely express your annual in dollars and cents, but it won't be enough for your company president's salary. It only makes sense to use float in the rare situations where the slightly faster processing of single-precision numbers is important, or when you need to store a large number of them.

Number of type float have a suffix F (for example: 3.14F). Floating-point numbers without an F suffix (such as: 3.14) are always considered to be of type double. You can optionally supply the D suffix (for example: 3.14D).

* Node: You can specify floating-point literals in hexadecimal. For example, 0,125 = 2 ^ -3 can be written 0x1.0p-3. In hexadecimal notation, you are p, not an e, to denote the exponent. (An e is a hexadecimal digit). Note that the mantissa is written in hexadecimal and the exponent in decimal. The base of the exponent is 2, not 10.

All floating-point computations follow the IEEE 754 specification. In particular, there are three special floating-point values to denote overflows and errors: Positive infinity, Negative infinity, NaN (not a number). For example, the result of dividing a positive number by 0 is positive infinity. Computing 0/0 or the square root of a negative number yields NaN.

* Node: The constants Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, and Double.NaN (as well as corresponding Float constants), but they are rarely used in practice. In particular, you cannot test:

if (x == Double.NaN) // is never true
to check whether a particular result equals Double.NaN. All "not a number" values are considered distinct. However, you can use the Double.isNaN method:

if (Double.isNaN(x)) // check whether x is "not a number"
* Caution: Floating-point numbers are not suitable for financial calculations in which roundoff errors cannot be tolerated. For example, the command System.out.println (2.0 - 1.1) prints 0.89999999,.. not 0.9 as you would expect. Such roundoff errors are caused by the fact that floating-point numbers are represented in the binary number system. There is no precise binary representation of the faction 1/10, just as there is no accurate representation of the fraction 1/3 in the decimal system. If you need precise numerical computations without roundoff errors, use the BigDecimal class, which is introduced later.

View Project

Download Project
The integer types are for numbers without fractional parts. Negative values are allowed. Java provides the four integer types:

TypeStorage RequirementRange(inclusive)
int4 bytes-2,147,483,648 to 2,147,483,637 (just over 2 billion)
short2 bytes-32,768 to 32,767
long8 bytes-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
byte1 byte-128 to 127

In most situations, the int type is the most practical. If you want to represent the number of inhabitants of our planet, you'll need to resort to a long. The byte and short types are mainly intended for specialized applications, such as low-level file handling, or for large arrays when storage space is at a premium.

Under Java, the ranges of the integer types do not depend on the machine on which you will be running the Java code. This alleviates a major pain for the programmer who wants to move software from one platform to another, or even between operating systems on the same platform. In contrast, C and C++ programs use the most efficient integer overflow on a 16-bit system. Since Java programs must run with the same result on all machines, the ranges for the various types are fixed.

Long integer number have a suffix L (for example: 4000L). Hexadecimal number have a prefix 0x (for example: 0xCAFE). Octal number have a prefix 0 (for example: 010 is 8). Naturally, this can be confusing, so we recommend against the use of octal constants.

Starting with Java 7, you can write numbers in binary, with a prefix 0b (for example: 0b1001 is 9). Also starting with Java 7, you can add underscores to number literals, such as 1_000_000 to denote one million. The underscores are for human eyes only. The Java compiler simply removes them.

*Node: In C/C++ the sizes of types such as int and long depend on the target platform. On a 16-bit processor such as the 8086, int are 2 bytes but on a 32-bit process like a Pentium they are 4-byte quantities. Similarly, long values are 4-byte on 32-bit processors and 8-byte on 64-bit processors. These differences make it challenging to write cross-platform programs. In Java, the sizes of all numeric types are platform-independent. Note that Java does not have any unsigned types.

View Project

Download Project
- Java is strongly typed language. This means that every variable must have a declared type. There are eight primitive types in Java:
  + Four of them are integer types.
  + Two are floating-point number types.
  + One is the character type char - used for code units in the Unicode encoding scheme.
  + One is a boolean type for truth values.
- Java has an arbitrary-precision arithmetic package. However, "big numbers", as they are called, are Java object and not a new Java type.

Saturday 16 August 2014

Comments in Java, as in most programming language, do not show up in the executable program. Thus, you can add as many comments as needed without fear of bloating the code. Java has three ways of marking comments. The most common form is a //. You use this for a comment that will run from the // to the end of the line.

   System.out.println("We will not use 'Hello, World!'"); // is this too cute?
When longer comments are needed, you can mark each line with a //, or you can use /* and */ comment delimiters that let you block off a longer comment.

Finally, a third kind of comment can be used to generate documentation automatically. This comment uses a /** to start and a */ to end.
/**
* This is the first sample program in Core Java
* @version 1.01 1997-03-22
* @author webmobileaz
*/
public class FirstSample
{
  public static void main(String[] args)
  {
    System.out.println("We will not use 'Hello, World!'");
  }
}
View Project 

 Download Project