Java Language Basics: Data Types, Variables, and Constants
This post covers the foundational concepts of Java programming, focusing on data types, variables, and constants. The content is based on the book "Java from Beginner to Expert," skipping the first two chapters.
3.1 Java Main Class Structure
A Java main class typically includes:
- Package declaration
- Import statements for API libraries
- Class declaration
- Declaration of member variables and local variables
- Main method definition
// Package declaration (must be in the Number package)
package Number;
// Class name must match the .class file name
public class MainClassExample {
// Member variable (global variable) declared with keyword static
static String greeting = "Hello";
// Main method
// public, static, void, accepts a String array parameter
public static void main(String[] args) {
// Local variable declared inside the method
String language = "Java";
System.out.println(greeting);
System.out.println(language);
}
}
3.2 Primitive Data Types
Java primitive data types fall into three categories:
- Numeric types (integer and floating-point)
- Character type
- Boolean type
Integer Types
Integers can be represented in decimal, octal (prefix 0), or hexadecimal (prefix 0x or 0X). Important rules:
- Decimal numbers cannot start with 0 except for the value 0 itself.
- Octal numbers must start with 0.
- Hexadecimal numbers must start with 0x or 0X.
| Data Type | Memory Space (8 bits = 1 byte) | Value Range |
|---|---|---|
| byte | 8 bits | -128 to 127 |
| short | 16 bits | -32768 to 32767 |
| int | 32 bits | -2147483648 to 2147483647 |
| long | 64 bits | -9223372036854775808 to 9223372036854775807 |
Floating-Point Types
float(single-precision, 32 bits)double(double-precision, 64 bits) is the default for floating-point literals. To use float, appendforFto the literal.
| Data Type | Memory Space | Value Range |
|---|---|---|
| float | 32 bits | 1.4E-45 to 3.4028235E38 |
| double | 64 bits | 4.9E-324 to 1.7976931348623157E308 |
Character Type
charstores a single 16-bit Unicode character, enclosed in single quotes' '.- Escape sequences start with a backslash
\.
| Escape Sequence | Meaning | Escape Sequence | Meaning |
|---|---|---|---|
\ddd |
1-3 digit octal | \uxxxx |
4-digit hexadecimal |
\' |
Single quote | \\ |
Backslash |
\t |
Tab | \r |
Carriage return |
\n |
Newline | \b |
Backspace |
\f |
Form feed |
Boolean Type
- Only two values:
trueandfalse.
public class DataTypeDemo {
public static void main(String[] args) {
System.out.println("---------------- 1. Integer Types ----------------");
// Integer type examples
int x1; // declare without initialization
int x2, y1; // declare multiple variables
int x3 = 450, y2 = -462; // declare and initialize
int maxInt = 2147483647; // max int value
// int overflow = 2147483648; // compilation error: integer too large
// For long literals exceeding int range, append L or l
long bigLong = 2147483648L; // L is recommended for readability
long anotherLong = 2147483648l;
// When adding different integer types, store result in the widest type
byte b = 124;
short s = 32564;
int i = 45784612;
long l = 46789451;
long result = b + s + i + l;
System.out.println("Sum result: " + result);
System.out.println("---------------- 2. Floating-Point Types ----------------");
// float f = 13.23; // compilation error: double cannot be converted to float
float flt = 13.23f; // explicit float literal
double dbl = 638.678; // double is default
double anotherDbl = 638.678d; // d is optional
System.out.println("Float value: " + flt);
System.out.println("Double value: " + anotherDbl);
System.out.println("---------------- 3. Character Type ----------------");
// char c = "a"; // compilation error: String cannot be converted to char
char letterA = 'a';
// Unicode value can be used directly
char charFromUnicode = 97; // 'a'
System.out.println("Direct char: " + letterA);
System.out.println("Char from Unicode: " + charFromUnicode);
char word = 'd', atSign = '@';
int unicode1 = 23045, unicode2 = 45213;
System.out.println("Unicode position of 'd': " + (int) word);
System.out.println("Unicode position of '@': " + (int) atSign);
System.out.println("Character at Unicode 23045: " + (char) unicode1);
System.out.println("Character at Unicode 45213: " + (char) unicode2);
System.out.println("Escape sequences:");
char backslash = '\\';
char star = '\u2605'; // Unicode star
char octalChar = '\123'; // octal 123 = 'S'
String quoteExample = "says \'OH, I see, thx.\'";
String tableExample = "Name1\tName2\nValue1\tValue2";
char before = 'a';
char backspace = '\b';
char after = 'c';
char formFeed = '\f';
System.out.println("Backslash: " + backslash + " Star: " + star);
System.out.println(quoteExample);
System.out.println(tableExample);
// Backspace moves cursor left, so output becomes "c" (overwrites 'a')
System.out.print(before);
System.out.print(backspace);
System.out.println(after);
System.out.println(formFeed);
}
}
3.3 Constants and Variables
Identifeirs
- Consist of letters, digits, underscores
_, and dollar signs$. Case-sensitive. - Cannot start with a digit.
- Cannot be a reserved keyword.
Keywords
| int | public | this | finally | boolean | abstract |
| continue | float | long | short | throw | throws |
| return | break | for | static | new | interface |
| if | goto | default | byte | do | case |
| strictfp | package | super | void | try | switch |
| else | catch | implements | private | final | class |
| extends | volatile | while | synchronized | instanceof | char |
| protected | import | transient | double |
Variable Declaration
- Variables are named memory locations that hold values that may change.
- Declaration informs the compiler of the type and allocates memory.
- Initialization is optional at declaration, but type is mandatory.
Constant Declaration
- Constants (final variables) are declared with the
finalkeyword. - They can be assigned only once throughout the program.
- By convention, constant names are written in uppercase.
Variable Scope
- Member variables: declared within the class body.
- Static variables: accessible across classes using
ClassName.staticVariable. - Instance variables: belong to an instance of the class.
- Static variables: accessible across classes using
- Local variables: declared within method bodies, valid only in the current block.
- Their lifetime depends on the method: memory is allocated when the method is invoked and released when the method ends.
- If a local variable has the same name as a member variable, the member variable is shadowed within that method.
public class VariableDemo {
// Constant member variable must be initialized at declaration
static final double PI = 3.14;
// Static variable (can be initialized later)
static int age = 18;
// Instance variable
int instanceVar = 45;
// Static variable
static int staticVar = 90;
static int shadowVar = 3;
public static void main(String[] args) {
final int number; // local constant
// number = 1235; // would be compilation error if uncommented: variable might already be assigned
age = 22; // modify static variable
number = 1236; // assign once
System.out.println("Constant PI: " + PI);
System.out.println("Number after assignment: " + number);
System.out.println("Age: " + age);
// Local variable shadows member variable
int shadowVar = 4;
System.out.println("Shadow variable (local is closer): " + shadowVar);
}
}