Data Types
Java’s pass-by-value approach is designed for simplicity and consistency. By always passing a copy (either of the value or the reference), Java avoids the complexities of pass-by-reference, which can lead to unexpected behaviors in some cases. Java is not pass-by-reference
Primitive Data Types
- Pass-by-value (copy of value)
data-type.MAX_VALUE&data-type.MIN_VALUEare used to find max and min values of data types- It can be applied to Integer, Long, Short, Byte, Float, Double
- Cannot store
nullvalues - nibble is group of four bits or half of a byte
- Not modifiable Within Methods
- Increasing order of size:
| Type | Size | Range |
|---|---|---|
byte | 8 bits (1 byte) | -128 to 127 |
char | 16 bits (2 bytes) | Unicode characters |
short | 16 bits (2 bytes) | -32,768 to 32,767 |
int | 32 bits (4 bytes) | -(2³¹) to (2³¹-1) |
float | 32 bits (4 bytes) | Approximately ±3.40282347E+38 |
long | 64 bits (8 bytes) | -(2⁶³) to (2⁶³-1) |
double | 64 bits (8 bytes) | Approximately ±1.7976931348623157E+308 |
2’s Complement Process
- Example: -5
- Take positive number (5):
00000101 - Find 1’s complement (invert all bits):
11111010 - Add 1 to get 2’s complement:
11111011 - Result:
11111011represents -5 in memory
Reference Data Types
- Pass-by-value (copy of reference to the actual data)
- Can store
nullvalues - Examples include:
String, Arrays, Classes, Interfaces, Enums - Passed by value, but the reference points to the same memory location, allowing modifications within Methods to reflect outside
Binary Representation of Numbers
- Method
Integer.toBinaryString(x)converts an integer (only) to its binary string representation. For byte and short, must first convert to int - Leading zeros are omitted in the output for positive numbers
- Negative numbers are stored using 2’s complement representation
ASCII Values
-
ASCII only needs 7 bits
Characters Range A-Z 65 to 90 a-z 97 to 122 0-9 48 to 57
Literals
- Literals are constant values used in a program
- Every literal has a data type
- Integer Literals:
int a = 100;- Used for
byte,short, andintdata types - For
longliterals, appendLorl(e.g., 125L)
- Used for
- Floating-point Literals:
float b = 10.5f;- By default,
doubleliterals - For
floatliterals, appendForf(e.g., 12.56F)
- By default,
- Character Literals:
char c = 'A'; - String Literals:
String s = "Hello";- Not a primitive data type, but a class
- Creates String objects
- Boolean Literals:
boolean flag = true;(predefined literals)
Type Compatibility
- Integer literals can be assigned to
byte,short, andintvariables if within range - Long literals (
Lsuffix) cannot be assigned to smaller integer types - Double literals (default decimal numbers) cannot be assigned to
floatwithout explicit casting
Reading Different Data Types
int number = sc.nextInt(); // Integer
float decimal = sc.nextFloat(); // Float
String word = sc.next(); // String (single word)
String line = sc.nextLine(); // String (full line)