CP-WEEK10
Java Programming: Data Types and Variables
1. Understanding Data Types
Importance: Data types are fundamental in Java programming as they define the size and type of data that can be stored in a variable.
Types of Data Types:
Primitive Data Types: These include basic types with pre-defined values.
Non-Primitive Data Types: Refer to objects created by the programmer, including classes, interfaces, and arrays.
2. The Eight Primitive Data Types in Java
byte: 1 byte, stores values from -128 to 127.
Example:
byte myNum = 100;
short: 2 bytes, stores values from -32,768 to 32,767.
Example:
short dollar = 5000;
int: 4 bytes, stores values from -2,147,483,648 to 2,147,483,647.
Example:
int myNum = 1000000;
long: 8 bytes, stores larger whole numbers; suffix with 'L'.
Example:
long myNum = 15000000000L;
float: 4 bytes, stores fractional numbers (6-7 decimal digits); suffix with 'f'.
Example:
float total = 5.75f;
double: 8 bytes, stores larger fractional numbers (15 decimal digits); suffix with 'd'.
Example:
double value = 555.7523d;
char: 2 bytes, stores a single character in single quotes.
Example:
char myGrade = 'F';
boolean: 1 bit, stores true or false values.
Example:
boolean isJavaFun = true;
3. Variable Declaration and Initialization
Declaration: Define the data type and variable name.
Example:
int a;
Initialization: Assign a valid value to a variable.
Example:
a = 5;orint b = 10;
Combining Declaration and Initialization: You can declare and initialize simultaneously.
Example:
double pi = 3.14;
4. Types of Variables in Java
Local Variables: Declared within a method, only accessible within that method.
Instance Variables: Declared outside methods, using the keyword
staticdetermines their behavior.Static Variables: Initialized once, at the start of program execution.
5. Working with Expressions
Expressions: Combinations of operators, literals, or constants, and variables returning a specific data type.
Example:
weight_lbs = 2.2 * weight_kg;
6. Java Operators
Types of Operators
Arithmetic Operators: Perform math operations.
Examples:
+,-,*,/,%(modulo)
Assignment Operators: Assign values to variables.
Examples:
=,+=,-=,*=,/=,%=, etc.
Relational Operators: Compare values, returning boolean.
Examples:
<,>,<=,>=,==,!=
Logical Operators: Evaluate logical expressions (true/false).
Examples:
&&(AND),||(OR),!(NOT)
Unary Operators: Operate on a single operand.
Examples:
++(increment),--(decrement),-(negative sign)
7. Summary of Key Concepts
The eight primitive data types in Java: byte, short, int, long, float, double, char, and boolean.
A variable serves as a named memory location to store values.
Expressions consist of operands and operators, with operator precedence affecting the evaluation order.
Operators, including arithmetic, assignment, relational, logical, and unary types, perform various functions in Java.