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

Data types variables operators

The document provides an overview of data types, variables, and operators in Java. It details primitive and non-primitive data types, their characteristics, and examples, as well as the different types of variables including local, instance, and class variables. Additionally, it covers the various operators available in Java for performing operations on data.

Uploaded by

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

Data types variables operators

The document provides an overview of data types, variables, and operators in Java. It details primitive and non-primitive data types, their characteristics, and examples, as well as the different types of variables including local, instance, and class variables. Additionally, it covers the various operators available in Java for performing operations on data.

Uploaded by

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

Data types , Variables ,

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:

1.Primitive Data Types

2.Non-Primitive (Reference) Data Types


DATA TYPES
Primitive Data 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:

 byte smallNumber = 120;


 short shrtNumber = 1200;
 int myNumber = 5000000;
 long largeNumber = 10000000000L;

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:

float decimalNumber = 5.75f;


double largeDecimalNumber = 19.99;

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

 The char data type is used to store single characters.


 char: Represents a single 16-bit Unicode character. Java uses the Unicode character set, which allows for a
wide range of characters from various languages.

Example:

char letter = 'A';


char unicodeChar = '\u0041'; // Unicode representation of 'A'

Type Size (bits) Range Default Value


0 to 65,535 (Unicode
char 16 '\u0000'
values)
DATA TYPES
Boolean Type

 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:

boolean isJavaFun = true;


boolean isFishTasty = false;

Type Size Range Default Value


boolean 1 bit (theoretically) true or false false
DATA TYPES
Primitive Data Types:
Type Size (bits) Description
byte 8 Small integer (-128 to 127)
Small integer (-32,768 to
short 16
32,767)
int 32 Integer (-2^31 to 2^31-1)
Large integer (-2^63 to 2^63-
long 64
1)
Floating point number (single
float 32
precision)
Floating point number
double 64
(double precision)
Single character/letter
char 16
(Unicode)
boolean 1 bit Boolean value (true or false)
DATA TYPES
Non-Primitive Data Types
 Non-primitive data types (also known as reference types) are created by the programmer and include classes,
arrays, interfaces, and enums. Unlike primitive data types, non-primitive types refer to objects and are not stored
directly in variables. Instead, the variable stores a reference to the memory location of the object.

String
 The String class is a special type of data type in Java used to represent sequences of characters.

Example:

String message = "Hello, World!";

 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"};

 Arrays have a fixed size once created.


 Arrays are zero-indexed, meaning the first element has an index of 0.
DATA TYPES
Class
 A class is a blueprint for creating objects. Objects are instances of classes, and they can contain fields (variables)
and methods (functions) to define their behavior.

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

Key Differences Between Primitive and Non-Primitive Data Types:

Feature Primitive Types Non-Primitive Types


Size Fixed (depends on the type) Varies (depends on the object)
Default Value 0, false, or null null
Stored in heap, reference is stored in
Memory Location Stored directly in the stack
stack
Manipulation Operate directly on the data Operate via reference to the object
No (created by the user or Java
Predefined Types Yes (8 types)
libraries)
Null Assignment No (except for wrappers like Integer) Yes
DATA TYPES
Wrappers for Primitive Types
 Java provides wrapper classes for all primitive data types. These wrapper classes are useful when you need to treat
primitives as objects, such as in collections (e.g., ArrayList or HashMap).

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.

Types of Variables in Java


 Java provides three types of variables:

 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:

 Must be initialized before use.


 Have method/block-level scope.
 Cannot have access modifiers like public, private, or protected.

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

public static void main(String[] args) {


Main obj1 = new Main();
System.out.println(obj1.x); // Output: 5
}
}
Example:
public class Car {
String model;
int year;
Car(String model, int year) {
this.model = model;
this.year = year;
}
public void displayCarDetails() {
System.out.println("Car: " + model + " " + " (" + year + ")");
}
public static void main(String[] args) {
Car car1 = new Car(“Corolla", 2020);
car1.displayCarDetails(); // Output: Corolla (2020)
}
}
VARIABLES
Class Variables (Static Fields)
 Class variables are variables that are declared with the static keyword within a class but outside any method,
constructor, or block. These variables are shared among all instances of the class, meaning there is only one copy
of the class variable, regardless of the number of instances created.

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

public static void main(String[] args)


{
System.out.println(Main.count); // Output: 0
}
}
VARIABLES
Example:
public class Employee {
// Class variable (static)
static int employeeCount = 0;
// Instance variable
String name;
// Constructor to initialize instance variable
Employee(String name) {
this.name = name;
employeeCount++; // Increment employee count when a new object is created
}
// Static method to get the employee count
public static int getEmployeeCount() {
return employeeCount;
}
public static void main(String[] args) {
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Jane");
System.out.println("Total Employees: " + Employee.getEmployeeCount());
// Output: Total Employees: 2
}
}
VARIABLES
Variable Declaration in Java

 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:

int number = 10;


String message = "Hello, World!";

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.

Default Values for Variables:


Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Object (e.g., String, arrays) null
VARIABLES
Scope of Variables
 The scope of a variable refers to the region of the program where that variable is accessible.
 Local Variables: Limited to the method/block where they are declared.
 Instance Variables: Accessible by all methods within the class.
 Class Variables: Accessible by all methods within the class, but can also be accessed using the class name (even
without an object).

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.

Access Modifiers for Variables


 Java provides four access levels for variables, which control their visibility within a program:
 private: Accessible only within the class.
 default (no modifier): Accessible within the same package.
 protected: Accessible within the same package and subclasses in other packages.
 public: Accessible from any other class.
VARIABLES
Final Variables (Constants)
 In Java, variables can be made constant by using the final keyword. Once a final variable is assigned a
value, it cannot be changed.

Syntax:
final <data_type> <variable_name> = <initial_value>;

Example:
final int MAX_SPEED = 120; // This value cannot be modified later

 final variables must be initialized when declared or in the constructor.


 Typically, constants are declared in uppercase letters with underscores (_) separating words.
OPERATORS
 Operators in Java are special symbols that perform operations on variables and values. Java supports several types
of operators, including arithmetic, relational, logical, bitwise, assignment, and more. Here's a detailed breakdown of
the types of operators in Java, along with examples

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:

int a = 10, b = 20;


int sum = a + b; // sum = 30
int difference = b - a; // difference = 10
int product = a * b; // product = 200
int quotient = b / a; // quotient = 2
int remainder = b % a; // remainder = 0

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:

int a = 10, b = 20;


boolean result1 = a == b; // false
boolean result2 = a < b; // true
boolean result3 = a >= 10; // true

Operator Description Example


== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
OPERATORS
Logical Operators
 Logical operators are used to combine multiple boolean expressions or conditions.

Logical AND (&&):


 Returns true if both conditions are true.
 If the first condition is false, the second is not evaluated (short-circuiting).

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')

Operator Description Example


&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a
OPERATORS
Assignment Operators
 Assignment operators are used to assign values to variables.

Example:
int a = 10;
a += 5; // a = a + 5 => a = 15
a -= 3; // a = a - 3 => a = 12

Operator Description Example


= Simple assignment a = 10
a += 10 (equivalent to a = a +
+= Add and assign
10)
-= Subtract and assign a -= 5
*= Multiply and assign a *= 2
/= Divide and assign a /= 2
%= Modulus and assign a %= 2
OPERATORS
Bitwise Operators
 Bitwise operators work on bits and perform bit-level operations. These are used mainly in low-level programming,
such as in systems programming or when working with device drivers.

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:

int a = 10, b = 20;


int result = (a > b) ? a : b; // result = 20

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.

 if: Conditional statement.


 else: Specifies the block to execute if the if condition is false.
 switch: Multi-branch selection statement.
 case: Defines individual conditions for a switch.
 default: Specifies the block to execute if none of the case values match.
 break: Exits from the current loop or switch.
 continue: Skips the current iteration of a loop.
 for: Loop that iterates a block of code a fixed number of times.
 while: Loop that iterates a block of code while a condition is true.
 do: Executes the block of code at least once, then checks the condition.
 return: Exits from a method and optionally returns a value.
KEYWORDS
Data Types
These keywords define the type of variables.

 int: Integer data type (32-bit).


 byte: Integer data type (8-bit).
 short: Integer data type (16-bit).
 long: Integer data type (64-bit).
 float: Floating-point data type (32-bit).
 double: Floating-point data type (64-bit).
 char: Character data type (16-bit, stores Unicode characters).
 boolean: Data type with two possible values: true or false.
KEYWORDS
Class and Object Related Keywords
These keywords are used to define classes and create objects.

 class: Declares a class.


 interface: Declares an interface.
 extends: Used to indicate that a class is inheriting from a superclass.
 implements: Used to indicate that a class is implementing an interface.
 new: Creates new objects.
 this: Refers to the current instance of a class.
 super: Refers to the superclass of the current object.
 abstract: Used to declare an abstract class or method.
 final: Used to declare constants, prevent method overriding, and prevent inheritance of classes.
 static: Defines class-level methods and variables (shared across all instances).
 instanceof: Checks if an object is an instance of a specified class or interface.
KEYWORDS
Exception Handling
These keywords are used to handle errors and exceptions in Java.

 try: Defines a block of code that will be tested for exceptions.


 catch: Catches exceptions that occur in the try block.
 finally: A block of code that is always executed after try and catch.
 throw: Throws an exception explicitly.
 throws: Declares exceptions that a method might throw.

Synchronization and Concurrency


These keywords are used for multithreading and synchronization in Java.

 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.

 void: Specifies that a method does not return any value.


 enum: Declares an enumerated type (a fixed set of constants).
 package: Declares a package (a group of related classes).
 import: Imports classes or entire packages for use in the current class.
 assert: Used for debugging purposes, allowing you to test assumptions in the code.
 native: Specifies that a method is implemented in a platform-dependent code (usually in C/C++).
 strictfp: Restricts floating-point calculations to ensure portability.
 const: Not used (reserved for future use).
 goto: Not used (reserved for future use).

Keywords for Memory Management


These keywords are used to handle memory in Java.

 null: Represents no value or no object.


 finalize: A method that the garbage collector calls before an object is destroyed.
KEYWORDS
Table of Important Java Keywords
Keywords Purpose
abstract, class, extends, implements, interface Used for class, inheritance, and interface declarations.
public, private, protected, default (not a keyword) Access control modifiers.
int, byte, short, long, float, double, char, boolean Primitive data types.
new, this, super, static, final, void, enum Class and object-related operations.
try, catch, finally, throw, throws Exception handling keywords.
synchronized, volatile, transient Concurrency and memory-related keywords.
return, break, continue, for, while, do, switch, case,
Control flow statements.
default, if, else, instanceof
assert, native, strictfp, package, import, const, goto Miscellaneous keywords (some reserved, some unused).
COMMENTS
Comment Types 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.

Comment Type Syntax Use Case


Short notes or quick
Single-line comment //
explanations
Longer explanations or to
Multi-line comment /* ... */
temporarily disable code
For generating API
Javadoc comment /** ... */ documentation (used with
Javadoc)
Precedence & Associativity
Precedence Operator Type Associativity Precedence Operator Type Associativity
() Parentheses < Relational less than
1 [] Array subscript Left to Right <= Relational less than or equal
· Member selection 7> Relational greater than Left to right
++ Unary post-increment >= Relational greater than or equal
2 Right to left
-- Unary post-decrement instanceof Type comparison (objects only)
++ Unary pre-increment == Relational is equal to
-- Unary pre-decrement 8 Left to right
!= Relational is not equal to
+ Unary plus
9& Bitwise AND Left to right
3- Unary minus Right to left
10 ^ Bitwise exclusive OR Left to right
! Unary logical negation
11 | Bitwise inclusive OR Left to right
~ Unary bitwise complement
12 && Logical AND Left to right
(type) Unary type cast
* Multiplication 13 || Logical OR Left to right
4/ Division Left to right 14 ? : Ternary conditional Right to left
% Modulus = Assignment
+ Addition += Addition assignment
5 Left to right -= Subtraction assignment
- Subtraction 15 Right to left
<< Bitwise left shift *= Multiplication assignment
6 >> Bitwise right shift with sign extension Left to right /= Division assignment
>>> Bitwise right shift with zero extension %= Modulus assignment
THANK YOU

You might also like