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

Java Tokens

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

Java Tokens

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

Java Tokens

• These statements and expressions are made up of tokens. In other


words, we can say that the expression and statement is a set of token

• The Java compiler breaks the line of code into text (words) is
called Java tokens. These are the smallest element of the
Java program
• public class Demo
• {
• public static void main(String args[])
• {
• System.out.println("javatpoint");
• }
• }
• In the above code snippet, public, class, Demo, {, static, void, main, (,
String, args, [, ], ), System, ., out, println, javatpoint, etc. are the Java
tokens.
• Types of Tokens
• Java token includes the following:
• Keywords
• Identifiers
• Literals
• Operators
• Separators
• 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:
• 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.
• 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:

• Integer
• Floating Point
• Character
• String
• Boolean
Operators: In 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.

• Arithmetic Operators
• Assignment Operators
• Relational Operators
• Unary Operators
• Logical Operators
• Ternary Operators
• Bitwise Operators
• Shift Operators
• 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.
• Parentheses (): It is used to call the functions and parsing the parameters.
• Curly Braces {}: The curly braces denote the starting and ending of a code block.
• Comma (,): It is used to separate two values, statements, and parameters.
• Assignment Operator (=): It is used to assign a variable and constant.
• Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
• 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:
• Line Oriented: It begins with a pair of forwarding slashes (//).
• Block-Oriented: It begins with /* and continues until it founds */.
Java Constant

• a constant is an entity in programming that is


immutable. In other words, the value that cannot be
change.
• Constants can be declared using Java's static and
final keywords
• The static keyword is used for memory management,
• and the final keyword signifies the property that the
variable's value cannot be changed
• It makes the primitive data types immutable.
• According to the Java naming convention the identifier
name must be in capital letters.
• Static and Final Modifiers
• The purpose to use the static modifier is to manage the memory.
• It also allows the variable to be available without loading any
instance of the class in which it is defined.
• The final modifier represents that the value of the variable cannot be
changed. It also makes the primitive data type immutable or
unchangeable.
• Syntax for Java Constants

• static final datatype identifier_name = constant;


• Example:
• static final float PI = 3.14f;
• public class Declaration {

• static final double PI = 3.14;

• public static void main(String[] args) {


• System.out.println("Value of PI: " + PI);
• }
•}
• Declaring Constant as Private
• Using the private access modifier before the constant name makes it
inaccessible from other classes. It means the value of the constant can
be accessed from within the class only.
• class ClassA {

• private static final double PI = 3.14;


•}
• public class ClassB {

• public static void main(String[] args) {


• System.out.println("Value of PI: " + ClassA.PI);
• }
•}
• Declaring Constant as Public
• Using the public access modifier before the constant name makes it available
anywhere in the program.

• class ClassA {
• public static final double PI = 3.14;
•}

• public class ClassB {

• public static void main(String[] args) {

• System.out.println("Value of PI: " + ClassA.PI);


• }
•}
• Constants using Enumeration- Enum
• The Enumeration is created using the enum keyword in Java.
• The Enumeration in Java is a list of named constants.
• It is a datatype that contains a fixed number of constants. It cannot be
changed at runtime or dynamically.
• It is similar to that of the final variables in Java.
• It is used for defining class types in Java. Using enumeration in class,
the class can have constructor, methods, and instance variables.
enum Car {
class EnumTest
{

public static void main(String args[])

KIA,
{
Car c;
c = Car.Nano;
System.out.println("Value of c: " + c);

Nano,
switch (c) {
case Maruti:
System.out.println("Maruti car");
break;
case KIA:

Maruti,
System.out.println("KIA car");
break;
case Nano:
System.out.println("Nano car");

}
break;
}
}
}
• 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
• A variable is the name of a reserved area allocated in memory

• int data=10;//Here data is variable


• Types of Variables
• There are three types of variables in Java:
• local variable
• instance variable
• static variable
• 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.
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of clas
• Java Simple for Loop
• A simple for loop is the same as C/C++. We can initialize the variable,
check condition and increment/decrement value. It consists of four parts:
1.Initialization: It is the initial condition which is executed once when the
loop starts. Here, we can initialize the variable, or we can use an already
initialized variable. It is an optional condition.
2.Condition: It is the second condition which is executed each time to test
the condition of the loop. It continues execution until the condition is
false. It must return boolean value either true or false. It is an optional
condition.
3.Increment/Decrement: It increments or decrements the variable value.
It is an optional condition.
4.Statement: The statement of the loop is executed each time until the
second condition is false.
Syntax

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


2.//statement or code to be executed
3.}
Example:
ForExample.java
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
• Java Nested for Loop
• If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever
outer loop executes.

Example:
NestedForExample.java
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
public class PyramidExample2 {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
public class Main {

public static void main(String[] args) {


char last = 'E', alphabet = 'A';

for (int i = 1; i <= (last - 'A' + 1); ++i) {


for (int j = 1; j <= i; ++j) {
System.out.print(alphabet + " ");
}
++alphabet;

System.out.println();
}
}
}
• public class Main {

Example 2: Program to print half


• public static void main(String[] args) {
pyramid a using numbers
• int rows = 5;
1
12 • for (int i = 1; i <= rows; ++i) {
123 • for (int j = 1; j <= i; ++j) {
• System.out.print(j + " ");
1234
• }
12345 • System.out.println();
• }
• }
• }
• Example 4: Inverted half Source Code
pyramid using *
public class Main {
*****
**** public static void main(String[] args) {
*** int rows = 5;

** for (int i = rows; i >= 1; --i) {


* for (int j = 1; j <= i; ++j) {
System.out.print("* ");
}
System.out.println();
}
}
}
Example 5: Inverted half pyramid Source Code
using numbers
public class Main {
12345
1234 public static void main(String[] args) {
123 int rows = 5;

12
for (int i = rows; i >= 1; --i) {
1 for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Example 6: Program to print full pyramid using *
public class Pyramid {

public static void main(String[] args) {


int rows = 5, k = 0;

for (int i = 1; i <= rows; ++i, k = 0) {


for (int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
}

while (k != 2 * i - 1) {
System.out.print("* ");
++k;
}

System.out.println();
}
}
}
Example 7: Program to print pyramid using numbers

public class Main { if (count <= rows - 1) {


System.out.print((i + k) + " ");
++count;
public static void main(String[] args) { } else {
int rows = 5, k = 0, count = 0, count1 = 0; ++count1;
System.out.print((i + k - 2 * count1) + " ");
}
for (int i = 1; i <= rows; ++i) {
for (int space = 1; space <= rows - i; ++space) { ++k;
System.out.print(" "); }
count1 = count = k = 0;
++count;
} System.out.println();
}
while (k != 2 * i - 1) { }
}
• Java for-each Loop
• The for-each loop is used to traverse array or collection in Java. It is
easier to use than simple for loop because we don't need to increment
value and use subscript notation.
• It works on the basis of elements and not the index. It returns element one
by one in the defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
ForEachExample.java
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
• Java Labeled For Loop
• We can have a name of each Java for loop. To do so, we use label before the
for loop. It is useful while using the nested for loop as we can
break/continue specific for loop.

Syntax:
labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}
LabeledForExample.java
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}

If you use break bb;, it will break inner loop only which is the default behaviour of any loop.
public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
• What is a Switch Case in Java?
• Switch case in Java is essential for avoiding redundant if-else statements in a
program.
switch(variable_name)
{
case value1:
//code to be executed if variable_name=value1
break;
case value2:
//code to be executed if variable_name=value2
break;

default:
//code to be executed if variable_name=value3
}
package com.dataflair.switchcase; {
import java.util.*; case 1:
System.out.println("The value of the variable =
"+variable);
public class SwitchStatement { break;
case 2:
public static void main(String[] args) { System.out.println("The value of the variable
="+variable);
break;
Scanner sc = new Scanner(System.in); case 3:
System.out.println("The value of the variable
="+variable);
int variable;
break;
System.out.println("Please enter the variable default:
value 1,2,3 ");
System.out.println("The value of the variable is neither 1
nor 2 nor 3");
variable=sc.nextInt(); }

}
switch(variable) }
switch(variable)
package com.dataflair.switchcase; {
import java.util.*; case 1:
System.out.println("The value of the variable =
"+variable);
public class SwitchStatement {
case 2:
System.out.println("The value of the variable =
public static void main(String[] args) { "+variable);
case 3:
Scanner sc = new Scanner(System.in); System.out.println("Value of the variable =
"+variable);
default:
int variable;
• System.out.println("The value of the variable
System.out.println("Please enter the is neither 1 nor 2 nor 3");
variable value");
• }
• }
variable=sc.nextInt(); • }
package com.dataflair.java.switchcase;
public class SwitchStrings
{
public static void main(String[] args) {
String course="java";
switch(course)
{
case "python":
System.out.println("Python was made by Guido Van Rossum");
break;
case "java":
System.out.println("Java was made by James Gosling! It is one of Shraman's favourites!");
break;
case "c++":
System.out.println("C ++ was made by Bjarne Stroustrup");
break;

}
}
}
package com.dataflair.switchcase;
import java.util.*;
{
case 6:
public class NestedSwitch System.out.println("That is old school!");
{ break;
public static void main(String[] args) { case 8:
Scanner sc = new Scanner(System.in); System.out.println("Wow, that’s great! Tons
of new features!");
break;
String course="java";
switch(course)
}
{
break;
case "python":
case "c++":
System.out.println("Python was made by Guido
Van Rossum"); System.out.println("C ++ was made by Bjarne
Stroustrup");
break;
break;
case "java":
System.out.println("What version of Java are you
using?"); }
int version=sc.nextInt(); }
switch(version) }
Java instanceof Operator

• The instanceof operator in Java is used to check whether an object is


an instance of a particular class or not.
• class Simple1{
• public static void main(String args[]){
• Simple1 s=new Simple1();
• System.out.println(s instanceof Simple1);//true
• }
•}
class Main {
// Java Program to check if an public static void main(String[] args) {
object of the subclass
// create an object of the subclass
// is also an instance of the
Dog d1 = new Dog();
superclass
// checks if d1 is an instance of the
// superclass subclass
System.out.println(d1 instanceof Dog);
class Animal { // prints true
}
// checks if d1 is an instance of the
superclass
// subclass System.out.println(d1 instanceof
class Dog extends Animal { Animal); }
} }
Instanceof operator
class Test
{
public static void main(String
args[])
{
Test t=new Test();
System.out.println(t instanceof
Test) ;
}
}
Dot Operator

• It is just a syntactic element. It denotes the separation of class from a


package, separation of method from the class, and separation of a
variable from a reference variable. It is also known
as separator or period or member operator.

It is used to separate a variable and method from a reference variable.


It is also used to access classes and sub-packages from a package.
It is also used to access the member of a package or a class.
public class DotOperatorExample1
{
void display()
{
double d = 67.54;
//casting double type to integer
int i = (int)d;
System.out.println(i);
}
public static void main(String args[])
{
DotOperatorExample1 doe = new DotOperatorExample1();
//method calling
doe.display();
}
}
Type Casting in Java

• In Java, type casting is a method or process that converts a data type


into another data type
• Two types
• manually - The automatic conversion is done by the compiler
• automatically- manual conversion performed by the programmer.
Widening or Automatic/Implicit Type Conversion

• Widening conversion takes place when two data types are


automatically converted.
• This happens when:

• The two data types are compatible.


• When we assign a value of a smaller data type to a bigger data type.
• Converting a lower data type into a higher one is called widening type
casting.
• It is also known as implicit conversion or down casting
• It is safe because there is no chance to lose data
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
int i = 100;

// Automatic type conversion


// Integer to long type
long l = i;

// Automatic type conversion


// long to float type
float f = l;

// Print and display commands


System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
Narrowing/Explicit/Up casting Type Casting

• Converting a higher data type into a lower one is


called narrowing type casting
• It is also known as explicit conversion or casting up

• It is done manually by the programmer.


• If we do not perform casting then the compiler reports a compile-time
error.
// Java program to illustrate Incompatible data Type
// for Explicit Type Conversion

// Main class
public class GFG {

// Main driver method


public static void main(String[] argv)
{

// Declaring character variable


char ch = 'c';
// Declaringinteger variable
int num = 88;
// Trying to insert integer to character
ch = num;
}
}
// Java program to Illustrate Explicit Type Conversion

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Double datatype
double d = 100.04;

// Explicit type casting by forcefully getting


// data from long datatype to integer type
long l = (long)d;

// Explicit type casting


int i = (int)l;

// Print statements
System.out.println("Double value " + d);

// While printing we will see that


// fractional part lost
System.out.println("Long value " + l);

// While printing we will see that


// fractional part lost
/ Java Program to Illustrate Conversion of // Print commands
// Integer and Double to Byte System.out.println("i = " + i + " b
= " + b);
// Main class System.out.println(
class GFG { "\nConversion of double to
byte.");
// Main driver method
public static void main(String args[]) // d % 256
{
b = (byte)d;
// Declaring byte variable
byte b;
// Print commands
// Declaring and initializing integer and double System.out.println("d = " + d + " b=
int i = 257; " + b);
double d = 323.142; }
}
// Display message
System.out.println("Conversion of int to byte.");

// i % 256
b = (byte)i;
• Type Promotion in Expressions
• While evaluating expressions, the intermediate value may exceed the
range of operands and hence the expression value will be promoted.
Some conditions for type promotion are:
1.Java automatically promotes each byte, short, or char operand to int
when evaluating an expression.
2.If one operand is long, float or double the whole expression is
promoted to long, float, or double respectively.
/ Java program to Illustrate Type promotion in Expressions

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Declaring and initializing primitive types


byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

// The Expression
double result = (f * b) + (i / c) - (d * s);

// Printing the result obtained after


// all the promotions are done
System.out.println("result = " + result);
}
• Explicit Type Casting in Expressions
• While evaluating expressions, the result is automatically updated to a
larger data type of the operand. But if we store that result in any
smaller data type it generates a compile-time error, due to which we
need to typecast the result.
// Java program to Illustrate Type Casting
// in Integer to Byte

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Declaring byte array


byte b = 50;

// Type casting int to byte


b = (byte)(b * 2);

// Display value in byte


System.out.println(b);
}
}
Mathematical Function-1) min():

public class min


{
public static void main(String
args[])
{
System.out.println(Math.min(12.1
23,12.456));
System.out.println(Math.min(23.1
2,23.0));
}
}
sqrt()
public class sqrtf
{
public static void main(String
args[])
{
double y=11.635;
System.out.println(Math.sqrt(16));
System.out.println(Math.sqrt(y));
}
}
pow()
public class powf
{
public static void main(String args[])
{
int x=2,y=3;
double a=11.635,b=2.76;
System.out.println(Math.pow(x,y));
System.out.println(Math.pow(a,b));
}
}
public class roundf
{
public static void main(String args[])
{
double d=100.675;
double e=100.500;
float f=100;
float g=90f;
System.out.println(Math.round(d));
System.out.println(Math.round(e));
System.out.println(Math.round(f));
System.out.println(Math.round(g));
}
}
abs()
public class absf
{
public static void main(String args[])
{
int a=-8;
double d=-100;
float f=-90;

System.out.println(Math.abs(a));
System.out.println(Math.abs(d));
System.out.println(Math.abs(f));
}
}

You might also like