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

Sunday, 15 January 2012

What are variables default values?

Variables declared in methods and in blocks are called local variables. Local variable are not initialized when they are created at method invocation. Therefore, a local variable must be initialized explicitly before being used. Otherwise the compiler will flag it as error when the containing method or block is executed.

Example:

public class SomeClassName{
public static void main(String args[]){ int total; System.out.println("The incremented total is " + total + 3); //(1)
}
}
The compiler complains that the local variable total used in println statement at (1) may not be initialized.
Initializing the local variable total before usage solves the problem:

public class SomeClassName{

public static void main(String args[]){int total = 45; //Local variable initialized with value 45 System.out.println("The incremented total is " + total+ 3); //(1)
}
}

Fields initialization

If no initialization is provided for an instance or static variable, either when declared or in an initializer block, then it is implicitly initialized with the default value of its type.
An instance variable is initialized with the default value of its type each time the class is instantiated, that is for every object created from the class.
A static variable is initialized with the default value of its type when the class is first loaded.


Data Type

Default Value
booleanfalse
char
'/u0000'
Integer(byte,short,int,long)0L for long, 0 for others
Floating-point(float,double)0.0F or 0.0D
reference typenull


Note: Reference fields are always initialized with the value null if no initialization is provided

Example of default values for fields

public class House{

// Static variable
static long similarHouses; //Default value 0L when class is loaded.

// Instance variables
String houseName; //Implicitly set to default value null
int numberOfRooms=5; // Explicitly set to 5
boolean hasPet; // Implicitly set to default value false

//..
}

How to declare and initialize a variable

A variable in Java has a type, name and a value. A variable may store of value of either:
- a primitive data type such as int, boolean, char.
or
- a reference to an object, also called reference variable.


for example:
int i; //variable i that can store an int value. boolean isDone; //Variable isDone that can store a boolean value.//Variables a, f and r that can store a char value each:
char a,f,r;

//Equivalent to the three separate declarations:
char a; char f; char r;

What we just deed above is called variable declaration. By declaring variable we are implicitly allocating memory for these variables and determining the value types that can be stored in them.
So, in the example above, we named a variable: isDone that can store a boolean value, but not initialized yet.

Giving a variable a value when declared is called initialization. Further, we can declare and initialize a variable in one go. For example, we could have declared and initialized our variables of the previous example:

int i = 101; //variable i initialized with the value 101://variable isDone initialized with the boolean value true.
boolean isDone = true;
// variables a,f and r initialized with the values 'a','f' and 'r' //respectively: char a = 'a', f='f', r='r';
//
equivalent to:
char a = 'a';char f = 'f';char r = 'r';


Analogous to declaring variables to denote primitive values, we can declare a variable denoting an object reference, that's; a variable having one of the following reference types: a class, an array, or an interface.

For instance (see also Class Instantiation ):
//declaring a redCar and a blueCar of class Car.
Car redCar, blueCar;

Please note that declarations above do not create any object of type Car. These are just variables that can store references to objects of class Car but no reference is created yet.
A reference variable has to be instantiated before being used. So:// declaring and initializing the redCar reference variable
Car redCar=new Car("red");
An object of class Car is created using the keyword new together with the Constructor call Car("red"), then stored in the variable redCar which is now ready to be manipulated.

Floats


Java Literals

A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-point), character, boolean or string values.

Example of literals:

Integer literals:
33 0 -9
Floating-point literals:
.3 0.3 3.14
Character literals:
'(' 'R' 'r' '{'
Boolean literals:(predefined values)
true false

String literals:
"language" "0.2" "r" ""

Note: Three reserved identifiers are used as predefined literals:
true and false representing boolean values.
null representing the null reference.



Let's have a closer look at our literals and type of data they can represent:

Integer Literals


Integer data types consist of the following primitive data types: int,long, byte, and short.
int is the default data type of an integer literal.
An integer literal, let's say 3000, can be specified as long by appending the suffix L (or l) to the integer value: so 3000L (or 3000l) is interpreted as a long literal.

There is no suffix to specify short and byte literals directly; 3000S , 3000B,
3000s, 3000b

Integer literals can also be specified as octal (base 8), or hexadecimal (base 16). Octal and hexadecimal have 0 and 0x prefix respectively. So 03 and 0x3 are representation of integer three in octal and hexa-decimal respectively.


Floating-point Literals

Floating-point data consist of float and double types.
The default data type of floating-point literals is double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.

We can also specify a floating-point literal in scientific notation using Exponent (short E or e), for instance: the double literal 0.0314E2 is interpreted as
0.0314 *10
² (i.e 3.14).

Examples of double literals:
0.0 0.0D 0d0.7 7D .7d
9.0 9. 9D

6.3E-2 6.3E-2D 63e-1
Examples of float literals:
0.0f 0f 7F .7f9.0f 9.F 9f
6.3E-2f 6.3E-2F 63e-1f


Note: The decimal point and the exponent are both optional and at least one digit must be specified.


Boolean Literals

As mentioned before, true and false are reserved literals representing the truth-values true and false respectively. Boolean literals fall under the primitive data type: boolean.

Character Literals

Character literals have the primitive data type character. A character is quoted in single quote (').

Note: Characters in Java are represented by the 16-bit Unicode character set.

String Literals

A string literal is a sequence of characters which has to be double-quoted (") and occur on a single line.

Examples of string literals:

"false or true"
"result = 0.01"

"a"

"Java is an artificial language"

String literals are objects of the class String, so all string literals have the type String.


Escape (aka backslash) sequences are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape sequence starts with a backslash. The available sequences are:
SeqUsage SeqUsage
\bbackspace \\backslash
\fformfeed \"double quote
\nnewline \'single quote
\rcarriage return \###Octal encoded character
\thorizontal tab \uHHHHUnicode encoded character

Java primitive data types

In Java, primitive data types can be categorized within three types:
  1. Integral types:
    • signed integers : byte,short,int and long.
    • unsigned character values, char,denoting all the 65536 characters in the 16-bit Unicode character set.
  2. Floating-point types: float and double, representing fractional signed numbers.
  3. Boolean type: boolean, representing logical values, the two literals, true or false.

A primitive data value can't act as an object in a Java program unless wrapped. Therefore, each primitive data type has a corresponding wrapper class that can be used to represent its value as an object.

Friday, 22 April 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, 21 April 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.