SlideShare a Scribd company logo
1 of 38
Java Variables, Data Types
and Operators
Java Variables
• A variable is a container which holds the value while the Java program is executed.
• A variable is the name of a reserved area allocated in memory. In other words,
variable is a name of the memory location.
• Its value can be changed.
• A variable is assigned with a data type.
• int data=50; //Here data is variable
• Three types of variables in java: local, instance and static.
• Two types of data types: primitive and non-primitive.
Declaring (Creating) Variables
Attention Python Programmers!
Java is a statically-typed programming language.
It means, all variables must be declared before its use.
That is why we need to declare variable's type and name.
Syntax:
type variable-name = value;
Examples:
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Example:
public class Main {
public static void main(String[] args)
{
String name = "John";
System.out.println(name);
}
}
Data Types in Java
• Data types specify the different sizes and values that can be stored in the variable. Two
data types in Java are Primitive and Non-primitive (Reference/Object Data Types)
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127 default value 0
short 2 bytes Stores whole numbers from -32,768 to 32,767 default value 0
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647 default
value 0
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 default value 0L
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
default value 0.0f
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Default value is 0.0d
boolean 1 bit Stores true or false values, default value is false
char 2 bytes Stores a single character/letter or ASCII values
Default 'u0000‘
Range 'u0000' (or 0) to 'uffff' (or 65,535 inclusive)
Example:
public class Main {
public static void main(String[] args) {
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number
char myLetter = 'D'; // character
boolean myBool = true; // boolean
String myText = "Hello"; // String
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLetter);
System.out.println(myBool);
System.out.println(myText);
}
}
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the
final keyword (this will declare the variable as "final" or "constant",
which means unchangeable and read-only):
First try it without final and then with final keyword
Example:
public class Main {
public static void main(String[] args) {
final int myNum = 15;
myNum = 20; // will generate an error
System.out.println(myNum);
}
}
Example:
public class Main {
public static void main(String[] args) {
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
}
}
• Example:
public class Main {
• public static void main(String[] args) {
• int x = 5;
• int y = 6;
• System.out.println(x + y); // Print the value of x + y
• }
• }
Declaring Multiple Variables Variables
• Example:
public class Main {
public static void main(String[] args) {
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
}
}
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
• Example:
public class Main {
• public static void main(String[] args) {
• int x = 5;
• int y = 6;
• System.out.println(x + y); // Print the value of x + y
• }
• }
Decimal Hexadecimal and Octal Numbers
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these
number systems for literals.
public class Main {
public static void main(String[] args) {
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
System.out.println(decimal);
System.out.println(octal);
System.out.println(hexa);
}}
Scientific Numbers
• A floating point number can also be a scientific number with an "e" to
indicate the power of 10:
• Example:
public class Main {
public static void main(String[] args) {
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
}
}
Characters
• The char data type is used to store a single character. The character must
be surrounded by single quotes, like 'A' or 'c':
Guess the OUTPUT!
• Example:
public class Main {
public static void main(String[] args) {
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
}
}
Non-Primitive Data Types
• Non-primitive data types are called reference types because they refer to
objects.
• Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
• A primitive type has always a value, while non-primitive types can be null
• Default value of any reference variable is null
• A primitive type starts with a lowercase letter, while non-primitive types starts
with an uppercase letter
• The size of a primitive type depends on the data type, while non-primitive types
have all the same size.
• Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
• Eexamples can be Employee, Puppy, etc.
Java Type Casting
• Type casting is when you assign a value of one primitive data type to another type.
• In Java, there are two types of casting:
• Widening Casting (automatically) - converting a smaller type to a larger type size
• Narrowing Casting (manually) - converting a larger type to a smaller size type
byte -> short -> char -> int -> long -> float -> double
double -> float -> long -> int -> char -> short -> byte
Widening Casting
• 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);
System.out.println(myDouble);
}
}
Java Variable Example: Widening
• public class Simple{
• public static void main(String[] args){
• int a=10;
• float f=a;
• System.out.println(a);
• System.out.println(f);
• }}
Narrowing Casting
• Example:
• public class Simple{
• public static void main(String[] args){
• float f=10.5f;
• //int a=f;//Compile time error
• int a=(int)f;
• System.out.println(f);
• System.out.println(a);
• }}
Narrowing Casting
• Example:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Explicit casting: double to int
System.out.println(myDouble);
System.out.println(myInt);
}
}
Java Variable Example: Overflow
class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}}
Output:
130
-136
130 -126
Java Variable Example: Adding Lower Type
class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c);
}}
Types of Variables in Java
1) Local Variable: A variable declared inside the body of the method is called
local variable. You can use this variable only within that method and the
other methods in the class aren't even aware that the variable exists.
2) Instance Variable: A variable declared inside the class but outside the
body of the method, is called an instance variable.
• 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.
Identifiers
• All Java variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
• Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:
• The general rules for naming variables are:
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain whitespace
• Names can also begin with $ and _ (but we will not use it in this tutorial)
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words/key words cannot be identifiers for variables
Escape Sequences
Java language supports few special escape sequences for String and char literals
Notation Character represented
n Newline (0x0a)
r Carriage return (0x0d)
f Formfeed (0x0c)
b Backspace (0x08)
s Space (0x20)
t tab
" Double quote
' Single quote
 backslash
ddd Octal character (ddd)
uxxxx Hexadecimal UNICODE character (xxxx)
Java Literals
• A literal is a source code representation of a fixed value. They are
represented directly in the code without any computation.
• Literals can be assigned to any primitive type variable.
• For Example:
byte a = 68;
char a = 'A';
Operators in Java
Precedence wise
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
• Example:
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}}
• Example:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x + y);
System.out.println(x * y);
System.out.println(x / y);
System.out.println(x % y);
}
}
• Example:
public class Main {
public static void main(String[] args) {
int x = 5;
++x;
System.out.println(x);
--x;
System.out.println(x);
}
}
Java Assignment Operators
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Java Assignment Operators
• Example:
public class Main {
public static void main(String[] args) {
int x = 5;
x += 3;
System.out.println(x);
x -= 3;
System.out.println(x);
x ^= 3;
System.out.println(x);
}
}
Java Comparison Operators
Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or
equal to
x >= y
<= Less than or equal
to
x <= y
Java Comparision Operators
• Example:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x == y); // returns false because 5 is not equal to 3
System.out.println(x >= y); // returns true because 5 is greater, or equal, to 3
}
}
Java Logical Operators
Operat
or
Name Description Example
&& Logical and Returns true if both statements are
true
x < 5 && x < 10
|| Logical or Returns true if one of the
statements is true
x < 5 || x < 4
! Logical not Reverse the result, returns false if
the result is true
!(x < 5 && x < 10)
Java Logical Operators
• Example:
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 && x < 10);
// returns true because 5 is greater than 3 AND 5 is less than 10
System.out.println(x > 3 || x < 4);
// returns true because one of the conditions are true (5 is greater than 3, but 5 is not less
than 4
System.out.println(!(x > 3 && x < 10));
// returns false because ! (not) is used to reverse the result
}}

More Related Content

Similar to Java Variables, Data Types and Operators Guide

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 conceptmanish kumar
 
Computational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptxComputational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptx320126552027SURAKATT
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignmentmcollison
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART IHari Christian
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 CertificationsGiacomo Veneri
 

Similar to Java Variables, Data Types and Operators Guide (20)

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
 
JAVA LESSON-01.pptx
JAVA LESSON-01.pptxJAVA LESSON-01.pptx
JAVA LESSON-01.pptx
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Computational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptxComputational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptx
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02basics
02basics02basics
02basics
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART I
 
Java - Basic Datatypes.pptx
Java - Basic Datatypes.pptxJava - Basic Datatypes.pptx
Java - Basic Datatypes.pptx
 
C language
C languageC language
C language
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java Basic day-1
Java Basic day-1Java Basic day-1
Java Basic day-1
 
ITFT - Java
ITFT - JavaITFT - Java
ITFT - Java
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Java Variables, Data Types and Operators Guide

  • 1. Java Variables, Data Types and Operators
  • 2. Java Variables • A variable is a container which holds the value while the Java program is executed. • A variable is the name of a reserved area allocated in memory. In other words, variable is a name of the memory location. • Its value can be changed. • A variable is assigned with a data type. • int data=50; //Here data is variable • Three types of variables in java: local, instance and static. • Two types of data types: primitive and non-primitive.
  • 3. Declaring (Creating) Variables Attention Python Programmers! Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need to declare variable's type and name. Syntax: type variable-name = value; Examples: int myNum = 5; float myFloatNum = 5.99f; char myLetter = 'D'; boolean myBool = true; String myText = "Hello";
  • 4. Example: public class Main { public static void main(String[] args) { String name = "John"; System.out.println(name); } }
  • 5. Data Types in Java • Data types specify the different sizes and values that can be stored in the variable. Two data types in Java are Primitive and Non-primitive (Reference/Object Data Types)
  • 6. Java Primitive Data Types In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language.
  • 7. Data Type Size Description byte 1 byte Stores whole numbers from -128 to 127 default value 0 short 2 bytes Stores whole numbers from -32,768 to 32,767 default value 0 int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647 default value 0 long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 default value 0L float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits default value 0.0f double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits Default value is 0.0d boolean 1 bit Stores true or false values, default value is false char 2 bytes Stores a single character/letter or ASCII values Default 'u0000‘ Range 'u0000' (or 0) to 'uffff' (or 65,535 inclusive)
  • 8. Example: public class Main { public static void main(String[] args) { int myNum = 5; // integer (whole number) float myFloatNum = 5.99f; // floating point number char myLetter = 'D'; // character boolean myBool = true; // boolean String myText = "Hello"; // String System.out.println(myNum); System.out.println(myFloatNum); System.out.println(myLetter); System.out.println(myBool); System.out.println(myText); } }
  • 9. Final Variables If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only): First try it without final and then with final keyword Example: public class Main { public static void main(String[] args) { final int myNum = 15; myNum = 20; // will generate an error System.out.println(myNum); } }
  • 10. Example: public class Main { public static void main(String[] args) { String firstName = "John "; String lastName = "Doe"; String fullName = firstName + lastName; System.out.println(fullName); } }
  • 11. • Example: public class Main { • public static void main(String[] args) { • int x = 5; • int y = 6; • System.out.println(x + y); // Print the value of x + y • } • }
  • 12. Declaring Multiple Variables Variables • Example: public class Main { public static void main(String[] args) { int x = 5, y = 6, z = 50; System.out.println(x + y + z); } } int x, y, z; x = y = z = 50; System.out.println(x + y + z);
  • 13. • Example: public class Main { • public static void main(String[] args) { • int x = 5; • int y = 6; • System.out.println(x + y); // Print the value of x + y • } • }
  • 14. Decimal Hexadecimal and Octal Numbers byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these number systems for literals. public class Main { public static void main(String[] args) { int decimal = 100; int octal = 0144; int hexa = 0x64; System.out.println(decimal); System.out.println(octal); System.out.println(hexa); }}
  • 15. Scientific Numbers • A floating point number can also be a scientific number with an "e" to indicate the power of 10: • Example: public class Main { public static void main(String[] args) { float f1 = 35e3f; double d1 = 12E4d; System.out.println(f1); System.out.println(d1); } }
  • 16. Characters • The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': Guess the OUTPUT! • Example: public class Main { public static void main(String[] args) { char myVar1 = 65, myVar2 = 66, myVar3 = 67; System.out.println(myVar1); System.out.println(myVar2); System.out.println(myVar3); } }
  • 17. Non-Primitive Data Types • Non-primitive data types are called reference types because they refer to objects. • Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String). • A primitive type has always a value, while non-primitive types can be null • Default value of any reference variable is null • A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter • The size of a primitive type depends on the data type, while non-primitive types have all the same size. • Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. • Eexamples can be Employee, Puppy, etc.
  • 18. Java Type Casting • Type casting is when you assign a value of one primitive data type to another type. • In Java, there are two types of casting: • Widening Casting (automatically) - converting a smaller type to a larger type size • Narrowing Casting (manually) - converting a larger type to a smaller size type byte -> short -> char -> int -> long -> float -> double double -> float -> long -> int -> char -> short -> byte
  • 19. Widening Casting • 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); System.out.println(myDouble); } }
  • 20. Java Variable Example: Widening • public class Simple{ • public static void main(String[] args){ • int a=10; • float f=a; • System.out.println(a); • System.out.println(f); • }}
  • 21. Narrowing Casting • Example: • public class Simple{ • public static void main(String[] args){ • float f=10.5f; • //int a=f;//Compile time error • int a=(int)f; • System.out.println(f); • System.out.println(a); • }}
  • 22. Narrowing Casting • Example: public class Main { public static void main(String[] args) { double myDouble = 9.78d; int myInt = (int) myDouble; // Explicit casting: double to int System.out.println(myDouble); System.out.println(myInt); } }
  • 23. Java Variable Example: Overflow class Simple{ public static void main(String[] args){ //Overflow int a=130; byte b=(byte)a; System.out.println(a); System.out.println(b); }} Output: 130 -136 130 -126
  • 24. Java Variable Example: Adding Lower Type class Simple{ public static void main(String[] args){ byte a=10; byte b=10; //byte c=a+b;//Compile Time Error: because a+b=20 will be int byte c=(byte)(a+b); System.out.println(c); }}
  • 25. Types of Variables in Java 1) Local Variable: A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. 2) Instance Variable: A variable declared inside the class but outside the body of the method, is called an instance variable. • 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.
  • 26. Identifiers • All Java variables must be identified with unique names. • These unique names are called identifiers. • Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). • Note: It is recommended to use descriptive names in order to create understandable and maintainable code: • The general rules for naming variables are: • Names can contain letters, digits, underscores, and dollar signs • Names must begin with a letter • Names should start with a lowercase letter and it cannot contain whitespace • Names can also begin with $ and _ (but we will not use it in this tutorial) • Names are case sensitive ("myVar" and "myvar" are different variables) • Reserved words/key words cannot be identifiers for variables
  • 27. Escape Sequences Java language supports few special escape sequences for String and char literals Notation Character represented n Newline (0x0a) r Carriage return (0x0d) f Formfeed (0x0c) b Backspace (0x08) s Space (0x20) t tab " Double quote ' Single quote backslash ddd Octal character (ddd) uxxxx Hexadecimal UNICODE character (xxxx)
  • 28. Java Literals • A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. • Literals can be assigned to any primitive type variable. • For Example: byte a = 68; char a = 'A';
  • 29. Operators in Java Precedence wise Operator Type Category Precedence Unary postfix expr++ expr-- prefix ++expr --expr +expr -expr ~ ! Arithmetic multiplicative * / % additive + - Shift shift << >> >>> Relational comparison < > <= >= instanceof equality == != Bitwise bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | Logical logical AND && logical OR || Ternary ternary ? : Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
  • 30. • Example: public class Main { public static void main(String[] args) { int sum1 = 100 + 50; int sum2 = sum1 + 250; int sum3 = sum2 + sum2; System.out.println(sum1); System.out.println(sum2); System.out.println(sum3); }}
  • 31. • Example: public class Main { public static void main(String[] args) { int x = 5; int y = 2; System.out.println(x + y); System.out.println(x * y); System.out.println(x / y); System.out.println(x % y); } }
  • 32. • Example: public class Main { public static void main(String[] args) { int x = 5; ++x; System.out.println(x); --x; System.out.println(x); } }
  • 33. Java Assignment Operators Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 34. Java Assignment Operators • Example: public class Main { public static void main(String[] args) { int x = 5; x += 3; System.out.println(x); x -= 3; System.out.println(x); x ^= 3; System.out.println(x); } }
  • 35. Java Comparison Operators Operator Name Example == Equal to x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 36. Java Comparision Operators • Example: public class Main { public static void main(String[] args) { int x = 5; int y = 3; System.out.println(x == y); // returns false because 5 is not equal to 3 System.out.println(x >= y); // returns true because 5 is greater, or equal, to 3 } }
  • 37. Java Logical Operators Operat or Name Description Example && Logical and Returns true if both statements are true x < 5 && x < 10 || Logical or Returns true if one of the statements is true x < 5 || x < 4 ! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
  • 38. Java Logical Operators • Example: public class Main { public static void main(String[] args) { int x = 5; System.out.println(x > 3 && x < 10); // returns true because 5 is greater than 3 AND 5 is less than 10 System.out.println(x > 3 || x < 4); // returns true because one of the conditions are true (5 is greater than 3, but 5 is not less than 4 System.out.println(!(x > 3 && x < 10)); // returns false because ! (not) is used to reverse the result }}