Data types variables operators
Data types variables operators
Operators
DATA TYPES
Data types
In Java, data types specify the size and type of values that can be stored in variables. Java is a strongly-
typed language, meaning each variable must be declared with a data type before it can be used. Java data
types are divided into two categories:
Types:
Primitive data types are the most basic data types built into Java. There are 8 primitive data types in Java:
Integer Types
Integer types are used to store whole numbers without decimal points.
Byte : Useful for saving memory in large arrays where memory savings are important. It is the smallest integer
data type.
short: Typically used when memory savings are important and the range of values is not large.
Int : The most commonly used integer data type.
Long: Used when a wider range than int is needed. Can store very large numbers.
Type Size (bits) Range Default Value
byte 8 -128 to 127 0
short 16 -32,768 to 32,767 0
int 32 -2^31 to 2^31 - 1 0
long 64 -2^63 to 2^63 - 1 0L
DATA TYPES
Examples:
A suffix L is required for long literals to distinguish them from int literals.
DATA TYPES
Floating-Point Types
These are used to store numbers with fractional parts (decimal points).
Float : Used when you need to save memory in large arrays of floating-point numbers. Precision is up to 7 decimal
digits.
double: The default data type for decimal values. Precision is up to 15 decimal digits. It is more precise than float.
Example:
A suffix f is required for float literals and d for double literals. In practice, double is preferred for
floating-point numbers unless memory is a concern.
Type Size (bits) Range Default Value
±3.4e−038 to
float 32 0.0f
±3.4e+038
±1.7e−308 to
double 64 0.0d
±1.7e+308
DATA TYPES
Character Type
Example:
The boolean data type represents only two possible values: true or false.
boolean: Used for simple flags that track true/false conditions. Its size is not precisely defined, but logically it
occupies one bit.
Example:
String
The String class is a special type of data type in Java used to represent sequences of characters.
Example:
String is a class, but Java allows you to use it like a primitive data type.
Strings are immutable in Java, meaning once they are created, their values cannot be changed.
DATA TYPES
Arrays
An array is a collection of elements of the same type stored in a single variable
Example:
.
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
Example:
class Person
{
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person("John", 25);
p1.displayInfo(); // Output: Name: John, Age: 25
}
}
Objects created from classes can have different states (values for variables).
Classes can have constructors, methods, and fields.
DATA TYPES
Example:
Integer num = 10; // Autoboxing from int to Integer
int primitiveNum = num; // Unboxing from Integer to int
Autoboxing: Automatically converts a primitive type to its corresponding wrapper object.
Unboxing: Automatically converts a wrapper object back to its corresponding primitive type.
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
VARIABLES
VARIABLES
In Java, variables are fundamental components used to store data that can be referenced and manipulated
within a program. Every variable in Java must be declared with a specific data type, which defines the kind of
data it can hold. Understanding the types, scope, lifetime, and initialization of variables is crucial for writing
efficient Java code.
Local Variables
Instance Variables (Non-static Fields)
Class Variables (Static Fields)
VARIABLES
Local Variables
Local variables are declared inside methods, constructors, or blocks (such as loops or conditionals) and are only
accessible within those methods or blocks. They are created when the method is called and destroyed once the
method execution is complete.
Key Points:
Characteristics:
Local variables do not have a default value, so you must explicitly initialize them before use.
They are stored in the stack memory.
The scope of local variables is limited to the method/block where they are declared.
VARIABLES
Syntax:
public class Main {
public void calculateSum() {
int a = 5; // Local variable
int b = 10; // Local variable
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
Example:
public class Main
{
public void displayMessage() {
String message = "Hello, World!"; // Local variable
System.out.println(message);
}
public static void main(String[] args) {
Main obj = new Main();
obj.displayMessage(); // Output: Hello, World!
}
}
VARIABLES
Instance Variables (Non-Static Fields)
Instance variables are declared inside a class but outside any method, constructor, or block. These variables
are created when an instance (or object) of the class is created and are destroyed when the object is
destroyed. They represent the properties or attributes of an object.
Key Points:
They have object-level scope, meaning each instance of the class has its own copy.
They can have access modifiers (private, public, protected).
They can be initialized when declared or within a constructor.
Characteristics:
Instance variables are initialized with default values if not explicitly initialized:
Numeric types (e.g., int, float) default to 0.
boolean defaults to false.
Object references (e.g., String) default to null.
They are stored in the heap memory because they are associated with objects.
Their scope is the entire class, but their accessibility depends on the access modifier.
VARIABLES
Syntax:
public class Main {
int x = 5; // Instance variable
Key Points:
They have class-level scope and are shared among all instances.
They are declared using the static keyword.
They can be accessed directly using the class name (without creating an object).
They are initialized once, when the class is loaded into memory.
Characteristics:
Can be accessed directly by the class name (ClassName.variableName), without creating an object of the class.
Class variables are shared among all instances, meaning any changes to the variable will affect all objects of the
class.
Class variables are initialized with default values, like instance variables.
They are stored in the method area (part of JVM memory where class structures are stored).
VARIABLES
Syntax:
public class Main
{
static int count = 0; // Class variable
All variables in Java need to be declared with a data type before they are used. The data type defines the type of
data that the variable can store, such as int, float, String, or a custom object type (like a class).
Syntax:
<data_type> <variable_name> = <initial_value>;
Example:
You can also declare multiple variables of the same type in a single statement:
int a = 5, b = 10, c = 20;
VARIABLES
Initialization of Variables
Local Variables: Must be initialized before use. If not, the compiler will throw an error.
Instance Variables: Automatically initialized with default values if not explicitly initialized.
Class Variables: Automatically initialized with default values. They are initialized once when the class is loaded.
Lifetime of Variables
Local Variables: Created when a method/block is called and destroyed once it completes execution.
Instance Variables: Created when an object is instantiated and destroyed when the object is destroyed (usually by
the garbage collector).
Class Variables: Created when the class is loaded and destroyed when the program ends or the class is unloaded.
Syntax:
final <data_type> <variable_name> = <initial_value>;
Example:
final int MAX_SPEED = 120; // This value cannot be modified later
Java Operators:
Arithmetic Operators: +, -, *, /, %
Unary Operators: +, -, ++, --, !
Relational Operators: ==, !=, >, <, >=, <=
Logical Operators: &&, ||, !
Assignment Operators: =, +=, -=, *=, /=, %=
Bitwise Operators: &, |, ^, ~, <<, >>, >>>
Ternary Operator: ?:
Instanceof Operator: instanceof
Java operators provide a wide range of functionality, from simple mathematical computations to advanced bitwise
manipulations, ensuring flexibility in programming and problem-solving.
OPERATORS
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication,
division, and modulus.
Example:
Notes: Integer division results in truncation. For example, 5 / 2 gives 2, not 2.5.
Modulus operator (%) returns the remainder of the division.
Operator Description Example
+ Addition a + b (adds a and b)
- Subtraction a - b (subtracts b from a)
* Multiplication a * b (multiplies a and b)
/ Division a / b (divides a by b)
% Modulus (remainder) a % b (remainder of a / b)
OPERATORS
Unary Operators
Unary operators operate on only one operand. They are used for incrementing, decrementing, negating a value, or
inverting a boolean.
Increment/Decrement:
Pre-increment (++a): Increases the value of a by 1, then returns a.
Post-increment (a++): Returns the value of a, then increases a by 1.
Pre-decrement (--a): Decreases the value of a by 1, then returns a.
Post-decrement (a--): Returns the value of a, then decreases a by 1.
Example:
int a = 5;
System.out.println(++a); // Pre-increment: a becomes 6, then prints 6
System.out.println(a++); // Post-increment: prints 6, then a becomes 7
System.out.println(a); // a is now 7
Operator Description Example
+ Unary plus (no effect) +a
- Unary minus (negation) -a
++ Increment (pre/post) ++a or a++
-- Decrement (pre/post) --a or a--
! Logical NOT (inverts boolean) !flag
OPERATORS
Relational (Comparison) Operators
Relational operators are used to compare two values. They return a boolean result (true or false).
Example:
Logical OR (||):
Returns true if either condition is true.
If the first condition is true, the second is not evaluated (short-circuiting).
Example:
boolean a = true, b = false;
boolean result1 = a && b; // false (because both are not true)
boolean result2 = a || b; // true (because at least one is true)
boolean result3 = !a; // false (inverts the value of 'a')
Example:
int a = 10;
a += 5; // a = a + 5 => a = 15
a -= 3; // a = a - 3 => a = 12
Example:
int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result1 = a & b; // result: 1 (binary: 0001)
int result2 = a | b; // result: 7 (binary: 0111)
int result3 = a ^ b; // result: 6 (binary: 0110)
int result4 = ~a; // result: -6 (binary: 1010, two's complement)
Operator Description Example
& Bitwise AND a&b
| Biwise OR a|b
^ Bitwise XOR a^b
~ Bitwise NOT ~a
<< Left shift a << 2
>> Right shift a >> 2
>>> Unsigned right shift a >>> 2
OPERATORS
Shift Operators:
<<: Left shift – shifts the bits to the left (multiplies by 2).
>>: Right shift – shifts the bits to the right (divides by 2).
>>>: Unsigned right shift – shifts bits to the right, and fills the leftmost bits with 0 (ignores the sign).
Example:
int a = 8; // binary: 1000
int result = a << 1; // result: 16 (binary: 10000, left shift by 1)
OPERATORS
Ternary (Conditional) Operator
The ternary operator is a shorthand for if-else statements. It takes three operands and returns a value based on a
condition.
Example:
In this example, result will be assigned the value of b if the condition (a > b) is false.
Operator Description Example
?: Ternary (conditional) condition ? expr1 : expr2
OPERATORS
Instanceof Operator
The instanceof operator checks whether an object is an instance of a specific class or subclass. It returns true if the
object is of the specified type, otherwise false.
Example:
String str = "Hello";
boolean result = str instanceof String; // true
Operator Description Example
instanceof Checks type of object obj instanceof ClassName
OPERATORS
Type Cast Operators
Type casting is used to convert one data type into another.
Example:
double a = 5.5;
int b = (int) a; // b = 5, explicit casting from double to int
Operator Description Example
(type) Type casting (int) 5.5
KEYWORDS
KEYWORDS
Java keywords are reserved words in the Java programming language that have a predefined meaning and cannot
be used as identifiers (variable names, function names, etc.). These keywords are integral to the syntax and
structure of Java programs.
Access Modifiers
These keywords define the access level for classes, methods, and variables.
public: Accessible from anywhere.
private: Accessible only within the declared class.
protected: Accessible within the same package and subclasses.
default (not a keyword but used for package-private access level): Accessible only within the same package.
KEYWORDS
Control Flow Statements
These keywords control the flow of execution in a Java program.
synchronized: Ensures that a block of code or method can only be accessed by one thread at a time.
volatile: Indicates that a variable's value may be changed unexpectedly by different threads.
transient: Prevents serialization of certain variables during the serialization process.
KEYWORDS
Miscellaneous Keywords
These are special-purpose keywords that serve specific functions in Java.
Single-line Comments
Single-line comments start with //. Anything written after // on the same line is treated as a comment.
Multi-line Comments
Multi-line comments (also known as block comments) start with /* and end with */. Everything between these
symbols is treated as a comment.
Documentation Comments (Javadoc)
Documentation comments start with /** and end with */. These comments are used to generate HTML
documentation using the javadoc tool.