+84 1649 660 740
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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

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

- Let's look more closely at one of the simplest Java programs you can have - one that simply prints a message to console:
public class FirstSample {
 public static void main(String[] args){
  System.out.println("We will not use 'Hello, World!'");
 }
}
- It is worth spending all the time you need to become comfortable with the framework of this sample; the pieces will recur in all applications. First and foremost, Java is case sensitive.
If you made any mistakes in capitalization (such as typing Main instead of main), the program will not run.

- Now let's look at this source code line by line. The keyword public is called an access modifier; these modifiers control the level of access other parts of a program have to this code. The keyword class reminds you that everything in a Java program lives inside a class. Class as a container for the program logic that defines the behavior of an applications. Classes are the building blocks with which all Java applications and applets are built. Everything in a Java program must be inside a class.

- Following the keyword class is the name of the class. The rules for class names in Java are quite generous. Names must begin with a letter, and after that, they can have any combination of letters and digits. The length is essentially unlimited. You cannot use a Java reserved word (such as public or class) for class name.

- The standard naming convention (which we follow in the name FirstSample) is the class names are nouns that start with an uppercase letter. If a name consists of multiple words, use an initial uppercase letter in each of the words.

- You need to make the file name for the source code the same as the name of the public class, with the extension .java appended. Thus, you must store this code in a file called FirstSample.java. (Again, case is important - don't use firstsample.java).

- If you have named the file correctly and not made any typos in the source code, then when you compile this source code, you end up with a file containing the bytecodes for this class. The Java compiler automatically names the bytecode file FirstSample.class and stores it in the same directory as the source file. Finally, launch the program by issuing the following command:

 java FirstSample
- Remember to leave off the .class extension when the program executes, it simply display the string We will not use 'Hello, World!' on the console.

- When you use java ClassName to run a compiled, the Java virtual machine always starts execution with the code in the main method in the class you indicate. (The term "method" is Java-speak for a function). Thus, you must have a main method in the source file for your class for your code to execute. You can, of course, add your own methods to a class and call them from the main method.

* Node: According to the Java Language Specification, the main method must be declared public . However, several version of the Java launcher were willing to execute Java programs even when the main method was not public.

- Notice the braces { } in the source code. In Java, as in C/C++, braces delineate the parts (usually called blocks) in your program. In Java, the code for any method must be started by an opening brace '{ '{' and ended by a closing brace '}'.

- Brace styles have inspired an inordinate amount of useless controversy. We follow a style that lines up matching braces. As white space in irrelevant to the Java compiler, you can use whatever brace style you like. We will have more to say about the use of braces when we talk about the various kinds of loops.

- For now, don't worry about the keywords static void - just think of them as part of what you need to get a Java program to compile. The point to remember for now is that every Java application must have a main method that is declared in the following way:


public class ClassName
{
  public static void main(String[] args)
  {
    program statements
  }
}
- Next, turn your attention to this fragment:

{
  System.out.println("We will not use 'Hello, World!'");
}
- Braces mark the beginning and end of the body of the method. This method has only one statement in it. As with most programming language, you can think of Java statements as sentences of the language. In Java, every statement must end with a semicolon. In particular, carriage returns do not mark the end of a statement, so statements can span multiple lines if need be.

- The body of the main method contains a statement that outputs a single line of text to the console.

- Here, we are using the System.out object and calling its println method. Notice the periods used to invoke a method. Java uses the general syntax: object.method(parameters) as its equivalent of a function call.

- In this case, we are calling the println method and passing it a string parameter. The method displays the string parameter on the console. It when terminates the output line, so that each call to println displays its output on a new line. Notice that Java, like C/C++, uses double quotes to delimit strings.

- Methods in Java, like function in any programming language, can use zero, one, or more parameters (some programmer call them arguments). Even if a method takes no parameters, you must still use empty parentheses. For example, a variant of the println method with no parameters just prints a blank line. You invoke it with the call:

  System.out.println();
* Note: System.out also has a print method that doesn't add a newline character to the output. For example, System.out.print("Hello"); prints Hello without a newline.

* Example:

=> File: FirstSample.java

package com.webmobileaz;

public class FirstSample {
 public static void main(String[] args){
  System.out.println("We will not use 'Hello, World!'");
  System.out.print("We will not use 'Hello, World!'");
  System.out.println("We will not use 'Hello, World!'");
 }
}

=> Result:



We will not use 'Hello, World!'
We will not use 'Hello, World!'We will not use 'Hello, World!'
View Example

DownLoad Example