Lexical Structure short:
The lexical structure of a programming language Short data type is a 16-bit signed two's
is the set of elementary rules that define what are complement integer.
the tokens or basic atoms of the program. It is the Minimum value is -32,768 (-2^15)
lowest level syntax of a language and specifies Maximum value is 32,767 (inclusive) (2^15 -
what is punctuation, reserved words, identifiers, 1)
constants and operators. Some of the basic rules Short data type can also be used to save
for Java are: memory as byte data type. A short is 2 times
smaller than an int
1. Java is case sensitive. Default value is 0.
2. Whitespace, tabs, and newline characters are Example: short s = 10000, short r = -20000
ignored except when part of string constants.
They can be added as needed for readability. int:
3. Comments in java are used for documentation, Int data type is a 32-bit signed two's
but they don't change code execution. complement integer.
4. Statements terminate in semicolons! Make Minimum value is - 2,147,483,648.(-2^31)
sure to always terminate statements with a Maximum value is 2,147,483,647(inclusive).
semicolon. (2^31 -1)
5. Commas are used to separate words in a list int is generally used as the default data type
6. Round brackets are used for operator for integral values unless there is a concern
precedence and argument lists. about memory.
7. Square brackets are used for arrays and square The default value is 0.
bracket notation. Example: int a = 100000, int b = -200000
8. Curly or brace brackets are used for blocks.
9. Keywords are reserved words that have long:
special meanings within the language syntax. Long data type is a 64-bit signed two's
10. Identifiers are names for constants, variables, complement integer.
functions, properties, methods and objects. Minimum value is -
The first character must be a letter, underscore 9,223,372,036,854,775,808.(-2^63)
or dollar sign. Following characters can also Maximum value is 9,223,372,036,854,775,807
include digits. Letters are A to Z, a to z, and (inclusive). (2^63 -1)
Unicode characters above hex 00C0. Java This type is used when a wider range than int
styling uses initial capital letter on object is needed.
identifiers, uppercase for constant ids and Default value is 0L.
lowercase for property, method and variable Example: long a = 100000L, int b = -200000L
ids.
float:
Note: an identifier must NOT be any word on the Float data type is a single-precision 32-bit
Java Reserved Word List IEEE 754 floating point.
Float is mainly used to save memory in large
Data Types arrays of floating point numbers.
Limits and Size of the primary data types Default value is 0.0f.
Float data type is never used for precise values
byte: such as currency.
Byte data type is an 8-bit signed two's Example: float f1 = 234.5f
complement integer. double:
Minimum value is -128 (-2^7) double data type is a double-precision 64-bit
Maximum value is 127 (inclusive)(2^7 -1) IEEE 754 floating point.
Default value is 0 This data type is generally used as the default
Byte data type is used to save space in large data type for decimal values, generally the
arrays, mainly in place of integers, since a default choice.
byte is four times smaller than an int. Double data type should never be used for
Example: byte a = 100 , byte b = -50 precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4 There is no suffix to specify short and byte literals
directly; 3000S , 3000B, 3000s, 3000b
boolean:
boolean data type represents one bit of Floating-point Literals
information. Floating-point data consist of float and double
There are only two possible values: true and types.
false. The default data type of floating-point literals is
This data type is used for simple flags that double, but you can designate it explicitly by
track true/false conditions. appending the D (or d) suffix. However, the suffix
Default value is false. F (or f) is appended to designate the data type of a
Example: boolean floating-point literal as float.
char: We can also specify a floating-point literal in
char data type is a single 16-bit Unicode scientific notation using Exponent (short E or e),
character. for instance: the double literal 0.0314E2 is
Minimum value is '\u0000' (or 0). interpreted as
Maximum value is '\uffff' (or 65,535 0.0314 *10² (i.e 3.14).
inclusive).
Char data type is used to store any Examples of double literals:
character. 0.0 0.0D 0d
Example: char letterA ='A' 0.7 7D .7d
9.0 9. 9D
Literal Constants 6.3E-2 6.3E-2D 63e-1
A constant value in a program is denoted
by a literal. Literals represent numerical Examples of float literals:
(integer or floating-point), character, 0.0f 0f 7F .7f
boolean or string values. 9.0f 9.F 9f
Example of literals: 6.3E-2f 6.3E-2F 63e-1f
Integer literals: Note: The decimal point and the exponent are
33 0 -9 both optional and at least one digit must be
Floating-point literals: specified.
.3 0.3 3.14
Character literals: Boolean Literals
'(' 'R' 'r' '{' As mentioned before, true and false are reserved
literals representing the truth-values true and false
Boolean literals:(predefined values) respectively. Boolean literals fall under the
true false primitive data type: boolean.
String literals:
"language" "0.2" "r" "" Character Literals
Note: Three reserved identifiers are used as Character literals have the primitive data type
predefined literals: character. A character is quoted in single quote (').
true and false representing boolean values. Note: Characters in Java are represented by the
null representing the null reference. 16-bit Unicode character set.
Let's have a closer look at our literals and type of String Literals
data they can represent: A string literal is a sequence of characters which
Integer Literals has to be double-quoted (") and occur on a single
Integer data types consist of the following line.
primitive data types: int,long, byte, and short. Examples of string literals:
int is the default data type of an integer literal. "false or true"
An integer literal, let's say 3000, can be specified "result = 0.01"
as long by appending the suffix L (or l) to the "a"
integer value: so 3000L (or 3000l) is interpreted "Java is an artificial language"
as a long literal.
String literals are objects of the class String, so all Class/static variables
string literals have the type String. Class variables also known as static variables are
declared with the static keyword in a class, but
Variables and Arrays outside a method, constructor or a block.
In Java, all variables must be declared before they There would only be one copy of each class
can be used. The basic form of a variable variable per class, regardless of how many objects
declaration is shown here: are created from it.
Static variables are rarely used other than being
type identifier [ = value][, identifier [= declared as constants. Constants are variables that
value] ...] ; are declared as public/private, final and static.
The type is one of Java's datatypes. The identifier Constant variables never change from their initial
is the name of the variable. To declare more than value.
one variable of the specified type, use a comma-
separated list. Declaring Array Variables:
Here are several examples of variable declarations To use an array in a program, you must declare a
of various types. Note that some include an variable to reference the array, and you must
initialization. specify the type of array the variable can
int a, b, c; // declares three ints, a, b, and c. reference. Here is the syntax for declaring an array
int d = 3, e, f = 5; // declares three more ints, variable:
initializing dataType[] arrayRefVar; // preferred way.
// d and f. or
byte z = 22; // initializes z. dataType arrayRefVar[]; // works but not
double pi = 3.14159; // declares an approximation preferred way.
of pi. Note: The style dataType[] arrayRefVar is
char x = 'x'; // the variable x has the value 'x'. preferred. The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted
There are three kinds of variables in Java: in Java to accommodate C/C++ programmers.
Local variables Example:
Local variables are declared in methods, The following code snippets are examples of this
constructors, or blocks. syntax:
Local variables are created when the method, double[] myList; // preferred way.
constructor or block is entered and the variable or double myList[]; // works but not
will be destroyed once it exits the method, preferred way.
constructor or block.
Access modifiers cannot be used for local Operators and Expressions
variables. Java provides a rich set of operators to manipulate
Local variables are visible only within the variables. We can divide all the Java operators
declared method, constructor or block. into the following groups:
Local variables are implemented at stack level Arithmetic Operators
internally. Relational Operators
There is no default value for local variables so Logical Operators
local variables should be declared and an initial Assignment Operators
value should be assigned before the first use.
The Arithmetic Operators:
Instance variables Arithmetic operators are used in mathematical
Instance variables are declared in a class, but expressions in the same way that they are used in
outside a method, constructor or any block. algebra. The following table lists the arithmetic
When a space is allocated for an object in the operators:
heap, a slot for each instance variable value is Operator Description Example
created. + Addition - Adds values on either side of
Instance variables are created when an object is the operator A + B will give 30
created with the use of the keyword 'new' and - Subtraction - Subtracts right hand operand
destroyed when the object is destroyed. from left hand operand A - B will give -10
* Multiplication - Multiplies values on either The static modifier for creating class methods and
side of the operator A * B will give 200 variables
/ Division - Divides left hand operand by The final modifier for finalizing the
right hand operand B / A will give 2 implementations of classes, methods, and
% Modulus - Divides left hand operand by variables.
right hand operand and returns remainder B % The abstract modifier for creating abstract classes
A will give 0 and methods.
++ Increment - Increases the value of operand The synchronized and volatile modifiers, which
by 1 B++ gives 21 are used for threads.
-- Decrement - Decreases the value of
operand by 1 B-- gives 19 Conditional Statements
if ,else, else if.....
The Relational Operators:
There are following relational operators supported class IfElseDemo {
public static void main(String[]
by Java language
args) {
Operator Description
== Checks if the values of two operands are int testscore = 76;
equal or not, if yes then condition becomes char grade;
true. (A == B) is not true.
if (testscore >= 90) {
!= Checks if the values of two operands are grade = 'A';
equal or not, if values are not equal then } else if (testscore >= 80) {
condition becomes true. (A != B) is true. grade = 'B';
> Checks if the value of left operand is } else if (testscore >= 70) {
greater than the value of right operand, if grade = 'C';
} else if (testscore >= 60) {
yes then condition becomes true. (A > grade = 'D';
B) is not true. } else {
< Checks if the value of left operand is less grade = 'F';
than the value of right operand, if yes then }
[Link]("Grade = " +
condition becomes true. (A < B) is grade);
true. }
>= Checks if the value of left operand is }
greater than or equal to the value of right
operand, if yes then condition becomes Loops and Switches
true. (A >= B) is not true. There may be a situation when we need to execute
<= Checks if the value of left operand is less a block of code several number of times, and is
than or equal to the value of right operand, often referred to as a loop.
if yes then condition becomes true. (A Java has very flexible three looping mechanisms.
<= B) is true. You can use one of the following three loops:
while Loop
Access Modifiers do...while Loop
Java provides a number of access modifiers to set for Loop
access levels for classes, variables, methods and As of Java 5, the enhanced for loop was
constructors. The four access levels are: introduced. This is mainly used for Arrays.
Visible to the package, the default. No modifiers
are needed. The while Loop:
Visible to the class only (private). A while loop is a control structure that allows you
Visible to the world (public). to repeat a task a certain number of times.
Visible to the package and all subclasses Syntax:
(protected). The syntax of a while loop is:
while(Boolean_expression)
Non Access Modifiers: {
Java provides a number of non-access modifiers to //Statements
achieve many other functionality. }
When executing, if the boolean_expression result execute a specific number of times.A for loop is
is true, then the actions inside the loop will be useful when you know how many times a task is
executed. This will continue as long as the to be repeated.
expression result is true. Syntax:
Here, key point of the while loop is that for(initialization;
the loop might not ever run. When the expression Boolean_expression; update)
is tested and the result is false, the loop body will {
be skipped and the first statement after the while //Statements
loop will be executed. Example: }
Here is the flow of control in a for loop:
public class Test { The initialization step is executed first, and
only once. This step allows you to declare and
public static void main(String args[]) { initialize any loop control variables. You are not
int x = 10; required to put a statement here, as long as a
semicolon appears.
while( x < 20 ) { Next, the Boolean expression is evaluated.
[Link]("value of x : " + x ); If it is true, the body of the loop is executed. If it
x++; is false, the body of the loop does not execute and
[Link]("\n"); flow of control jumps to the next statement past
} the for loop.
} After the body of the for loop executes, the
} flow of control jumps back up to the update
statement. This statement allows you to update
The do...while Loop: any loop control variables. This statement can be
A do...while loop is similar to a while loop, except left blank, as long as a semicolon appears after the
that a do...while loop is guaranteed to execute at Boolean expression.
least one time. Syntax: The Boolean expression is now evaluated again. If
Do{ it is true, the loop executes and the process repeats
//Statements itself (body of loop, then update step, then
}while(Boolean_expression); Boolean expression). After the Boolean
Notice that the Boolean expression appears at the expression is false, the for loop terminates.
end of the loop, so the statements in the loop Example:
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of public class Test {
control jumps back up to do, and the statements in public static void main(String args[]) {
the loop execute again. This process repeats until for(int x = 10; x < 20; x = x+1) {
the Boolean expression is false. Example: [Link]("value of x : " + x );
[Link]("\n");
public class Test { }
public static void main(String args[]) }
{ }
int x = 10;
do{ Enhanced for loop in Java:
[Link]("value of x : " + x ); As of Java 5, the enhanced for loop was
x++; introduced. This is mainly used for Arrays.
[Link]("\n"); Syntax:
}while( x < 20 ); for(declaration : expression)
} {
} //Statements
This would produce the following result: }
Declaration: The newly declared block variable,
The for Loop: which is of a type compatible with the elements of
A for loop is a repetition control structure that the array you are accessing. The variable will be
allows you to efficiently write a loop that needs to
available within the for block and its value would The continue keyword can be used in any of the
be the same as the current array element. loop control structures. It causes the loop to
Expression: This evaluates to the array you need immediately jump to the next iteration of the loop.
to loop through. The expression can be an array In a for loop, the continue keyword causes flow of
variable or method call that returns an array. control to immediately jump to the update
Example: statement. In a while loop or do/while loop, flow
of control immediately jumps to the Boolean
public class Test { expression.
public static void main(String args[]){ The syntax of a continue is a single statement
int [] numbers = {10, 20, 30, 40, 50}; inside any loop:
for(int x : numbers ){ Syntax: continue;
[Link]( x ); Example:
[Link](","); public class Test {
} public static void main(String args[]) {
[Link]("\n"); int [] numbers = {10, 20, 30, 40, 50};
String [] names ={"James", "Larry", for(int x : numbers ) {
"Tom", "Lacy"}; if( x == 30 ) {
for( String name : names ) { continue;
[Link]( name ); }
[Link](","); [Link]( x );
} [Link]("\n");
} }
} }
This would produce the following result: }
10,20,30,40,50,
James,Larry,Tom,Lacy, Switch
public class SwitchDemo {
The break Keyword: public static void main(String[] args) {
The break keyword is used to stop the entire loop. int month = 8;
The break keyword must be used inside any loop String monthString;
or a switch statement. switch (month) {
The break keyword will stop the execution case 1: monthString = "January";
of the innermost loop and start executing the next break;
line of code after the block. The syntax of a break case 2: monthString = "February";
is a single statement inside any loop. Syntax: break;
break; case 3: monthString = "March";
Example: break;
public class Test { case 4: monthString = "April";
public static void main(String break;
args[]) { case 5: monthString = "May";
int [] numbers = {10, 20, 30, break;
40, 50}; case 6: monthString = "June";
for(int x : numbers ) { break;
if( x == 30 ) { case 7: monthString = "July";
break; break;
} case 8: monthString = "August";
[Link]( x ); break;
[Link]("\n"); case 9: monthString =
} "September";
} break;
} case 10: monthString = "October";
This would produce the following result: break;
case 11: monthString =
The continue Keyword: "November";
break; Primitive type Wrapper class Constructor
case 12: monthString = Arguments:
"December"; byte Byte byte or String
break; short Short short or String
default: monthString = "Invalid int Integer int or String
month"; long Long long or String
break; float Float float, double or String
} double Doubledouble or String
[Link](monthString); char Character char
} boolean Boolean boolean or String
Command Line Arguments
A Java application can accept any number of //////////---------------System Class & Math
arguments from the command line. This allows Class------------------////////
the user to specify configuration information
when the application is launched. ---------------------Math---------------------
The class Math contains methods for performing
public class Echo { basic numeric operations such as the elementary
public static void main (String[] args) { exponential, logarithm, square root, and
for (String s: args) trigonometric functions.
{ [Link](s); public class MathLibraryExample {
} public static void main(String[] args) {
int i = 7;
} int j = -9;
} double x = 72.3;
double y = 0.34;
/////////////////-------------String [Link]("i is " + i);
utilites---------------------/////////////////// [Link]("j is " + j);
public class TestOnly { [Link]("x is " + x);
public static void main(String[]args){ [Link]("y is " + y);
String name="Ram Bahadur Thapa"; [Link](x + " is approximately " +
String firstName=[Link](0, 3); [Link](x));
String [Link](y + " is approximately " +
middleName=[Link]([Link]("B"), [Link](y));
[Link]
Of("r")+1);
int haPos=[Link]("ha"); // Comparison operators
[Link](firstName); // min() returns the smaller of the two
[Link](middleName); arguments you pass it
[Link](haPos); [Link]("min(" + i + "," + j + ") is "
} + [Link](i,j));
[Link]("min(" + x + "," + y + ") is
" + [Link](x,y));
///////////--------------Type [Link]("min(" + i + "," + x + ") is "
Wrappers---------------------------//////////// + [Link](i,x));
A primitive wrapper class in the Java is one of [Link]("min(" + y + "," + j + ") is "
eight classes provided in the [Link] package to + [Link](y,j));
provide object methods for the eight primitive
types. All of the primitive wrapper classes in Java // There's a corresponding max() method
are immutable. J2SE 5.0 introduced autoboxing of // that returns the larger of two numbers
primitive types into their wrapper object, and [Link]("max(" + i + "," + j + ") is "
automatic unboxing of the wrapper objects into + [Link](i,j));
their primitive value—the implicit conversion [Link]("max(" + x + "," + y + ") is
between the wrapper objects and primitive values. " + [Link](x,y));
[Link]("max(" + i + "," + x + ") is " [Link]("Here's another random
+ [Link](i,x)); number: " +
[Link]("max(" + y + "," + j + ") is " [Link]());
+ [Link](y,j)); }
}
// The Math library defines a couple
// of useful constants: ------------------------------------------------------------
[Link]("Pi is " + [Link]); -----------------------
[Link]("e is " + Math.E); [Link]
// Trigonometric methods import [Link].*;
// All arguments are given in radians public class ReadString {
// Convert a 45 degree angle to radians public static void main (String[] args) {
double angle = 45.0 * 2.0 * [Link]/360.0;
[Link]("cos(" + angle + ") is " + // prompt the user to enter their name
[Link](angle)); [Link]("Enter your name: ");
[Link]("sin(" + angle + ") is " +
[Link](angle)); // open up standard input
BufferedReader br = new
// Inverse Trigonometric methods BufferedReader(new
// All values are returned as radians InputStreamReader([Link]));
double value = 0.707; String userName = null;
[Link]("acos(" + value + ") is " + // read the username from the command-line;
[Link](value)); need to use try/catch with the
[Link]("asin(" + value + ") is " + // readLine() method
[Link](value)); try {
[Link]("atan(" + value + ") is " + userName = [Link]();
[Link](value)); } catch (IOException ioe) {
[Link]("IO error trying to read
// pow(x, y) returns the x raised your name!");
// to the yth power. [Link](1);
[Link]("pow(2.0, 2.0) is " + }
[Link](2.0,2.0));
[Link]("pow(10.0, 3.5) is " + [Link]("Thanks for the name, " +
[Link](10.0,3.5)); userName);
[Link]("pow(8, -1) is " +
[Link](8,-1)); }
// sqrt(x) returns the square root of x. } //
for (i=0; i < 10; i++) {
[Link]( Locale, Date & Calendar Class
"The square root of " + i + " is " + The [Link](Locale
[Link](i)); newLocale) method sets the default locale for this
} instance of the Java Virtual Machine.
package [Link];
// Finally there's one Random method
// that returns a pseudo-random number import [Link].*;
// between 0.0 and 1.0;
[Link]("Here's one random number: public class LocaleDemo {
"+
[Link]()); public static void main(String[] args) {
// create a new locale public static void main(String[] args) {
Locale locale1 = new Locale("en", "US", NumberFormat formatter;
"WIN"); String number;
// 0 --> a digit or 0 if no digit present
// print locale formatter = new DecimalFormat("00000");
[Link]("Locale:" + locale1); number = [Link](-1234.567);
[Link]("Number 1: " + number);
// set another default locale formatter = new DecimalFormat("0000.000");
[Link](new Locale("fr", number = [Link](-1234.567);
"FRANCE", "MAC")); [Link]("Number 2: " + number);
// # --> a digit or nothing if no digit present
// create a new locale based on new default formatter = new DecimalFormat("##");
settings number = [Link](-1234.567);
Locale locale2 = [Link](); [Link]("Number 3: " +
number); }
// print the new locale
[Link]("Locale::" + locale2); String Class
} ------------------------------------------------------------
} -----------------------
In Java programming language String class is
sequence of characters. String is not primitive
DateFormat Class type in java. String class is Object like others
Date Formatting using SimpleDateFormat: Classes i.e (StringBuffer or Math) But Strings are
SimpleDateFormat is a concrete class for immutable Objects. Immutable means final that
formatting and parsing dates in a locale-sensitive can not be changed once declared.
manner. SimpleDateFormat allows you to start by
choosing any user-defined patterns for date-time import [Link].*;
formatting. For example:
public class Test{
import [Link].*; public static void main(String args[]){
import [Link].*; String Str = new String("Welcome to
[Link]");
public class DateDemo {
public static void main(String args[]) { [Link]("Return Value :" );
[Link]([Link](10) );
Date dNow = new Date( );
//SimpleDateFormat ft = new SimpleDateFormat [Link]("Return Value :" );
("yyyy-MM-dd"); [Link]([Link](10, 15) );
SimpleDateFormat ft = }
new SimpleDateFormat ("E [Link] 'at' }
hh:mm:ss a zzz");
StringBuffer Class
[Link]("Current Date: " + The StringBuffer and StringBuilder classes are
[Link](dNow)); used when there is a necessity to make a lot of
} modifications to Strings of characters.
} public class Test{
NumberFormat Class public static void main(String args[]){
NumberFormat is the abstract base class for all StringBuffer sBuffer = new StringBuffer("
number formats. This class provides the interface test");
for formatting and parsing numbers. [Link](" String Buffer");
import [Link]; [Link](sBuffer); }
import [Link];
public class StringBuilder Class
FormatNumberWithCustomNumberFormat {
StringBuilder objects are like String objects, }
except that they can be modified. Internally, these
objects are treated like variable-length arrays that Regular Expressions
contain a sequence of characters. Regular expressions are a language of string
import [Link].*; patterns built in to most modern programming
public class StringBuilderDemo { languages, including Java 1.4 onward; they can be
public static void main(String[] args) { used for: searching, extracting, and modifying
StringBuilder str = new StringBuilder("India text. This chapter will cover basic syntax and use.
"); . Dot, any character (may or may not match
[Link]("string = " + str); line terminators, read on)
// append character to the StringBuilder \d A digit: [0-9]
[Link]('!'); \D A non-digit: [^0-9]
// convert to string object and print it \s A whitespace character: [ \t\n\x0B\f\r]
[Link]("After append = " + \S A non-whitespace character: [^\s]
[Link]()); \w A word character: [a-zA-Z_0-9]
str = new StringBuilder("Hi "); \W A non-word character: [^\w]
[Link]("string = " + str); However; notice that in Java, you will need to
// append integer to the StringBuilder “double escape” these backslashes.
[Link](123); String pattern = "\\d \\D \\W \\w \\S \\s";
// convert to string object and print it
[Link]("After append = " + * Match 0 or more times
[Link]()); + Match 1 or more times
} ? Match 1 or 0 times
} {n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
String Tokenizers \ Escape the next meta-character (it
In Java, you can StringTokennizer class to split a becomes a normal/literal character)
String into different tokenas by defined delimiter. ^ Match the beginning of the line
(space is the default delimiter). . Match any character (except newline)
import [Link]; $ Match the end of the line (or before
public class App { newline at the end)
public static void main(String[] args) { | Alternation (‘or’ statement)
String str = "This is String , split by () Grouping
StringTokenizer, created by mkyong"; [] Custom character class
StringTokenizer st = new
StringTokenizer(str);
import [Link];
[Link]("---- Split by import [Link];
space ------"); public class ValidateDemo {
while ([Link]()) { public static void main(String[] args) {
List<String> input = new
[Link]([Link]()); ArrayList<String>();
} [Link]("123-45-6789");
[Link]("---- Split by [Link]("9876-5-4321");
comma ',' ------"); [Link]("987-65-4321 (attack)");
StringTokenizer st2 = new [Link]("987-65-4321 ");
StringTokenizer(str, ","); [Link]("192-83-7465");
for (String ssn : input) {
while ([Link]()) { if ([Link]("^(\\
d{3}-?\\d{2}-?\\d{4})$")) {
[Link]([Link]()); [Link]("Found
} good SSN: " + ssn);
} }
}
}
}