0% found this document useful (0 votes)
6 views

JavaTokens

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

JavaTokens

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Java Tokens

Last Updated : 12 Mar, 2024


In Java, Tokens are the smallest elements of a program that is
meaningful to the compiler. They are also known as the fundamental
building blocks of the program. Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators
6. Comments
7. Separators
1. Keyword:
Keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since
keywords are referred names for a compiler, they can’t be used as
variable names because by doing so, we are trying to assign a new
meaning to the keyword which is not allowed. Java language supports the
following keywords:

abstract assert boolean


break byte case
catch char class
const continue default
do double else
enum exports extends
final finally float
for goto if
implements import instanceof
int interface long
module native new
open opens package
private protected provides
public requires return
short static strictfp
super switch synchronized
this throw throws
to transient transitive
try uses void
volatile while with
2. Identifiers:
Identifiers are used as the general terminology for naming of variables,
functions and arrays. These are user-defined names consisting of an
arbitrarily long sequence of letters and digits with either a letter or the
underscore (_) as a first character. Identifier names must differ in spelling
and case from any keywords. You cannot use keywords as identifiers;
they are reserved for special use. Once declared, you can use the
identifier in later program statements to refer to the associated value. A
special kind of identifier, called a statement label, can be used in goto
statements. Examples of valid identifiers:
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers:
My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
3. Constants/Literals:
Constants are also like normal variables. But the only difference is, their
values cannot be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals. Constants
may belong to any of the data type. Syntax:
final data_type variable_name;
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
final int PI = 3.14; //Here final keyword is used to define the
constant PI
}}
4. Special Symbols:
The following special symbols are used in Java having some special
meaning and thus, cannot be used for some other purpose.
[] () {}, ; * =
 Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function
calls and function parameters.
 Braces{}: These opening and ending curly braces marks the start and
end of a block of code containing more than one executable statement.
 comma (, ): It is used to separate more than one statements like for
separating parameters in function calls.
 semi colon : It is an operator that essentially invokes something called
an initialization list.
 asterick (*): It is used to create pointer variable.
 assignment operator: It is used to assign values.
5. Operators:
Java provides many types of operators which can be used according to
the need. They are classified based on the functionality they provide.
Some of the types are-
 Arithmetic Operators
 Unary Operators
 Assignment Operator
 Relational Operators
 Logical Operators
 Ternary Operator
 Bitwise Operators
 Shift Operators
 instance of operator
 Precedence and Associativity
6. Comments:
In Java, Comments are the part of the program which are ignored by the
compiler while compiling the Program. They are useful as they can be
used to describe the operation or methods in the program. The
Comments are classified as follows:
 Single Line Comments
 Multiline Comments
// This is a Single Line Comment
/*
This is a Multiline Comment
*/
Java
import java.io.*;

class GFG {
public static void main (String[] args) {

// This is a Single line Comment

/*
This is a Multiline Comment
*/
}}
7. Separators:
Separators are used to separate different parts of the codes. It tells the
compiler about completion of a statement in the program. The most
commonly and frequently used separator in java is semicolon (;).
int variable; //here the semicolon (;) ends the declaration of the
variable
Java
import java.io.*;

class GFG {
public static void main (String[] args) {
System.out.println("GFG!"); //Here the semicolon (;) used to end the
print statement
}
}

Types of Statements in Java


Statements are roughly equivalent to sentences in natural languages. In general,
statements are just like English sentences that make valid sense. In this section, we
will discuss what is a statement in Java and the types of statements in Java.

What is statement in Java?


In Java, a statement is an executable instruction that tells the compiler what to
perform. It forms a complete command to be executed and can include one or more
expressions. A sentence forms a complete idea that can include one or more
clauses.

Types of StatementsJava statements can be broadly classified into the


following categories:Expression Statements Declaration
Statements Control Statements

Expression StatementsExpression is an essential building block of any Java program.


Generally, it is used to generate a new value. Sometimes, we can also assign a value to
a variable. In Java, expression is the combination of values, variables, operators,
and method calls.There are three types of expressions in Java:
o Expressions that produce a value. For example, (6+9), (9%2), (pi*radius)
+ 2. Note that the expression enclosed in the parentheses will be evaluate
first, after that rest of the expression.
o Expressions that assign a value. For example, number = 90, pi = 3.14.
o Expression that neither produces any result nor assigns a value. For
example, increment or decrement a value by using increment or
decrement operator respectively, method invocation, etc. These
expressions modify the value of a variable or state (memory) of a program.
For example, count++, int sum = a + b; The expression changes only the
value of the variable sum. The value of variables a and b do not change, so it
is also a side effect.

Declaration StatementsIn declaration statements, we declare variables and


constants by specifying their data type and name. A variable holds a value that is
going to use in the Java program. For example:

1. int quantity;
2. boolean flag;
3. String message; Also, we can initialize a value to a variable. For example:

1. int quantity = 20;


2. boolean flag = false;
3. String message = "Hello";

Java also allows us to declare multiple variables in a single declaration statement.


Note that all the variables must be of the same data type.

1. int quantity, batch_number, lot_number;


2. boolean flag = false, isContains = true;
3. String message = "Hello", how are you;
4. Control StatementControl statements decide the flow (order or sequence
of execution of statements) of a Java program. In Java, statements are parsed
from top to bottom. Therefore, using the control flow statements can
interrupt a particular section of a program based on a certain condition
5.

6.

Java command-line argument is an argument i.e. passed at the time of


running the Java program. In Java, the command line arguments passed
from the console can be received in the Java program and they can be used
as input. The users can pass the arguments during the execution bypassing
the command-line arguments inside the main() method.

Working command-line argumentsWe need to pass the arguments as


space-separated values. We can pass both strings and primitive data
types(int, double, float, char, etc) as command-line arguments. These
arguments convert into a string array and are provided to the main()
function as a string array argument.

When command-line arguments are supplied to JVM, JVM wraps these and
supplies them to args[]. It can be confirmed that they are wrapped up in an
args array by checking the length of args using args.length.
Internally, JVM wraps up these command-line arguments into the args[ ]
array that we pass into the main() function. We can check these arguments
using args.length method. JVM stores the first command-line argument at
args[0], the second at args[1], the third at args[2], and so on.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]); } }
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.
class A{ public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
} }
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc

Java Variable Declaration


Java programming language requires variables to operate and handle data. Java creates several
variables as per data format and data types. The variable declaration means creating a variable in
a program for operating different information.

The Java variable declaration creates a new variable with required properties. The programming
language requires four basic things to declare a variable in the program.

1. Data-type
2. Variable name
3. Initial value
4. Semicolon

Data-type: It represent the type of value variable.

Variable name: The Java variable declaration requires a unique name. We prefer to declare
small and understandable variable names.

Initial value: Java language requires the initial value of the variable. Declare
variable with initial value does not necessary in the main class. We must assign the
initial value in the default constructor. The "final variable" needs to declare the
initial value.
Semicolon: The semicolon represents the end of the variable declaration
statement.

Variable Declaration
There are two ways to declare a variable in Java. The first method is to assign the
initial value to the variable. The second method declares variable without initial
value.

Declare a Variable with Initial Value

1. Data_type variable_name = value;


o For example: String my_name = "Java coder";
o We initialize data with a given variable and display it as an output.
o The way of declaration works on the default method of the class.

Declare a Variable without Initial Value

1. Data_type variable_name;
o For example: String my_name;
o We do not need to initialize data with a given variable.
o Assign value in any method and display it as an output.
o The way of declaration works inside and outside of the default method.
o The variable data is displayed inside of the default method of the class.

Examples
Java Variable Declaration Example: With Initialization
Create several variables with the different data formats. Here, we can use int,
String, Boolean and other data types.

o Create variables with required data types in the default method.


o Use variable name and its value.
o Return this value in the method as per data format.

CreateVariable.java

1. public class CreateVariable {


2. public static void main(String[] args)
3. {
4. //variable declaration
5. int student_id = 10;
6. String student_name = "Java coder";
7. double numbers = 3.21;
8. Boolean shows = true;
9. System.out.println("Name:" +student_name+ "\nAge:" +student_id);
10. System.out.println("Number:" +numbers+ "\nBoolean:" +shows);
11. }
12.}

Type Casting in Java


In Java, type casting is a method or process that converts a data type into another
data type in both ways manually and automatically. The automatic conversion is
done by the compiler and manual conversion performed by the programmer. In this
section, we will discuss type casting and its types with proper examples.

Type casting
Convert a value from one data type to another data type is known as type casting.

Types of Type Casting


There are two types of type casting:

In Java, there are two types of casting:


 Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size
type:

Example
public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses () in front of
the value:

Example
public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9

The Scope of Variables in Java


Variables are an essential part of data storage and manipulation in the realm of
programming. In addition to making values available within a programme, they offer
a means of holding them temporarily. Not all variables, though, are made equally.
Each variable has a scope that specifies how long it will be seen and used in a
programme. Java code must be efficient and error-free, which requires an
understanding of variable scope. The scope of variables in Java will be explored in
this section, along with their effects on how programmes are executed.

There are four scopes for variables in Java: local, instance, class, and method
parameters. Examining each of these scopes in more detail will be helpful.

Local Variables:
Local variables are those that are declared inside of a method, constructor, or code
block. Only the precise block in which they are defined is accessible. The local
variable exits the block's scope after it has been used, and its memory is freed.
Temporary data is stored in local variables, which are frequently initialised in the
block where they are declared. The Java compiler throws an error if a local variable
is not initialised before being used. The range of local variables is the smallest of all
the different variable types.

Example:

1. public SumExample
2. {
3. public void calculateSum() {
4. int a = 5; // local variable
5. int b = 10; // local variable
6. int sum = a + b;
7. System.out.println("The sum is: " + sum);
8. } // a, b, and sum go out of scope here
9. }

Output:

The sum is: 15


Instance Variables:
Within a class, but outside of any methods, constructors, or blocks, instance
variables are declared. They are accessible to all methods and blocks in the class
and are a part of an instance of the class. If an instance variable is not explicitly
initialised, its default values are false for boolean types, null for object references,
and 0 for numeric kinds. Until the class instance is destroyed, these variables'
values are retained.

Example:

1. public class Circle {


2. double radius; // instance variable
3. public double calculateArea() {
4. return Math.PI * radius * radius;
5. }
6. }

Class Variables (Static Variables):


In a class but outside of any method, constructor, or block, the static keyword is
used to declare class variables, also referred to as static variables. They relate to
the class as a whole, not to any particular instance of the class. Class variables can
be accessed by using the class name and are shared by all instances of the class.
Like instance variables, they have default values, and they keep those values until
the programme ends.

Example:

1. public class Bank {


2. static double interestRate; // class variable
3. // ...
4. }

Method Parameters:
Variables that are supplied to a method when it is invoked are known as method
parameters. They serve as inputs for method execution and are used to receive
values from the caller. The scope of method parameters is restricted to the method
in which they are defined, making them local to that method. The values of the
arguments given are allocated to the respective parameters when a method is
called.

Example:
1. public void printName(String name) { // name is a method parameter
2. System.out.println("Hello, " + name + "!");
3. }

Writing clear and effective Java code requires a solid understanding of variable
scope. Here are some essential ideas to bear in mind:

The minimal scope necessary for variables to serve their purpose should be
expressed. As a result, there are fewer naming conflicts, and the code is easier to
comprehend.

To prevent compilation issues, local variables should be initialised before usage.

To guarantee consistent behaviour, instance and class variables should be correctly


initialised.

To encourage modular and reusable code, method parameters should be used to


send data to a method and receive return values.

In conclusion, the accessibility and longevity of variables in a Java programme


depend on the variables' scope. Developers can produce more productive, readable,
and maintainable code by comprehending and using variable scope efficiently. The
following time you develop Java code, be sure to pay special attention to variable
scope and take full advantage of its features.

Literals in Java
In Java, literal is a notation that represents a fixed value in the source code. In
lexical analysis, literals of a given type are generally known as tokens. In this
section, we will discuss the term literals in Java.

Literals
In Java, literals are the constant values that appear directly in the program. It can
be assigned directly to a variable. Java has various types of literals. The following
figure represents a literal.

Types of Literals in Java


There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:

1. int decVal = 26;


2. int octVal = 067;
3. int hexVal = 0x1a;
4. int binVal = 0b11010;
5. Character Literals
6. A character literal is expressed as a character or an escape sequence,
enclosed in a single quote ('') mark. It is always a type of char. For
example, 'a', '%', '\u000d', etc.
7. String Literals
8. String literal is a sequence of characters that is enclosed
between double quotes ("") marks. It may be alphabet, numbers, special
characters, blank space, etc. For example, "Jack", "12345", "\n", etc.
9. Floating Point Literals
10.The vales that contain decimal are floating literals. In Java, float and double
primitive types fall into floating-point literals. Keep in mind while dealing with
floating-point literals.

o Floating-point literals for float type end with F or f. For example, 6f, 8.354F,
etc. It is a 32-bit float literal.
o Floating-point literals for double type end with D or d. It is optional to write D
or d. For example, 6d, 8.354D, etc. It is a 64-bit double literal.
o It can also be represented in the form of the exponent.

Floating:

1. float length = 155.4f;

Decimal:

1. double interest = 99658.445;

Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0
and 1. For example, true, 0, etc.

1. boolean isEven = true;

Syntax of Symbolic Constants


final data_type CONSTANT_NAME = value;
 final: The final keyword indicates that the value of the constant cannot be
changed once it is initialized.
 data_type: The data type of the constant such as int, double, boolean, or
String.
 CONSTANT_NAME: The name of the constant which should be written in all
capital letters with underscores separating words.
 value: The initial value of the constant must be of the same data type as the
constant.
Initializing a symbolic constant:
final double PI = 3.14159;
Example:
 Java

// Java Program to print an Array

import java.io.*;

public class Example {

public static final int MAX_SIZE = 10;

public static void main(String[] args)

int[] array = new int[MAX_SIZE];

for (int i = 0; i < MAX_SIZE; i++) {

array[i] = i * 2;
}

System.out.print("Array: ");

for (int i = 0; i < MAX_SIZE; i++) {

System.out.print(array[i] + " ");

System.out.println();

Output
Array: 0 2 4 6 8 10 12 14 16 18

Operators:

constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to
perform various calculations and functions be it logical, arithmetic, relational, etc.
They are classified based on the functionality they provide. Here are a few types:
1. Arithmetic Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operator

Arithmetic Operators

These operators involve the mathematical operators that can be used to


perform various simple or advanced arithmetic operations on the primitive data
types referred to as the operands. These operators consist of various unary and
binary operators that can be applied on a single or two operands. Let’s look at
the various operators that Java has to provide under the arithmetic operators.
import java.util.Scanner;

public class ArithmeticOperators {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter the first number: ");


double num1 = sc.nextDouble();

System.out.print("Enter the second number: ");


double num2 = sc.nextDouble();

double sum = num1 + num2;


double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;

System.out.println("The sum of the two numbers is: " + sum);


System.out.println("The difference of the two numbers is: " +
difference);
System.out.println("The product of the two numbers is: " + product);
System.out.println("The quotient of the two numbers is: " +
quotient);
}
}
Input
Enter the first number: 20
Enter the second number: 10
Output
The sum of the two numbers is: 30.0
The difference of the two numbers is: 10.0
The product of the two numbers is: 200.0
The quotient of the two numbers is: 2.0

Operator 3: Increment(++)
It is used to increment the value of an integer. It can be used in two separate
ways:
3.1: Post-increment operator
When placed after the variable name, the value of the operand is incremented but
the previous value is retained temporarily until the execution of this statement and
it gets updated before the execution of the next statement.
Syntax:
num++
Illustration:
num = 5
num++ = 6
3.2: Pre-increment operator
When placed before the variable name, the operand’s value is incremented
instantly.
Syntax:
++num
Illustration:
num = 5
++num = 6
Operator 4: Decrement ( — )
It is used to decrement the value of an integer. It can be used in two separate
ways:
4.1: Post-decrement operator
When placed after the variable name, the value of the operand is decremented but
the previous values is retained temporarily until the execution of this statement and
it gets updated before the execution of the next statement.
Syntax:
num--
Illustration:
num = 5
num-- = 5 // Value will be decremented before execution of next
statement.
4.2: Pre-decrement operator
When placed before the variable name, the operand’s value is decremented
instantly.
Syntax:
--num
Illustration:
num = 5
--num = 5 //output is 5, value is decremented before execution of
next statement
Operator 5: Bitwise Complement(~)
This unary operator returns the one’s complement representation of the input value
or operand, i.e, with all bits inverted, which means it makes every 0 to 1, and every
1 to 0.
Syntax:
~(operand)
Illustration:
a = 5 [0101 in Binary]
result = ~5

This performs a bitwise complement of 5


~0101 = 1010 = 10 (in decimal)

Then the compiler will give 2’s complement


of that number.
2’s complement of 10 will be -6.
result = -6
Example:
 Java

// Java program to Illustrate Unary

// Bitwise Complement Operator

// Importing required classes

import java.io.*;

// Main class

class GFG {
// Main driver method

public static void main(String[] args)

// Declaring a variable

int n1 = 6, n2 = -2;

// Printing numbers on console

System.out.println("First Number = " + n1);

System.out.println("Second Number = " + n2);

// Printing numbers on console after

// performing bitwise complement

System.out.println(

n1 + "'s bitwise complement = " + ~n1);

System.out.println(

n2 + "'s bitwise complement = " + ~n2);

Output

First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1
Example program in Java that implements all basic unary operators for user
input:
 Java

import java.util.Scanner;

public class UnaryOperators {

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// fro user inputs here is the code.

// System.out.print("Enter a number: ");

// int num = sc.nextInt();

int num = 10;

int result = +num;

System.out.println(
"The value of result after unary plus is: "

+ result);

result = -num;

System.out.println(

"The value of result after unary minus is: "

+ result);

result = ++num;

System.out.println(

"The value of result after pre-increment is: "

+ result);

result = num++;

System.out.println(

"The value of result after post-increment is: "

+ result);

result = --num;
System.out.println(

"The value of result after pre-decrement is: "

+ result);

result = num--;

System.out.println(

"The value of result after post-decrement is: "

+ result);

Output

The value of result after unary plus is: 10


The value of result after unary minus is: -10
The value of result after pre-increment is: 11
The value of result after post-increment is: 11
The value of result after pre-decrement is: 11
The value of result after post-decrement is: 11

You might also like