Java Fundamentals: Constants, Variables, Data Types, Operators and Methods
Java Overview
Java is a high-level programming language released by Sun Microsystems (Stanford University Network, United States) in 1995. Programming languages allow developers to issue instructions to computers to complete required tasks.
Key milestones in Java's development:
- 1995: Sun releases Java 1.0
- 1997: Java 1.1 launched
- 1998: Java 1.2 released
- 2000: Java 1.3 introduced
- 2002: Java 1.4 published
- 2004: Java 1.5 released
- 2006: Java 1.6 launched
- 2009: Oracle acquires Sun Microsystems, releases Java 1.7 in 2011
- 2014: Java 1.8 released
- 2017: Java 9.0 launched
Java is primarily used for internet application development, including e-commerce platforms, logistics systems, online banking systems, as well as back-end big data storage, query and data mining.
Basic Computer Concepts
Binary
Unlike the decimal system used in daily life, all data in computers is represented in binary. Binary only uses two digits 0 and 1, and follows the rule of carrying over when reaching 2 (e.g. 1 + 1 = 10 in binary). Each 0 or 1 is called 1 bit.
To convert decimal to binary, we use the repeated division by 2 method, collecting remainders after each division.
Byte
Byte is the most common smallest storage unit in computers. All data is stored in the form of bytes, and you can check the byte size of any file via its properties menu.
8 bits equal 1 byte, written as 1 byte or 1 B. Unit conversions:
8 bit = 1 B
1024 B = 1 KB
1024 KB = 1 MB
1024 MB = 1 GB
1024 GB = 1 TB
Common DOS Commands
Mastering basic DOS commands is helpful for Java beginners in early development work.
Java Development Environment Setup
JVM (Java Virtual Machine)
JVM is an abstract virtual computer that acts as the runtime environment for all Java programs. All Java code runs on the JVM, and cross-platform compatibility is Java's most famous feature.
Cross-platform: Java programs can run on any operating system, and this feature is implemented by the JVM. Java programs run on the JVM, and the JVM runs on the native operating system.
JRE vs JDK
- JRE (Java Runtime Environment): The runtime environment for Java programs, includes the JVM and core class libraries required at runtime. You only need to install JRE if you only want to run existing Java programs.
- JDK (Java Development Kit): The full development toolkit for Java, includes JRE plus development tools for programmers. You must install JDK to develop new Java programs.
Hierarchy relationship: JDK > JRE > JVM
First Java Program
Java program development follows three core steps: write source code → compile → run.
- Compilation: The
javaccompiler translates human-written Java source code into class files that the JVM can understand, and checks for code errors during this process. Compilation only succeeds if no errors are found. - Execution: The compiled class file is handed over to the JVM to run.
The main Method
The main method is the fixed entry point of any Java program. Its syntax cannot be modified, and the JVM always starts executing the program from the main method.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Comments
Comments are explanatory text for code, they do not affect compilation or execution. Java supports two comment types:
- Single-line comment: Starts with
//and ends at the line break. - Multi-line comment: Starts with
/*and ends with*/.
Keywords
Keywords are predefined words in Java that have special semantic meanings. All keywords are lowercase. Examples include public, class, static, void in the example above. You do not need to memorize all keywords at once, you can learn them gradually.
Identifiers
Identifiers are custom names for classes, methods, variables, etc. The class name HelloWorld in the example above is an identifier.
Hard Naming Requirements
- Identifiers can contain 26 English letters (case-sensitive), digits 0-9,
$(dollar sign) and_(underscore) - Identifiers cannot start with a digit
- Identifiers cannot be a Java keyword
Soft Naming Conventions
- Class names: Upper CamelCase (first letter uppercase, first letter of each subsequent word uppercase)
- Method names: Lower CamelCase (first letter lowercase, first letter of each subsequent word uppercase)
- Variable names: All lowercase
Constants
Constants are fixed values that do not change during the execution of a Java program.
Variables and Data Types
Variables are values that can change during program execution. Similar to how we use letters to represent numbers in math, Java uses variables to store dynamic data. A variable can only hold one value at a time, and must have an explicit data type declared.
Data Types
Java data types are divided into two categories:
- Primitive data types: Includes integer, floating-point, character, and boolean types
- Reference data types: Includes classes, arrays, interfaces
Java defines 4 categories and 8 total primitive data types. The default type for integers is int, and the default type for floating-point numbers is double.
Variable Declaration
Variable declaration requires three core components: data type, variable name, initial value:
dataType variableName = initialValue;
Conventions:
- Add
Lsuffix forlongtype values - Add
Fsuffix forfloattype values
Variable rules:
- Variable names must be unique within the same scope (same pair of curly braces)
- Variables must be initialized before they can be used
Data Type Conversion
Java requires consistent data types for calculations, so type conversion occurs when data types do not match.
Implicit (Automatic) Conversion
When a smaller range type operates with a larger range type, the smaller range type is automatically promoted to the larger range type.
Example:
public static void main(String[] args) {
int numA = 1;
byte numB = 2;
// Result of byte + int is int, cannot assign to byte
// byte result = numA + numB; // Compile error
int result = numA + numB;
System.out.println(result);
}
Explanation: byte occupies 1 byte, when operated with int (4 bytes), it is automatically promoted to int, so the result is an int. Similarly, when int operates with double, int is promoted to double:
public static void main(String[] args) {
int val = 1;
double decimalVal = 2.5;
double result = val + decimalVal;
System.out.println(result);
}
Conversion order (from smaller range to larger range):
byte, short, char → int → long → float → double
Note:
byte,short, andcharare all promoted directly tointwhen participating in operations.
Explicit (Forced) Conversion
When you need to convert a larger range type to a smaller range type, you need to manually perform forced conversion. Automatic conversion is done by Java, while forced conversion requires manual intervention.
Syntax:
targetType variableName = (targetType) valueToConvert;
Example: int i = 1.5; will fail to compile, because 1.5 is a double which has a larger range than int, so we need forced conversion:
// Forcing double to int directly removes the decimal part
int i = (int) 1.5;
Another example:
public static void main(String[] args) {
short s = 1;
// s + 1 results in int, cannot assign directly to short
// s = s + 1; // Compile error
s = (short) (s + 1); // Compiles successfully after forced conversion
}
Important Notes
- Converting floating-point numbers to integers truncates the decimal part directly, which may cause precision loss
- Forcing larger integer types to smaller types may truncate higher bits, leading to unexpected data loss
Example:
short maxShort = 32767; // Maximum value of short type
// Truncation leads to unexpected result after conversion
maxShort = (short) (maxShort + 10);
ASCII Encoding
All data stored in computers is binary, so encoding tables were created to map human-readable characters to numeric values. ASCII (American Standard Code for Information Interchange) is the first standardized encoding, which maps all English letters, digits and symbols to integers.
Example:
public static void main(String[] args) {
char c = 'a';
int offset = 1;
// char is promoted to int during calculation, using its ASCII value
System.out.println(c + offset); // Output: 98
}
Explanation: When char and int are calculated, the character is converted to its ASCII code (a = 97), then added to 1 to get 98.
Operators
Arithmetic Operators
All integer arithmetic operations in Java will never return a floating-point result.
Example:
public static void main(String[] args) {
int num = 1234;
System.out.println(num / 1000 * 1000); // Output: 1000
}
Increment and Decrement
++ increases the variable value by 1, -- decreases the variable value by 1, and they have the same usage rules.
- Independent use: Pre-increment
++iand post-incrementi++have the same effect - Mixed use: There is a clear difference:
Pre-increment: Variable increments first, the new value is used in the operation:
public static void main(String[] args) {
int a = 1;
int b = ++a;
System.out.println(a); // 2
System.out.println(b); // 2
}
Post-increment: The original value is used first, then the variable increments:
public static void main(String[] args) {
int a = 1;
int b = a++;
System.out.println(a); // 2
System.out.println(b); // 1
}
String Concatenation with +
When the + operator encounters a string, it acts as a concatenation operator:
public static void main(String[] args){
System.out.println("5+5=" + 5 + 5); // Output: 5+5=55
}
Assignment Operators
Assignment operators assign the value on the right side of the operator to the variable on the left side:
public static void main(String[] args){
int val = 5;
val += 5; // Equivalent to val = val + 5
System.out.println(val); // Output: 10
}
Comparison Operators
Comparison operators compare two values and return a boolean result (true or false):
public static void main(String[] args) {
System.out.println(1 == 1); // true
System.out.println(1 < 2); // true
System.out.println(3 > 4); // false
System.out.println(3 <= 4); // true
System.out.println(3 >= 4); // false
System.out.println(3 != 4); // true
}
Logical Operators
Logical operators connect multiple boolean expressions and return a boolean result:
public static void main(String[] args) {
System.out.println(true && true); // true
System.out.println(true && false); // false
System.out.println(false && true); // false (short-circuit, right side not evaluated)
System.out.println(false || false); // false
System.out.println(false || true); // true
System.out.println(true || false); // true (short-circuit, right side not evaluated)
System.out.println(!false); // true
}
Ternary Operator
Syntax:
resultType variable = booleanExpression ? valueIfTrue : valueIfFalse;
Execution logic: If the boolean expression is true, the first value is assigned to the variable, otherwise the second value is assigned:
public static void main(String[] args) {
int resA = (1 == 2 ? 100 : 200);
System.out.println(resA); // 200
int resB = (3 <= 4 ? 500 : 600);
System.out.println(resB); // 500
}
Introduction to Methods
Writing duplicate code for repeated functionality leads to code redundancy. Methods allow us to extract reusable functionality into an independent code block that can be called whenever needed, improving code reusability and reducing redundancy.
Method Definition
Syntax:
modifier returnType methodName(parameterList) {
// method code
return;
}
Explanation:
- Modifier: Use
public staticfor now - Return type: Use
voidfor methods that do not return a value. If return type isvoid,returncan be omitted - Method name: Follows identifier naming rules, used for invocation
- Parameter list: Leave empty for methods without parameters
Example:
public static void printMethod() {
System.out.println("This is a custom method");
}
When defining a method, you need to clarify two points:
- Return type: What type of result the method returns
- Parameter list: What parameters the method needs from the caller
Example: Defining a method to calculate the sum of two integers:
public static void main(String[] args) {
// Call method with actual arguments 5 and 6, receive the returned result
int total = calculateSum(5, 6);
System.out.println(total);
}
/*
* Calculate sum of two integers
* @param a first integer
* @param b second integer
* @return sum of a and b
*/
public static int calculateSum(int a, int b) {
return a + b;
}
Notes for definision:
- Methods must be defined inside a class, outside of any other method
- The return type must match the type of the value returned by the
returnstatement, otherwise compilation fails
Method Invocation
A method will not run until it is called. Common invocation methods:
- Direct invocation: Call the method directly by name, used for
voidmethods that do not return a value:
public static void main(String[] args) {
printGreeting();
}
public static void printGreeting() {
System.out.println("Custom method called from main");
}
- Assignment invocation: Define a variable to receive the return value of the method, used for methods with return values:
public static void main(String[] args) {
int sum = calculateSum(5, 6);
System.out.println(sum);
}
public static int calculateSum(int a, int b) {
return a + b;
}
- Print invocation: Call the method directly inside a print statement, used for methods with return values:
public static void main(String[] args) {
System.out.println(calculateSum(5, 6));
}
public static int calculateSum(int a, int b) {
return a + b;
}
Note: You cannot use print invocation for
voidmethods, because they do not return any value to print:// This code will fail to compile // public static void main(String[] args) { // System.out.println(printHello()); // Error // } // // public static void printHello() { // System.out.println("Hello"); // }
Correct vs Incorrect Method Definition
Correct example:
public class MethodDemo {
public static void main(String[] args){
}
// Correct: defined in class, outside other methods
public static void customMethod(){}
}
Incorrect example:
// This code is incorrect
// public class MethodDemo {
// public static void main(String[] args){
// // Error: cannot define a method inside another method
// public static void customMethod(){}
// }
// }