Showing posts with label syntax and grammar. Show all posts
Showing posts with label syntax and grammar. Show all posts

Friday, April 22, 2011

Limits and Size of the primary data types


Limits of the primary datatypes:

Data types Width (in bytes) Minimum value Maximum Value
byte 1 -27 27 - 1
short 2 -215 215-1
int 4 -231 231 - 1
long 8 -263 263 - 1
char 2 0x0 0xffff
float 4 1.401298e-45 3.402823e+38
double 8 4.940656e-324 1.797693e+308


So the sizes in bytes are:
byte - 1 B
short, char - 2B
int, float - 4 B
double, long - 8B

Also to get the limits through java we can get it by their wrapper classes. Click here to see how to get limits programatically.

Primary datatypes and their wrapper classes

Corresponding to all the primitive type there is a wrapper class defined. These wrapper classes are OOP version of the primitive types. These classes provide useful methods for manipulating primitive data values and objects.

The language designers decided that the higher processing speed and memory efficiency of simple, non-class structures for such heavily used data types overruled the elegance of a pure object-only language.The designers decided instead that for each primitive type there would be a corresponding wrapper class. An instance of a wrapper contains, or wraps, a primitive value of the corresponding type.

Some primitive types and their wrapper classes:

Data types Wrapper class
int Integer
short Short
long Long
byte Byte
char Character
float Float
double Double

he wrapper constuctors create class objects from the primitive types. For example, for a double floating point number "d" :
     double d = 5.0;
     Double aD = new Double(d);

Here a Double wrapper object is created by passing the double value in the Double constructor argument.
In turn, each wrapper provides a method to return the primitive value
     double r = aD.doubleValue();

Each wrapper has a similar method to access the primitive value: integerValue() for Integer, booleanValue() for Boolean, and so forth.

Identifier in java

  1. Identifiers are names of variables, functions, classes etc. The name used as an identifier must follow the following rules in JavaTM technology.

    • Each character is either a digit, letter, underscore(_) or currency symbol ($,¢, £ or ¥)
    • First character cannot be a digit.
    • The identifier name must not be a reserved word. 
Note:
Unicode characters above hex 00C0 are allowed as well. Java styling uses initial capital letter on object identifiers, uppercase for constant ids and lowercase for property, method and variable ids.

Comments in java technology

  1. Java technology supports three type of comments :
    1. A single line comment starting with //
    2. A multi-line comment enclosed between /* and */
    3. A documentation or javadoc comment is enclosed between /** and */. These comments can be used to generate HTML documents using the javadoc utility, which is part of Java language.

Java source file format

A Java source file has the following elements in this specific order.
  • An optional package statement. All classes and interfaces defined in the file belong to this package. If the package statement is not specified, the classes defined in the file belong to a default package. An example of a package statement is -
    package testpackage;
  • Zero or more import statements. The import statement makes any classes defined in the specified package directly available. For example if a Java source file has a statement importing the class "java.class.Button", then a class in the file may use Button class directly without providing the names of the package which defines the Button class. Some examples of import statement are -
    import java.awt.*; // All classes in the awt package are imported.
    import java.applet.Applet;
  • Any number of class and interface definitions may follow the optional package and import statements.
If a file has all three of the above constructs, they must come in the specific order of package statement, one or more import statements, followed by any number of class or interface definitions. Also all the above three constructs are optional. So an empty file is a legal Java file.

Thursday, April 21, 2011

Relational Operators in java

Java has six relational operators that compare two numbers and return a boolean value. The relational operators are <, >, <=, >=, ==, and !=.
x < y Less than True if x is less than y, otherwise false.
x > y Greater than True if x is greater than y, otherwise false.
x <= y Less than or equal to True if x is less than or equal to y, otherwise false.
x >= y Greater than or equal to True if x is greater than or equal to y, otherwise false.
x == y Equal True if x equals y, otherwise false.
x != y Not Equal True if x is not equal to y, otherwise false.
Here are some code snippets showing the relational operators.
boolean test1 = 1 < 2;  // True. One is less that two.
boolean test2 = 1 > 2; // False. One is not greater than two.
boolean test3 = 3.5 != 1; // True. One does not equal 3.5
boolean test4 = 17*3.5 >= 67.0 - 42; //True. 59.5 is greater than 5
boolean test5 = 9.8*54 <= 654; // True. 529.2 is less than 654
boolean test6 = 6*4 == 3*8; // True. 24 equals 24
boolean test7 = 6*4 <= 3*8; // True. 24 is less than or equal to 24
boolean test8 = 6*4 < 3*8; // False. 24 is not less than 24

This, however, is an unusual use of booleans. Almost all use of booleans in practice comes in conditional statements and loop tests. You've already seen several examples of this. Earlier you saw this

if (args.length > 0) {
System.out.println("Hello " + args[0]);
}

args.length > 0 is a boolean value. In other words it is either true or it is false. You could write

boolean test = args.length > 0;
if (test) {
System.out.println("Hello " + args[0]);
}

instead. However in simple situations like this the original approach is customary. Similarly the condition test in a while loop is a boolean. When you write while (i < args.length) the i < args.length is a boolean.




All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators.

Booleans

Booleans are named after George Boole, a nineteenth century logician. Each boolean variable has one of two values, true or false. These are not the same as the Strings "true" and "false". They are not the same as any numeric value like 1 or 0. They are simply true and false. Booleans are not numbers; they are not Strings. They are simply booleans.
Boolean variables are declared just like any other variable.
boolean test1 = true;
boolean test2 = false; 
Note that true and false are reserved words in Java. These are called the Boolean literals. They are case sensitive. True with a capital T is not the same as true with a little t. The same is true of False and false.

The char data type in Java

A char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. A char literal is a single one character enclosed in single quote marks like this
char myCharacter = 'g';
Some characters are hard to type. For these Java provides escape sequences. This is a backslash followed by an alphanumeric code. For instance '\n' is the newline character. '\t' is the tab character. '\\' is the backslash itself. The following escape sequences are defined:
\b backspace
\t tab
\n linefeed
\f formfeed
\r carriage return
\" double quote, "
\' single quote, '
\\ backslash, \
The double quote escape sequence is used mainly inside strings where it would otherwise terminate the string. For instance
System.out.println("And then Jim said, \"Who's at the door?\"");
It isn't necessary to escape the double quote inside single quotes. The following line is legal in Java
char doublequote = '"';

Further java also supports Unicode Characters.

Unicode character in java

Java uses the Unicode character set. Unicode is a two-byte character code set that has characters representing almost all characters in almost all human alphabets and writing systems around the world including English, Arabic, Chinese and more.
Unfortunately many operating systems and web browsers do not handle Unicode. For the most part Java will properly handle the input of non-Unicode characters. The first 128 characters in the Unicode character set are identical to the common ASCII character set. The second 128 characters are identical to the upper 128 characters of the ISO Latin-1 extended ASCII character set. It's the next 65,280 characters that present problems.
You can refer to a particular Unicode character by using the escape sequence \u followed by a four digit hexadecimal number. For example
\u00A9 The copyright symbol
\u0022 " The double quote
\u00BD The fraction 1/2
\u0394 Δ The capital Greek letter delta
\u00F8 A little o with a slash through it
You can even use the full Unicode character sequence to name your variables. However chances are your text editor doesn't handle more than basic ASCII very well. You can use Unicode escape sequences instead like this:


String Mj\u00F8lner = "Hammer of Thor";

 but frankly this is way more trouble than it's worth.

Conditions, Statements and Blocks

Conditions are phrases that can be evaluated to a boolean value such as a comparison operator between two constants, variables or expressions used to test a dynamic situation. Examples are x <= 5 and bool_flag != true.

Statements are complete program instructions made from constants, variables, expressions and conditions. Statements always end with a semicolon. A program contains one or more statements.
Assignment statements use an assignment operator to store a value or the result of an expression in a variable.

Memory allocation is done at the time of assignment. Primitive datatypes have static allocation with size determined by their type. Simple examples include :
first_name = "Fred"; 
count +=1;

Variables may be assigned an initial value when declared. This is considered good programming practice. Examples are  
boolean fileOpenFlag = true;,  
int finalScore = null;
final float PI = 3.14159;

Array variables can use a shortcut method of initial value assignment. Examples are:
int v[] = {2,4,20}; //declaration/creation/assignment in one step!
int m[][] = {{2,3,4}, {4,5,6}, {1,1,1}}; // two dimensional array

Local variables must be assigned a value prior to use. There is no default assumption. Failure to initialize will cause a compiler error! Field variables (aka properties) have defaults but initialization is good programming practice.
Execution blocks are sets or lists of statements enclosed in curly brackets. Variables maintain their definition (or 'scope') until the end of the execution block that they are defined in. This is the reason why variable declaration and assignment can be a two step process.
Note: It is a good rule of thumb to declare variables in as nested a scope as possible to limit the chance of spurious assignment.
Beware: A variable's content can be hidden by redeclaration of its name within a nested execution block. At times this is convenient but beginning programmers should avoid reuse (ie. 'overload') of variable names.

Storing integral types in java


All the integer types in Java technology are internally stored in two's complement. In two's complement, positive numbers have their corresponding binary representation.
For negative numbers see - 2's complement of negative numbers in java

The shift operators- << , >> , >>>(3 operators) for int and long



The shift left operator in Java technology is "<<". There are two operators for doing the right shift - signed right shift (>>) and zero fill right shift (>>>). The left shift operator fills the right bits by zero. The effect of each left shift is multiplying the number by two. The example below illustrates this - int i = 13; // i is 00000000 00000000 00000000 0000 1101 
i = i << 2; // i is 00000000 00000000 00000000 0011 0100

 After this left shift, i becomes 52 which is same as multiplying i by 4 Zero fill shift right is represented by the symbol >>>. This operator fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number is positive, negative otherwise.) The example below illustrates applying the operator >>> on a number.  
int b = 13; // 00000000 00000000 00000000 0000 1101 
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011

So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect of applying the operator >>> on a negative number.  
int b = -11; //11111111 11111111 11111111 1111 0101 
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101
So the result of applying zero fill right shift operator with operand two on -11 is 1073741821. Signed right shift operator (>>) fills the left most bit by the sign bit. The result of applying the signed shift bit has the same sign as the left operand. For positive numbers the signed right shift operator and the zero fill right shift operator both give the same results. For negative numbers, their results are different. The example below illustrates the signed right shift.  

int b = -11; // 11111111 11111111 11111111 1111 0101 

b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2's complement of -3) // Here the sign bit 1 gets filled in the two most significant bits. 
The new value of b becomes -3.


1. How to generate a random number between 1 to x, x being a whole number greater than 1
Ans: double result = x * Math.random();

Important rules for the conditional operators - && and ||

Operator && returns true if both operands are true, false otherwise. Operator || returns false if both operands are false, true otherwise. The important thing to note about these operators is that they are short-circuited. This means that the left operand is evaluated before the right operator. If the result of the operation can be evaluated after computing the left operand, then the right side is not computed. In this respect these operators are different from their bit-wise counterparts - bit-wise and (&), and bit-wise or (|). The bit-wise operators are not short-circuited. This means both the operands of bit-wise operator are always evaluated independent of result of evaluations.

The equality operator


The equality operator (==) when applied to objects return true if two objects have same reference value, false otherwise. The example below illustrates this --

String str1 = "first string";
String str2 = new String("first string");
String str3 = "first string";
boolean test1 = (str1 == str2);
boolean test2 = (str1 == str3);
In the example above, test1 is set to false because str1 and str2 point to different references. As str1 and str3 point to the same reference, test2 gets set to true. When a string is initialized without using the new operator, and with an existing string, then the new string also points to the first string's location. So in the example above, str1 and str3 point to the same pool of memory and hence test2 gets set to true. The string str2 on the other hand is created using the new operator and hence points to a different block of memory. Hence test1 gets set to false.

Java primary data types : Integers

The integer types are for numbers without fractional parts. Negative values are allowed.
  • int      4 bytes
  • Short  2 bytes
  • Long   8 bytes
  • Byte   1 byte

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 type for each processor. As a result, a C program that runs well on a 32-bit processor may exhibit integer overflow on a 16-bit system. Because Java programs must run with the same results on all machines, the ranges for the various types are fixed.

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

Cpp vs Java on integers

Note that Java does not have any unsigned types.

Java vs Cpp : Integers

In C and C++, int denotes the integer type that depends on the target machine. On a 16-bit processor, like the 8086, integers are 2 bytes. On a 32-bit processor like the Sun SPARC, they are 4-byte quantities. On an Intel Pentium, the integer type of C and C++ depends on the operating system: for DOS and Windows 3.1, integers are 2 bytes. When 32-bit mode is used for Windows programs, integers are 4 bytes. In Java, the sizes of all numeric types are platform independent.

Primary data types and their default values

Each primitive data type has a default value specified. Variable of primitive data type may be initialized.
Only class member variables are automatically initialized. Method variables need explicit initialization.

Primitive Data type Default Value
byte 0
short 0
int 0
long 0L or 0l
float 0.0f
double 0.0d
boolean false
char '\u0000'

Lexical Structure in java

The lexical structure of a programming language is the set of elementary rules that define what are the tokens or basic atoms of the program. It is the lowest level syntax of a language and specifies what is punctuation, reserved words, identifiers, constants and operators. Some of the basic rules for Java are:
  • Java is case sensitive.
  • Whitespace, tabs, and newline characters are ignored except when part of string constants. They can be added as needed for readability.
  • Comments in java are used for documentation, but they don't change code execution.
  • Statements terminate in semicolons! Make sure to always terminate statements with a semicolon.
  • Commas are used to separate words in a list
  • Round brackets are used for operator precedence and argument lists.
  • Square brackets are used for arrays and square bracket notation.
  • Curly or brace brackets are used for blocks.
  • Keywords are reserved words that have special meanings within the language syntax.
  • Identifiers are names for constants, variables, functions, properties, methods and objects. The first character must be a letter, underscore or dollar sign. Following characters can also include digits. Letters are A to Z, a to z, and Unicode characters above hex 00C0. Java styling uses initial capital letter on object identifiers, uppercase for constant ids and lowercase for property, method and variable ids.
    Note: an identifier must NOT be any word on the Java Reserved Word List.

Monday, April 18, 2011

Binary representation of negative numbers in java : 2's complement

Negative numbers in Java are represented using 2's complement. As we know that integers in Java occupy 4 bytes so to understand how a negative integer (say -4) is represented internally in Java, we first need to find the binary equivalent of the positive value of the integer (in this case 4) and subsequently by finding the 2's complement of that binary representation.

Okay, so how do find 2's complement of a binary number? Simply by adding '1' to the 1's complement of that number. But, how to find 1's complement of a binary number then? Just by reverting the bits of the number i.e., changing 1s to 0s and 0s to 1s. An example may of of some help here.

Example
int i = -4;
...

Step #1: Binary Equivalent of the positive value (4 in this case)

0000 0000 0000 0000 0000 0000 0000 0100

Step #2: 1's complement of the binary rep of 4 by inverting the bits

1111 1111 1111 1111 1111 1111 1111 1011

Step #3: Finding 2's complement by adding 1 to the corresponding 1's complement

1111 1111 1111 1111 1111 1111 1111 1011
0000 0000 0000 0000 0000 0000 0000 0001
---------------------------------------
1111 1111 1111 1111 1111 1111 1111 1100

Thus, we see that integer -4 is represented by the binary sequence (1111 1111 1111 1111 1111 1111 1111 1100) in Java.

Once we have an understanding of how the numbers are represented internally, bit-level manipulation becomes easily understandable, which otherwise is obviously one of the hardest things in Java (or any other language supporting that) to visualize.

Tuesday, April 12, 2011

Convert Exponential form to Decimal number format in Java

While working with Doubles and Long numbers in Java you will see that most of the value are displayed in Exponential form.
For example : In following we are multiplying 2.35 with 10000 and the result is printed.
//Division example
Double a = 2.85d / 10000;
System.out.println("1) " + a.doubleValue());
 
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2) " + a.doubleValue());
Result:
1)  2.85E-4
2)  2.85E8
Thus you can see the result is printed in exponential format. Now you may want to display the result in pure decimal format like: 0.000285 or 285000000. You can do this simply by using class java.math.BigDecimal. In following example we are using BigDecimal.valueOf() to convert the Double value to BigDecimal and than .toPlainString() to convert it into plain decimal string.
import java.math.BigDecimal;
//..
//..
 
//Division example
Double a = 2.85d / 10000;
System.out.println("1) " + BigDecimal.valueOf(a).toPlainString());
 
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2) " + BigDecimal.valueOf(a).toPlainString());
Result:
1)  0.000285
2)  285000000
The only disadvantage of the above method is that it generates lonnnnggg strings of number. You may want to restrict the value and round off the number to 5 or 6 decimal point. For this you can use java.text.DecimalFormat class. In following example we are rounding off the number to 4 decimal point and printing the output.
import java.text.DecimalFormat;
//..
//..
 
Double a = 2.85d / 10000;
DecimalFormat formatter = new DecimalFormat("0.0000");
System.out.println(formatter .format(a));
Result:
0.0003

Chitika