Note:
This was written for Day 1 in Java class. So the organization might be a little messy...
Packages
- Package: A collection of classes. It also creates a directory for organizing classes.
Output shortcuts (IntelliJ)
sout: System.out.println()
souf: System.out.printf()
- Documentation Comment:
/** … */
- Line Comment:
//
Main Method
- The
main method is the entry point for Java programs. The compiler looks for the main method to start execution.
Naming Conventions
- Class Names: Should start with capital letters (e.g.,
MyClass).
- Variable Names: Should start with a lowercase letter and use camelCase (e.g.,
myVariable).
Variable Exchange
Swapping values using a temporary variable:
int y = 5;
int x = 3;
int temp = y;
y = x;
x = temp;
This is similar to the swap() function in C++.
Variable Scope
int v1 = 15;
if (v1 > 10) {
int v2;
v2 = v1 + v2 + 5;
}
System.out.println(v2);
- Scope:
v2 is only declared within the if statement scope and is not accessible outside of it.
Data Types
Primitive Types
- byte: 1 byte, range: -128 to 127
- short: 2 bytes
- char: 2 bytes
- int: 4 bytes, range: -2.1 billion to 2.1 billion
- long: 8 bytes, range: -9.2 quintillion to 9.2 quintillion
Literals
- Binary:
0b1101 (e.g., 0b represents a binary number)
- Hexadecimal:
0xB3 (e.g., 0x represents a hexadecimal number)
Long Type
Floating-Point Types
- Double: Default for decimal numbers, more accurate than
float.
- Float: Use "f" to specify a
float literal:float myFloat = 1.23f;
Exponential Notation
- Use
e for exponential notation (e.g., 1.23e10).
Variables
- Definition: A name referencing a value in memory.
- Data Types: Variables can hold different data types (e.g.,
int, long, String, char, boolean).
- Value: The data stored in a variable. Values can change during execution.
- Scope: Determines where variables can be accessed (global, local, class).
Variable Scope
- Global Variables: Accessible anywhere in the code.
- Local Variables: Accessible only within the scope they are declared (e.g., within methods or control statements).
- Class Variables: Accessible within the class or through inheritance, depending on access modifiers (e.g.,
private, protected, public).
Lifecycle of Variables
- Const & Static Variables: Exist from the start to the end of the program execution.
- Local Variables: Created when the method is called and destroyed when the method exits.
- Instance Variables: Created when an object is instantiated and destroyed when the object is garbage collected.
Primitive vs. Reference Types
- Primitive Types: Can only be read (e.g.,
int, char).
- Reference Types: Can be read and written (e.g., objects of classes).