SlideShare a Scribd company logo
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.
• 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
Java Tokens in  java program   .    pptx
Java Tokens in  java program   .    pptx
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
Java Tokens in  java program   .    pptx
• 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 {
KIA,
Nano,
Maruti,
}
class EnumTest
{
public static void main(String args[])
{
Car c;
c = Car.Nano;
System.out.println("Value of c: " + c);
switch (c) {
case Maruti:
System.out.println("Maruti car");
break;
case KIA:
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[])
{
A a=new A(); // a instance variable
a.method();
}
}//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();
}
}
}
Example 2: Program to print half
pyramid a using numbers
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
• public class Main {
• public static void main(String[] args) {
• int rows = 5;
• for (int i = 1; i <= rows; ++i) {
• for (int j = 1; j <= i; ++j) {
• System.out.print(j + " ");
• }
• System.out.println();
• }
• }
• }
• Example 4: Inverted half
pyramid using *
* * * * *
* * * *
* * *
* *
*
Source Code
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
using numbers
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Source Code
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(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 {
public static void main(String[] args) {
int rows = 5, k = 0, count = 0, count1 = 0;
for (int i = 1; i <= rows; ++i) {
for (int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
++count;
}
while (k != 2 * i - 1) {
if (count <= rows - 1) {
System.out.print((i + k) + " ");
++count;
} else {
++count1;
System.out.print((i + k - 2 * count1) + " ");
}
++k;
}
count1 = count = k = 0;
System.out.println();
}
}
}
• 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.*;
public class SwitchStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int variable;
System.out.println("Please enter the variable
value 1,2,3 ");
variable=sc.nextInt();
switch(variable)
{
case 1:
System.out.println("The value of the variable = "+variable);
break;
case 2:
System.out.println("The value of the variable ="+variable);
break;
case 3:
System.out.println("The value of the variable ="+variable);
break;
default:
System.out.println("The value of the variable is neither 1
nor 2 nor 3");
}
}
}
package com.dataflair.switchcase;
import java.util.*;
public class SwitchStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int variable;
System.out.println("Please enter the
variable value");
variable=sc.nextInt();
switch(variable)
{
case 1:
System.out.println("The value of the
variable = "+variable);
case 2:
System.out.println("The value of the
variable = "+variable);
case 3:
System.out.println("Value of the variable =
"+variable);
default:
• System.out.println("The value of the
variable is neither 1 nor 2 nor 3");
• }
• }
• }
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.*;
public class NestedSwitch
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String course="java";
switch(course)
{
case "python":
System.out.println("Python was made by Guido Van
Rossum");
break;
case "java":
System.out.println("What version of Java are you
using?");
int version=sc.nextInt();
switch(version)
{
case 6:
System.out.println("That is old school!");
break;
case 8:
System.out.println("Wow, that’s great! Tons of
new features!");
break;
}
break;
case "c++":
System.out.println("C ++ was made by Bjarne
Stroustrup");
break;
}
}
}
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
• }
• }
// Java Program to check if an
object of the subclass
// is also an instance of the
superclass
// superclass
class Animal {
}
// subclass
class Dog extends Animal {
}
class Main {
public static void main(String[] args) {
// create an object of the subclass
Dog d1 = new Dog();
// checks if d1 is an instance of the
subclass
System.out.println(d1 instanceof
Dog); // prints true
// checks if d1 is an instance of the
superclass
System.out.println(d1 instanceof 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
// Print commands
System.out.println("i = " + i + "
b = " + b);
System.out.println(
"nConversion of double to
byte.");
// d % 256
b = (byte)d;
// Print commands
System.out.println("d = " + d + "
b= " + b);
}
}
/ Java Program to Illustrate Conversion of
// Integer and Double to Byte
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Declaring byte variable
byte b;
// Declaring and initializing integer and
double
int i = 257;
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
• 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.12
3,12.456));
System.out.println(Math.min(23.12
,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));
}
}
Ad

More Related Content

Similar to Java Tokens in java program . pptx (20)

Java_Roadmap.pptx
Java_Roadmap.pptxJava_Roadmap.pptx
Java_Roadmap.pptx
ssuser814cf2
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
SadhanaParameswaran
 
Java
JavaJava
Java
Zeeshan Khan
 
Java Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer ScienceJava Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer Science
AnezkaJaved
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptx
Srizan Pokrel
 
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
AssignmentjsnsnshshusjdnsnshhzudjdndndjdAssignmentjsnsnshshusjdnsnshhzudjdndndjd
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
tusharjain613841
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
University of Potsdam
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
Rakesh Madugula
 
JAVA programming language made easy.pptx
JAVA programming language made easy.pptxJAVA programming language made easy.pptx
JAVA programming language made easy.pptx
Sunila31
 
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf VsjsjsnhehehJAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
ssuserb1a18d
 
Multi Threading- in Java WPS Office.pptx
Multi Threading- in Java WPS Office.pptxMulti Threading- in Java WPS Office.pptx
Multi Threading- in Java WPS Office.pptx
ManasaMR2
 
Annotations
AnnotationsAnnotations
Annotations
Knoldus Inc.
 
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptxJava UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
hofon47654
 
Unit 1
Unit 1Unit 1
Unit 1
LOVELY PROFESSIONAL UNIVERSITY
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
SadhanaParameswaran
 
Java Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer ScienceJava Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer Science
AnezkaJaved
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptx
Srizan Pokrel
 
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
AssignmentjsnsnshshusjdnsnshhzudjdndndjdAssignmentjsnsnshshusjdnsnshhzudjdndndjd
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
tusharjain613841
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
Rakesh Madugula
 
JAVA programming language made easy.pptx
JAVA programming language made easy.pptxJAVA programming language made easy.pptx
JAVA programming language made easy.pptx
Sunila31
 
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf VsjsjsnhehehJAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
ssuserb1a18d
 
Multi Threading- in Java WPS Office.pptx
Multi Threading- in Java WPS Office.pptxMulti Threading- in Java WPS Office.pptx
Multi Threading- in Java WPS Office.pptx
ManasaMR2
 
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptxJava UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
hofon47654
 

Recently uploaded (20)

five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Resistance measurement and cfd test on darpa subboff model
Resistance measurement and cfd test on darpa subboff modelResistance measurement and cfd test on darpa subboff model
Resistance measurement and cfd test on darpa subboff model
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIHlecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
Abodahab
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIHlecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
Abodahab
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Ad

Java Tokens in java program . pptx

  • 1. 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
  • 2. • 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.
  • 3. • Java token includes the following: • Keywords • Identifiers • Literals • Operators • Separators • Comments
  • 4. • 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:
  • 5. • 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.
  • 6. • 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
  • 9. 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
  • 11. • 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 */.
  • 12. 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.
  • 13. • 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.
  • 14. • Syntax for Java Constants • static final datatype identifier_name = constant; • Example: • static final float PI = 3.14f;
  • 15. • public class Declaration { • static final double PI = 3.14; • public static void main(String[] args) { • System.out.println("Value of PI: " + PI); • } • }
  • 16. • 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.
  • 17. • 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); • } • }
  • 18. • 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); • } • }
  • 19. • 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.
  • 20. enum Car { KIA, Nano, Maruti, } class EnumTest { public static void main(String args[]) { Car c; c = Car.Nano; System.out.println("Value of c: " + c); switch (c) { case Maruti: System.out.println("Maruti car"); break; case KIA: System.out.println("KIA car"); break; case Nano: System.out.println("Nano car"); break; } } }
  • 21. • 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
  • 22. • Types of Variables • There are three types of variables in Java: • local variable • instance variable • static variable
  • 23. • 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.
  • 24. public class A { static int m=100;//static variable void method() { int n=90;//local variable } public static void main(String args[]) { A a=new A(); // a instance variable a.method(); } }//end of clas
  • 25. • 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.
  • 27. 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); } } }
  • 28. • 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 } }
  • 29. 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 } } }
  • 30. 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 } } }
  • 31. 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(); } } }
  • 32. Example 2: Program to print half pyramid a using numbers 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 • public class Main { • public static void main(String[] args) { • int rows = 5; • for (int i = 1; i <= rows; ++i) { • for (int j = 1; j <= i; ++j) { • System.out.print(j + " "); • } • System.out.println(); • } • } • }
  • 33. • Example 4: Inverted half pyramid using * * * * * * * * * * * * * * * * Source Code 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(); } } }
  • 34. Example 5: Inverted half pyramid using numbers 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 Source Code 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(j + " "); } System.out.println(); } } }
  • 35. 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(); } } }
  • 36. Example 7: Program to print pyramid using numbers public class Main { public static void main(String[] args) { int rows = 5, k = 0, count = 0, count1 = 0; for (int i = 1; i <= rows; ++i) { for (int space = 1; space <= rows - i; ++space) { System.out.print(" "); ++count; } while (k != 2 * i - 1) { if (count <= rows - 1) { System.out.print((i + k) + " "); ++count; } else { ++count1; System.out.print((i + k - 2 * count1) + " "); } ++k; } count1 = count = k = 0; System.out.println(); } } }
  • 37. • 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 }
  • 38. 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); } } }
  • 39. • 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 }
  • 40. 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.
  • 41. 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); } } } }
  • 42. • 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 }
  • 43. package com.dataflair.switchcase; import java.util.*; public class SwitchStatement { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int variable; System.out.println("Please enter the variable value 1,2,3 "); variable=sc.nextInt(); switch(variable) { case 1: System.out.println("The value of the variable = "+variable); break; case 2: System.out.println("The value of the variable ="+variable); break; case 3: System.out.println("The value of the variable ="+variable); break; default: System.out.println("The value of the variable is neither 1 nor 2 nor 3"); } } }
  • 44. package com.dataflair.switchcase; import java.util.*; public class SwitchStatement { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int variable; System.out.println("Please enter the variable value"); variable=sc.nextInt(); switch(variable) { case 1: System.out.println("The value of the variable = "+variable); case 2: System.out.println("The value of the variable = "+variable); case 3: System.out.println("Value of the variable = "+variable); default: • System.out.println("The value of the variable is neither 1 nor 2 nor 3"); • } • } • }
  • 45. 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; } } }
  • 46. package com.dataflair.switchcase; import java.util.*; public class NestedSwitch { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String course="java"; switch(course) { case "python": System.out.println("Python was made by Guido Van Rossum"); break; case "java": System.out.println("What version of Java are you using?"); int version=sc.nextInt(); switch(version) { case 6: System.out.println("That is old school!"); break; case 8: System.out.println("Wow, that’s great! Tons of new features!"); break; } break; case "c++": System.out.println("C ++ was made by Bjarne Stroustrup"); break; } } }
  • 47. Java instanceof Operator • The instanceof operator in Java is used to check whether an object is an instance of a particular class or not.
  • 48. • class Simple1{ • public static void main(String args[]){ • Simple1 s=new Simple1(); • System.out.println(s instanceof Simple1);//true • } • }
  • 49. // Java Program to check if an object of the subclass // is also an instance of the superclass // superclass class Animal { } // subclass class Dog extends Animal { } class Main { public static void main(String[] args) { // create an object of the subclass Dog d1 = new Dog(); // checks if d1 is an instance of the subclass System.out.println(d1 instanceof Dog); // prints true // checks if d1 is an instance of the superclass System.out.println(d1 instanceof Animal); } }
  • 50. Instanceof operator class Test { public static void main(String args[]) { Test t=new Test(); System.out.println(t instanceof Test) ; } }
  • 51. 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.
  • 52. 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(); } }
  • 53. 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.
  • 54. 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
  • 55. // 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);
  • 56. 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.
  • 57. // 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; }
  • 58. // 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
  • 59. // Print commands System.out.println("i = " + i + " b = " + b); System.out.println( "nConversion of double to byte."); // d % 256 b = (byte)d; // Print commands System.out.println("d = " + d + " b= " + b); } } / Java Program to Illustrate Conversion of // Integer and Double to Byte // Main class class GFG { // Main driver method public static void main(String args[]) { // Declaring byte variable byte b; // Declaring and initializing integer and double int i = 257; double d = 323.142; // Display message System.out.println("Conversion of int to byte."); // i % 256 b = (byte)i;
  • 60. • 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.
  • 61. / 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
  • 62. • 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.
  • 63. // 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); } }
  • 64. Mathematical Function-1) min(): public class min { public static void main(String args[]) { System.out.println(Math.min(12.12 3,12.456)); System.out.println(Math.min(23.12 ,23.0)); } }
  • 65. 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)); } }
  • 66. 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)); } }
  • 67. 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)); } }
  • 68. 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)); } }