L3: Back to Basics
Whitespace in Java
- Whitespace: Includes spaces, tabs, and newline characters. It separates words and symbols to make the code readable.
- The compiler ignores extra whitespace, but using it improves code readability for developers.
Errors in Java
- Compiler Errors vs. Runtime Errors:
- Compiler Errors: Occur when the code violates Java’s syntax rules (e.g., missing a semicolon or misspelled keywords). These errors prevent the program from compiling and provide details like the error type and line number.
- Runtime Errors: Occur while the program is running (e.g., division by zero). These errors are not caught by the compiler.
- Logical Errors:
- The program compiles and runs, but produces incorrect results due to flawed logic (e.g., incorrect calculations or using the wrong condition in an
if
statement). - Testing and debugging are essential to identify and fix these errors.
- The program compiles and runs, but produces incorrect results due to flawed logic (e.g., incorrect calculations or using the wrong condition in an
- Syntax vs. Semantics:
- Syntax: Refers to the correct structure of code (e.g., correct use of keywords and punctuation).
- Semantics: Refers to the meaning and logic of the code. Syntactically correct code can still have semantic errors.
Variables and Constants
Variables: Store data in memory. Defined by a data type (e.g.,
int
,double
) and an identifier (name).- Scope: The section of the program where the variable can be accessed. Defined by the braces
{}
in which it is declared. A variable declared inside a method cannot be accessed outside that method.
- Scope: The section of the program where the variable can be accessed. Defined by the braces
Constants: Values that do not change after they are assigned. Declared using the
final
keyword.final double PI = 3.14159;
- Constants follow the same scope rules as variables.
Primitive Data Types
- Integer Types:
byte
,short
,int
,long
- Floating-Point Types:
float
,double
- Character Type:
char
- Boolean Type:
boolean
Sizes in Memory:
byte
: 8 bitsshort
: 16 bitsint
: 32 bitslong
: 64 bitsfloat
: 32 bitsdouble
: 64 bitschar
: 16 bitsboolean
: 1 bit (true or false)
Legal Assignment of Literals:
Integer literals default to
int
, floating-point literals todouble
.Suffixes can change default types:
long bigNumber = 123456789L; float fraction = 3.14F;
Type Conversion:
Widening: Safe conversion of a smaller type to a larger type (e.g.,
int
todouble
).Narrowing: Risky conversion from a larger type to a smaller type, which may cause data loss.
Casting: Explicitly converts one data type to another using
(target_type)
. Useful when narrowing:int num = (int) 3.14; // Results in 3
Purpose of Multiple Numerical Types:
- Different types allow optimization of memory usage and precision based on the requirements of the program.
Primitive Operations
Arithmetic Operators:
+
,,
,/
,%
- Integer Division: Dividing two integers truncates the decimal (e.g.,
9 / 2
results in4
).
Order of Operations: Follows standard algebraic precedence (e.g., multiplication and division before addition and subtraction). Parentheses can be used to alter the order.
Incrementing and Decrementing:
++
(increment) and--
(decrement) operators to increase or decrease a variable’s value by 1.In the prefix form, the operator is placed before the operand. The value of the operand is incremented or decremented first, and then the result is used in the expression. The syntax for prefix increment and decrement operators is as follows:
++variable; --variable;
In the postfix form, the operator is placed after the operand. The value of the operand is used in the expression first, and then it is incremented or decremented. The syntax for postfix increment and decrement operators is as follows:
variable++; variable--;
Assignment Operators:
⚠️If you declare an variable inside a method (including the
main
method) without initializing it, it won’t have a default value. You must explicitly assign a value to it before using it, otherwise, you’ll get a compilation error.If you declare an variable as a member of a class (outside any method), it will automatically be initialized to the appropriate default value.
=
for assignment.Compound operators (e.g.,
+=
,=
,=
,/=
) combine an operation with assignment:int x = 5; x += 3; // Equivalent to x = x + 3;
Strings in Java
String Creation: Defined using double quotes (
"
):String greeting = "Hello, World!";
String Methods: Common methods include:
length()
: Returns the length of the string.charAt(int index)
: Returns the character at the specified index.substring(int start, int end)
: Returns a substring from the start to the end index.toUpperCase()
,toLowerCase()
: Converts the string to uppercase or lowercase.
String “Arithmetic” (Concatenation):
The
+
operator concatenates strings:String fullName = "John" + " " + "Doe"; // "John Doe"
String Immutability: Strings are immutable, meaning once created, they cannot be changed. Any modification results in a new string.
String Constant Pool: Strings with identical content are stored in a common pool to optimize memory usage.
Predefined Classes: Java’s standard library includes classes like
String
, which provide methods for handling text efficiently.
Reference Variables
Instantiation Using
new
:Creates a new object of a class:
String message = new String("Hello");
Aliases: When two reference variables point to the same object, changes through one reference affect the other.
Garbage Collection: Automatically frees memory by removing objects that no longer have any references.
Invoking Methods: Methods are called using dot notation:
int length = message.length();