Search This Blog

Showing posts with label literals. Show all posts
Showing posts with label literals. Show all posts

Monday, 2 January 2012

Closer In Java, Its Look Like Literals


By literal we mean any number, text, or other information that represents a value. This means what you type is what you get. We will use literals in addition to variables in Java statement.
  • Integer Literals
  • Floating-Point Literals
  • Boolean Literals
  • Character Literals

Integer Literals

Integers are probably the most commonly used type in the typical program. Any whole
number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal
values, meaning they are describing a base 10 number. There are two other bases which
can be used in integer literals, octal (base eight) and hexadecimal (base 16). Octal
values are denoted in Java by a leading zero. Normal decimal numbers cannot have a
leading zero. Thus, the seemingly valid value 09 will produce an error from the compiler,
since 9 is outside of octal's 0 to 7 range. A more common base for numbers used by
programmers is hexadecimal, which matches cleanly with modulo 8 word sizes, such as
8, 16, 32, and 64 bits. You signify a hexadecimal constant with a leading zero-x, (0x or
0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer value. Since Java is
strongly typed, you might be wondering how it is possible to assign an integer literal to
one of Java's other integer types, such as byte or long, without causing a type mismatch
error. Fortunately, such situations are easily handled. When a literal value is assigned to
a byte or short variable, no error is generated if the literal value is within the range of the
target type. Also, an integer literal can always be assigned to a long variable. However,
to specify a long literal, you will need to explicitly tell the compiler that the literal value is
of type long. You do this by appending an upper- or lowercase L to the literal. For
example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long.

659L Decimal integer literal of type long integer
 0x4a Hexadecimal integer literal of type integer
 057L Octal integer literal of type long integer


Character Literals

Characters in Java are indices into the Unicode character set. They are 16-bit values that
can be converted into integers and manipulated with the integer operators, such as the
addition and subtraction operators. A literal character is represented inside a pair of
single quotes. All of the visible ASCII characters can be directly entered inside the
quotes, such as 'a', 'z', and '@'. For characters that are impossible to enter directly, there
are several escape sequences, which allow you to enter the character you need, such as
'\\'' for the single-quote character itself, and '\\n' for the newline character. There is also a
mechanism for directly entering the value of a character in octal or hexadecimal. For octal
notation use the backslash followed by the three-digit number. For example, '\\141' is the
letter 'a'. For hexadecimal, you enter a backslash-u (\\u), then exactly four hexadecimal
digits. For example, '\\u0061' is the ISO-Latin-1 'a' because the top byte is zero. '\\ua432'
is a Japanese Katakana character. 


Character Escape Sequences


Escape Sequence                                              Description


\ddd                                                               O ctal character (ddd)
\uxxxx                                                 Hexadecimal UNICODE character (xxxx)
\'                                                                           Single quote
\"                                                                          Double quote
\\                                                                             Backslash
\r                                                                        Carriage return
\n                                                         New line (also known as line feed)
\f                                                                            Form feed
\t                                                                                 Tab
\b                                                                           Backspace





Lets see the table below in which the character literals use Unicode escape sequence to represent printable and nonprintable characters both.

 'u0041' Capital letter A
 '\u0030' Digit 0
 '\u0022' Double quote "
 '\u003b' Punctuation ;
 '\u0020' Space
 '\u0009' Horizontal Tab 
Floating-Point Literals


Floating-point numbers represent decimal values with a fractional component. They can
be expressed in either standard or scientific notation. Standard notation consists of a
whole number component followed by a decimal point followed by a fractional
component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation
floating-point numbers. Scientific notation uses a standard-notation, floating-point number
plus a suffix that specifies a power of 10 by which the number is to be multiplied. The
exponent is indicated by an E or e followed by a decimal number, which can be positive
or negative. Examples include 6.022E23, 314159E–05, and 2e+100.
Floating-point literals in Java default to double precision. To specify a float literal, you
must append an F or f to the constant. You can also explicitly specify a double literal by
appending a D or d. Doing so is, of course, redundant. The default double type
consumes 64 bits of storage, while the less-accurate float type requires only 32 bits.

 The default type when you write a floating-point literal is double.
Type
Size
Range
Precision
name
bytes
bits
approximate
in decimal digits
float
4
32
+/- 3.4 * 1038
6-7
double
8
64
+/- 1.8 * 10308
15
The following floating-point literals represent double-precision floating-point and floating-point values.
 6.5E+32 (or 6.5E32) Double-precision floating-point literal
 7D Double-precision floating-point literal
 .01f Floating-point literal
Boolean Literals

Boolean literals are simple. There are only two logical values that a boolean value can
have, true and false. The values of true and false do not convert into any numerical
representation. The true literal in Java does not equal 1, nor does the false literal equal
0. In Java, they can only be assigned to variables declared as boolean, or used in
expressions with Boolean operators.

We have to use the values true and false to represent a Boolean value. Like boolean chosen = true;

String Literals

The string of characters is represented as String literals in Java. In Java a string is not a basic data type, rather it is an object. These strings are not stored in arrays as in C language. There are few methods provided in Java to combine strings, modify strings and to know whether to strings have the same value.
We represent string literals asString myString = "How are you?";
The above example shows how to represent a string. It consists of 
a series of characters inside double quotation marks.
Lets see some more examples of string literals:
""    // the empty string
"\""   // a string containing "
"This is a string"   // a string containing 16 characters
"This is a " +   // actually a string-valued constant expression,
"two-line string"   // formed from two string literals
Strings can include the character escape codes as well, as shown here:String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");

Null Literals

The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables. For instance

s = null;
An this example an object is referenced by s. We reduce the number of references to an object by assigning null to s. Now, as in this example the object is no longer referenced so it will be available for the garbage collection i.e. the compiler will destroy it and the free memory will be allocated to the other object. Well, we will later learn about garbage collection.
 
The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables. For instance

s = null;
An this example an object is referenced by s. We reduce the number of references to an object by assigning null to s. Now, as in this example the object is no longer referenced so it will be available for the garbage collection i.e. the compiler will destroy it and the free memory will be allocated to the other object. Well, we will later learn about garbage collection.

Friday, 30 December 2011

Lexical Issues ( atomic elements of Java )


Now that you have seen several short Java programs, it is time to more formally describe
the atomic elements of Java. Java programs are a collection of 

  • whitespace 
  • identifiers
  • comments
  • literals
  • operators
  • separators
  • keywords
Whitespace 


Java is a free-form language. This means that you do not need to follow any special
indentation rules. For example, the Example program could have been written all on one
line or in any other strange way you felt like typing it, as long as there was at least one
whitespace character between each token that was not already delineated by an operator
or separator. In Java, whitespace is a space, tab, or newline.

Identifiers

Identifiers are used for class names, method names, and variable names. An identifier
may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters. They must not begin with a number, lest they be
confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a different
identifier than Value.
Some examples of valid identifiers are:

HighTemp     temp    h8      $low         this_is_ok


Invalid variable names include:


2temp      low-temp    Yes/ok

Comments

As mentioned, there are three types of comments defined by Java. You have already
seen two: 
1) single-line( // ) 
2) multiline.  //
                  //

The third type is called a documentation comment.
This type of comment is used to produce an HTML file that documents your program. The
documentation comment begins with a 
/* and ends with a */.

literals


A constant value in Java is created by using a literal representation of it. For example,
here are some literals:

100                             literal specifies an integer
98.6                            literal specifies a floating-point value
'X'                               literal specifies is a character constant
"This is a test"              literal specifies  is a string

 A literal can be used anywhere a value of
its type is allowed.


Separators

In Java, there are a few characters that are used as separators. The most commonly
used separator in Java is the semicolon. As you have seen, it is used to terminate
statements. The separators are shown in the following table:
Symbol                       Name                             Purpose
( )                             Parentheses        Used to contain lists of parameters in method
                                                          definition and invocation. Also used for defining
                                                          precedence in expressions, containing expressions in
                                                          control statements, and surrounding cast types.

{ }                             Braces              Used to contain the values of automatically initialized
                                                           arrays. Also used to define a block of code, for
                                                           classes, methods, and local scopes.

[ ]                              Brackets            Used to declare array types. Also used when
                                                           dereferencing array values.

;                                Semicolon           Terminates statements.

,                                Comma               Separates consecutive identifiers in a variable
                                                           declaration. Also used to chain statements together
                                                            inside a for statement.

.                                 Period               Used to separate package names from subpackages
                                                           and classes. Also used to separate a variable or
                                                           method from a reference variable.


Keywords in Java

There are 48 reserved keywords currently defined in the Java language.
These keywords, combined with the syntax of the operators and separators, form the
definition of the Java language. These keywords cannot be used as names for a variable,
class, or method

abstract   const   Finally   int   Public   this   boolean   continue   Float   interface   Return   throw
break   default    For      long   Short    throws    byte      do         Goto    native      Static   transient
case     double     If        new   Strictfp   try      catch     else     Implements       package     Super
void      char     extends    Import   private    Switch    volatile   class     final    Instanceof   protected
Synchronized    while

The keywords const and goto are reserved but not used.
In addition to the keywords, Java reserves the following: true, false, and null. These are
values defined by Java. You may not use these words for the names of variables, classes,
and so on.