This document discusses Java variables, data types, and operators. It covers the basics of declaring variables in Java, including primitive and non-primitive data types. It also describes different types of variables, literals, casting, and operators such as arithmetic, assignment, comparison, and logical operators. Examples are provided to demonstrate variable declaration and usage of various 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';
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
}}