0% found this document useful (0 votes)
17 views22 pages

Java Tokens

Uploaded by

rinnysony
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
17 views22 pages

Java Tokens

Uploaded by

rinnysony
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Java Tokens

In Java, the program contains classes and methods. Further, the methods
contain the expressions and statements required to perform a specific
operation. These statements and expressions are made up of tokens. In
other words, we can say that the expression and statement is a set
of tokens. The tokens are the small building blocks of a Java program that
are meaningful to the Java compiler.

What is token in Java?


The Java compiler breaks the line of code into text (words) is called Java
tokens. These are the smallest element of the Java program.

token <= identifier | keyword | separator | operator | literal | com


ment

Types of Tokens
Java token includes the following:

o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words of any programming
language. Each keyword has a special meaning. It is always written in lower
case. Java provides the following keywords:

w
01. abstract 02. boolean 03. byte 04. break 05.

06. case 07. catch 08. char 09. continue 10.

11. do 12. double 13. else 14. extends 15.

16. finally 17. float 18. for 19. if 20.

21. import 22. instanceof 23. int 24. interface 25.

26. native 27. new 28. package 29. private 30.

31. public 32. return 33. short 34. static 35.

36. switch 37. synchronized 38. this 39. thro 40.

41. transient 42. try 43. void 44. volatile 45.

46. assert 47. const 48. enum 49. goto 50.

Identifier: Identifiers are used to name a variable, constant, function, class,


and array. It usually defined by the user. It uses letters, underscores, or a
dollar sign as the first character. The label is also known as a special kind of
identifier that is used in the goto statement. Remember that the identifier
name must be different from the reserved keywords. There are some rules to
declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a


dollar sign. It cannot start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
Some valid identifiers are:

1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value
(constant) in the source code. It can be categorized as an integer literal,
string literal, Boolean literal, etc. It is defined by the programmer. Once it has
been defined cannot be changed. Java provides five types of literals are as
follows:

o Integer
o Floating Point
o Character
o String
o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

Operators: In programming, operators are the special symbol that tells the
compiler to perform a special operation. Java provides different types of
operators that can be classified according to the functionality they provide.
There are eight types of operators in Java, are as follows:

o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

(Condition) ? (Statement1) :
Ternary
(Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>

Separators: The separators in Java is also known as punctuators. There are


nine separators in Java, are as follows:

o Square Brackets []: It is used to define array elements. A pair of


square brackets represents the single-dimensional array, two pairs
of square brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the
parameters.
o Curly Braces {}: The curly braces denote the starting and ending
of a code block.
o Comma (,): It is used to separate two values, statements, and
parameters.
o Assignment Operator (=): It is used to assign a variable and
constant.
o Semicolon (;): It is the symbol that can be found at end of the
statements. It separates the two statements.
o Period (.): It separates the package name form the sub-packages
and class. It also separates a variable or method from a reference
variable.

Comments: Comments allow us to specify information about the program


inside our Java code. Java compiler recognizes these comments as tokens but
excludes it form further processing. The Java compiler treats comments as
whitespaces. Java provides the following two types of comments:

o Line Oriented: It begins with a pair of forwarding slashes (//).


o Block-Oriented: It begins with /* and continues until it founds */.

Data Types in Java


Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Boolean Data Type
The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.

Example:

Boolean one = false;

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127
(inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.

Example:

byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.

Example:

short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range
lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive).
Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647.
Its default value is 0.

The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.

Example:

int a = 100000, int b = -200000


Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used
when you need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited. It is recommended to use a float (instead of double)
if you need to save memory in large arrays of floating point numbers. The
float data type should never be used for precise values, such as currency. Its
default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its
value range is unlimited. The double data type is generally used for decimal
values just like float. The double data type also should never be used for
precise values, such as currency. Its default value is 0.0d.

Example:

double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is
used to store characters.

Example:

char letterA = 'A'

Why char uses 2 byte in java and what is \u0000 ?


It is because java uses Unicode system not ASCII code system. The \u0000 is
the lowest range of Unicode system.
Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in


java: local, instance and static.

Variable
A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.

int data=50;//Here data is variable

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is


not shared among instances.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it among
all the instances of the class. Memory allocation for static variables happens
only once when the class is loaded in the memory.
JVM (Java Virtual Machine) Architecture
JVM (Java Virtual Machine) is an abstract machine. It is a specification that
provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).

What is JVM
It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the
command prompt to run the java class, an instance of JVM is created.

What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader,
memory area, execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever
we run the java program, it is loaded first by the classloader. There are three
built-in classloaders in Java.

1. Bootstrap ClassLoader:
2. Extension ClassLoader:
3. System/Application ClassLoader:

2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant
pool, field and method data, the code for methods.

3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays
a part in method invocation and return.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual
machine instruction currently being executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter:
3. Just-In-Time(JIT) compiler:

Difference between JDK, JRE, and JVM


if you want to get the detailed knowledge of Java Virtual Machine, move to
the next page. Firstly, let's see the differences between the JDK, JRE, and JVM.

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual
machine because it doesn't physically exist. It is a specification that provides
a runtime environment in which Java bytecode can be executed. It can also
run those programs which are written in other languages and compiled to
Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and
JDK are platform dependent because the configuration of each OS is different
from each other. However, Java is platform independent. There are three
notions of the JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java
RTE. The Java Runtime Environment is a set of software tools which are used
for developing Java applications. It is used to provide the runtime
environment. It is the implementation of JVM. It physically exists. It contains a
set of libraries + other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies


besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK)
is a software development environment which is used to develop Java
applications and applets. It physically exists. It contains JRE + development
tools.

JDK is an implementation of any one of the below given Java Platforms


released by Oracle Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other
resources such as an interpreter/loader (java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), etc. to complete the development
of a Java Application.
Java Control Statements | Control Flow in
Java
Java compiler executes the code from top to bottom. The statements in the
code are executed according to the order in which they appear.
However, Java provides statements that can be used to control the flow of
Java code. Such statements are called control flow statements. It is one of the
fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements / Conditional Statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
o labelled loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement
to execute and when. Decision-making statements evaluate the Boolean
expression and control the program flow depending upon the result of the
condition provided. There are two types of decision-making statements in
Java, i.e., If statement and switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of
the If statement gives a Boolean value, either true or false. In Java, there are
four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.


1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of
code if the expression evaluates to true.

Syntax of if statement is given below.

if(condition)
{
statement 1; //executes when condition is true
}

Consider the following example in which we have used the if statement in the
java code.

Student.java

public class Student


{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20

2) if-else statement
The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of
the if-block is evaluated as false.

Syntax:

if(condition)
{
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}
Consider the following example.

Student.java

public class Student


{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else
statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else
statement at the end of the chain.

Syntax of if-else-if statement is given below.

if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
}
Consider the following example.

Student.java

public class Student


{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
}
}
}
Output:

Delhi

4. Nested if-statement
n nested if-statements, the if statement can contain a if or if-else statement
inside another if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.

Student.java

public class Student


{
public static void main(String[] args)
{
String address = "Delhi, India";

if(address.endsWith("India"))
{

if(address.contains("Meerut"))
{
System.out.println("Your city is Meerut");
}
else if(address.contains("Noida"))
{
System.out.println("Your city is Noida");
}
Else
{
System.out.println(address.split(",")[0]);
}
}
else
{
System.out.println("You are not living in India");
}
}
}
Output:

Delhi

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch
statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances
the readability of the program.

The syntax to use the switch statement is given below.


switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Student.java

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly
while some condition evaluates to true. However, loop statements are used
to execute the set of instructions in a repeated order. The execution of the
set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there
are differences in their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times,
we want to execute the block of code.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the
for loop in java.

Calculation.java

public class Calculattion


{
public static void main(String[] args)
{
int sum = 0;
for(int j = 1; j<=10; j++)
{
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:

The sum of first 10 natural numbers is 55

You might also like