Java Programming Fundamentals
Java Programming Fundamentals
1. Java and the Tools Needed to Build Programs
Java is a programming language used to build many kinds of applications. A Java program consists of source code that is compiled and then run by a Java runtime.
The Java Development Kit
The Java Development Kit (JDK) is the software development environment used to build Java applications. It includes:
A compiler, which translates Java source code into Java bytecode.
Libraries containing reusable code.
Runtime components needed to run Java programs.
Other development tools.
A project needs a JDK installed so that its source code can be compiled and executed.
Code editors and IDEs
Java code can be written in many editors and integrated development environments (IDEs). Common choices include:
IntelliJ IDEA
Eclipse
NetBeans
An IDE provides tools for editing code, organizing project files, compiling programs, and running them. IntelliJ IDEA’s Community Edition is a free option suitable for basic Java development.
A command-line application is a useful starting point because it can be run in a terminal without the added complexity of building a graphical user interface.
2. The Structure of a Java Program
A Java program is organized using classes and methods.
Functions and methods
A function is a block of code that performs a task. Examples include code that sends an email, converts a measurement, or validates user input.
In Java, a function that belongs to a class is called a method. Methods generally have:
A return type, which specifies the kind of value returned. A method that returns nothing uses
void.A name describing its purpose.
Parentheses that can contain parameters, which allow values to be passed into the method.
A body enclosed in curly braces, containing the instructions to execute.
A method that returns a value must return a value compatible with its declared return type. A void method does not return a value.
Classes
A class is a container for related methods and other members. Classes help organize code into meaningful groups. For example, a class might hold methods related to customers, payments, or email.
A Java program must define its classes. A typical beginner program has a class containing the program’s entry point.
The main method
The main method is the entry point of a Java application: execution begins there. A common declaration is:
public static void main(String[] args) {
// Program instructions
}publicmakes the method accessible from outside its class.staticallows the runtime to call the method without first creating an object of the class.voidindicates that the method returns no value.String[] argsallows command-line arguments to be supplied to the program.
Access modifiers
An access modifier controls which other parts of a program can access a class, method, or other member. Common modifiers include public and private.
Java syntax and naming conventions
Java statements are generally terminated with semicolons. Curly braces mark the beginning and end of classes and code blocks. Java convention places the opening brace on the same line as a class or method declaration.
Common naming conventions include:
PascalCase for class names: each word begins with a capital letter, as in
MainProgram.camelCase for method and variable names: the first word begins with a lowercase letter, and later words begin with capitals, as in
sendEmailormonthlyPayment.
3. Creating a Project and Printing a Message
A Java project contains source files and supporting project structure. Java source files use the .java extension. A file may contain a package declaration indicating which package its class belongs to.
Packages
A package groups related classes and provides a namespace for them. Packages help organize large programs and prevent classes with the same name from conflicting.
A common convention is to base a project’s package name on a company’s domain name written in reverse order. For example, a domain such as example.com might correspond to a package beginning with com.example. This does not require the developer to own or register that domain; it is a naming convention.
A package declaration appears near the top of a source file and ends with a semicolon. Classes from other packages can be made available with import statements. Some classes in java.lang are available automatically.
Printing output
A common way to print a line of text to the terminal is:
System.out.println("Hello, world!");Here:
Systemis a class.outis a field representing standard output.printlnis a method that prints a value and then moves to a new line.Text enclosed in double quotes is a string literal.
The dot operator accesses members of a class or object. The print method is similar to println, but it does not automatically add a new line.
4. How Java Code Is Compiled and Executed
Java program execution involves compilation followed by execution.
Compilation to bytecode
The Java compiler, included in the JDK, translates Java source files into Java bytecode. A compiled class is commonly stored in a .class file.
The compiler can be invoked from a terminal using javac and a source filename, for example:
javac Main.javaThe filename’s capitalization must match on case-sensitive operating systems.
Running bytecode with the JVM
The Java Virtual Machine (JVM) executes Java bytecode. It translates bytecode into instructions the underlying operating system and processor can run.
This arrangement makes Java programs portable:
A developer compiles Java source code into bytecode.
The bytecode can be used on different operating systems.
Each system needs a compatible Java runtime containing a JVM.
The program’s package structure matters when running a class directly: the JVM needs the class’s fully qualified name, including its package.
Key idea: Java source code is compiled to platform-independent bytecode, which a platform-specific JVM executes.
An IDE typically handles compilation and execution behind the scenes. When a program is run from an IDE, the editor may compile the source into class files and then use the JVM to execute them.
5. Java’s Origins and Editions
Java was developed by James Gosling at Sun Microsystems and released in 1995. It was initially called Oak, then Green, before being renamed Java. Sun Microsystems was later acquired by Oracle.
Traditional Java editions have served different purposes:
Java Standard Edition (Java SE): The core Java platform and standard libraries used for general-purpose Java development.
Java Enterprise Edition (Java EE): Additional technologies historically used to build large-scale, distributed, and multi-tier applications on top of Java SE.
Java Micro Edition (Java ME): A smaller Java platform designed for resource-constrained and mobile devices.
Java Card: Technologies for running Java-based applications on smart cards.
Java versions change over time, so a version described as current in older material should not be assumed to be current today.
6. Variables, Constants, and Data Types
Variables and assignment
A variable is a named location used to store data while a program runs. Declaring a variable specifies its type and name. Assigning a value stores a value in it.
int age = 30;intis the variable’s type.ageis its identifier.=is the assignment operator.30is the initial value.
Giving a variable its first value is called initialization. A variable must be initialized before its value can be read. Its value can be changed later unless it is declared as a constant.
Variables should have meaningful, descriptive names. Names such as viewsCount reveal more than names such as v or n.
It is possible to declare multiple variables on one line, but one declaration per line is generally easier to read.
Constants
A constant is a variable whose value cannot be reassigned after initialization. In Java, the final keyword marks a variable as non-reassignable.
By convention, constant names use uppercase letters with underscores between words, such as MONTHS_IN_YEAR. Named constants also make code easier to understand than unexplained numeric values, sometimes called magic numbers.
Primitive and reference types
Java types fall into two broad categories:
Primitive types store simple values directly, such as numbers, Boolean values, and individual characters.
Reference types store references to objects, which can represent more complex data.
Java has eight primitive types:
byte,short,int, andlongrepresent whole numbers.floatanddoublerepresent numbers with fractional parts.charrepresents a single character.booleanrepresentstrueorfalse.
The approximate storage sizes and ranges described in the material are:
byte: 1 byte; values from −128 through 127.short: 2 bytes; a larger whole-number range thanbyte.int: 4 bytes; commonly used for whole numbers and capable of representing values into the billions.long: 8 bytes; used for larger whole numbers.float: 4 bytes; a floating-point type.double: 8 bytes; a floating-point type with more precision thanfloat.char: 2 bytes; represents a single character.boolean: representstrueorfalse.
A type should be chosen to suit the value and range the program needs. For example, a small whole-number quantity may fit in a byte, while a large count may require a long.
Numeric literals and suffixes
Java treats whole-number literals as int by default. A whole-number literal too large for an int can be marked as a long by adding L:
long viewsCount = 3_000_000_000L;Java treats decimal literals as double by default. An F suffix marks one as a float:
float price = 10.99F;Underscores can improve the readability of numeric literals by separating groups of digits, as in 3_000_000.
A char literal is written in single quotes, such as 'A'. A string is written in double quotes, such as "Hello".
Words such as class, public, static, and void are reserved keywords. They have defined meanings in Java and cannot be used as ordinary class, method, or variable names.
7. Objects, References, and Memory Behavior
A class defines a type and acts as a blueprint for objects. An object is an instance of a class. For example, a Date class can be used to create a particular date object.
Reference-type objects have members, such as fields and methods, which can be accessed with the dot operator. Primitive values do not have object members in the same way.
Creating objects
A common way to create an object is to use the new operator:
Date now = new Date();Classes from packages other than the current package or automatically available packages may need to be imported. For example, Date is available in java.util.
Copying primitive values
When a primitive variable is assigned to another primitive variable, its value is copied. The variables then hold independent values. Changing one does not change the other.
Copying references
A reference variable holds a reference to an object, not the object’s contents directly. When one reference variable is assigned to another, the reference is copied. Both variables can then refer to the same object.
If that shared object is changed through one reference, the change is visible through the other reference. This is why reference variables should not be mistaken for independent copies of their objects.
Key distinction: Primitive assignment copies a value; reference assignment copies a reference to an object.
8. Strings and Text
A string is a sequence of characters. Java’s String type is a reference type, even though string literals allow strings to be created without explicitly writing new.
String message = "Hello, world!";The String class is in java.lang, which is available without an explicit import.
Combining and examining strings
Strings support useful operations, including:
Concatenation: The
+operator joins strings with other strings or values.startsWithandendsWith: Check whether a string begins or ends with a specified sequence.length: Returns the number of characters.indexOf: Returns the index of the first occurrence of a character or sequence. If it is not found, the result is −1.replace: Produces a string in which a target sequence is replaced with another sequence.toLowerCaseandtoUpperCase: Produce versions with letters converted to lowercase or uppercase.trim: Produces a version with leading and trailing whitespace removed.
String indexes begin at 0. Therefore, the first character has index 0.
Immutability
Strings are immutable: a string’s contents do not change after the object is created. A method such as replace, trim, or toLowerCase returns a new string instead of modifying the original. To keep the modified result, the program must use the returned string.
Parameters and arguments
A method declaration can define parameters, which are named placeholders for values. When a method is called, the actual values supplied are arguments.
For example, in a string replacement operation, the target and replacement are parameters in the method definition; the particular text values supplied during a call are arguments.
Escape sequences
Some characters need special notation inside strings. An escape sequence begins with a backslash:
\"includes a double quote in a string.\\includes a backslash.\ninserts a new line.\tinserts a tab.
For example, a Windows-style path must escape each backslash in Java source code, even though the program displays each intended backslash as one character.
9. Arrays
An array stores a fixed-length sequence of values of the same type. Arrays are reference types, so creating an array allocates an array object.
Creating and accessing an array
An array can be created with a specified length:
int[] numbers = new int[5];Individual items are accessed by index. Indexing starts at 0, so an array of length 5 has valid indexes from 0 through 4.
Using an index outside the array’s bounds causes an error at runtime, reported as an exception.
An array’s length field gives the number of items it can hold. Array length cannot be increased or decreased after creation. A collection type is needed when a resizable sequence is required.
Initial values
When an array is created with a specified length, its elements receive default values. For example:
Numeric primitive elements default to zero.
Boolean elements default to
false.Reference elements default to
null.
An array can also be initialized with its contents when those contents are known:
int[] numbers = {2, 3, 5, 1, 4};Printing and utility methods
Printing an array directly does not usually display its elements in a readable list. The Arrays utility class provides methods such as:
Arrays.toString(array)for a one-dimensional array.Arrays.deepToString(array)for nested or multidimensional arrays.Arrays.sort(array)to sort an array.
The Arrays class provides overloaded methods: methods with the same name but different parameter types. This allows corresponding operations to be available for different kinds of arrays.
Multidimensional arrays
A multidimensional array is an array whose elements are themselves arrays. A two-dimensional array can represent a grid or matrix, while a three-dimensional array can represent data arranged in three dimensions.
For example, a 2×3 matrix has two rows and three columns. Its elements are accessed with a row index and a column index. Nested brace initializers can make such structures easier to read.
10. Arithmetic, Casting, and Number Formatting
Arithmetic operators
Java provides familiar arithmetic operators:
+for addition-for subtraction*for multiplication/for division%for the remainder, or modulus
If both operands in a division are whole-number types, the result is also a whole-number result; any fractional part is discarded. To retain a fractional result, at least one operand must be a floating-point value.
Operator precedence
Multiplication and division are evaluated before addition and subtraction. Parentheses can change the order of evaluation.
For example, the expression 10+3×2 evaluates to 16, because multiplication happens first. In the expression (10+3)×2, the parentheses make addition happen first, producing 26.
Increment, decrement, and compound assignment
The increment operator increases a variable by one; the decrement operator decreases it by one. They can appear before or after a variable.
With postfix use, such as
x++, the current value is used before the increment takes effect.With prefix use, such as
++x, the increment occurs before the value is used.
This distinction matters inside a larger expression or assignment.
Compound assignment operators provide shorter forms for updates:
x += 2is equivalent tox = x + 2.The same pattern applies to subtraction, multiplication, and division.
Implicit and explicit casting
Casting converts a value from one type to another.
Implicit casting happens automatically when the conversion is safe and does not risk losing information. For example, a smaller whole-number type can be widened to a larger one.
Explicit casting is written by the programmer and is needed when information may be lost. Converting a
doubleto anint, for example, removes the fractional part.
Floating-point types can hold fractional values, so converting a whole number to a floating-point type is generally safe. Converting in the opposite direction may lose precision.
Converting strings to numbers
A string cannot be converted to a number with a primitive cast. Wrapper classes provide parsing methods for converting text that represents numbers:
Integer.parseInt(...)Short.parseShort(...)Float.parseFloat(...)Double.parseDouble(...)
The text must be in a valid format for the selected method. For example, parsing "1.1" as an integer causes an exception. User-interface input commonly arrives as text, so numeric input often needs to be parsed before calculations can use it.
The Math class
The Math class provides common mathematical operations, including:
Math.round(...)to round a floating-point value.Math.ceil(...)to return the smallest integer-valued result greater than or equal to the input.Math.floor(...)to return the greatest integer-valued result less than or equal to the input.Math.max(a, b)andMath.min(a, b)to select the greater or smaller value.Math.random()to generate a randomdoublein the range from 0 inclusive to 1 exclusive.Math.pow(a, b)to raise one value to the power of another.
A random value in a larger range can be produced by scaling the result of Math.random(). Parentheses are important when combining scaling, rounding, and casting: a cast applies only to the expression it directly encloses.
Formatting numbers
The NumberFormat class can format numbers as currencies or percentages. It is an abstract class, so it is not constructed directly with new. Instead, factory methods such as getCurrencyInstance() and getPercentInstance() return suitable formatter objects.
Formatting produces a string for display. Depending on the formatting style and locale, currency formatting can add a currency symbol, group digits with separators, and limit the number of displayed decimal places. Percentage formatting converts a fractional value such as 0.1 into a percentage such as 10%.
Method chaining means calling another method on the object returned by a previous method. This can avoid temporary variables when the intermediate result is used only once.
11. Reading Input from the Terminal
The Scanner class can read input from several sources, including the terminal and files. To read from standard input, a scanner can be constructed with System.in.
Common scanner methods include:
nextByte()for a byte.nextInt()for an integer.nextFloat()andnextDouble()for decimal numbers.nextBoolean()for a Boolean value.next()for the next token.nextLine()for the remainder of a line.
The scanner method should match the kind of input the program expects. If the user provides text that cannot be parsed as the expected type, the program can encounter an exception.
Tokens and lines
A token is a unit of input separated by whitespace. next() reads one token, so it stops at a space. To read a full line containing spaces, nextLine() is generally more appropriate.
nextLine() also preserves spaces in the returned text. Calling trim() on the result can remove leading and trailing whitespace if that is desirable.
Printing prompts and reusable scanners
print is useful for prompts that should remain on the same line as the user’s response. println adds a line break after the prompt.
A scanner should usually be created once and reused rather than repeatedly constructed inside a loop. This avoids unnecessary object creation.
12. Building a Mortgage Calculator
A mortgage calculator combines input, numeric types, constants, arithmetic, validation, and formatting.
Mortgage payment formula
Let:
P be the principal, or amount borrowed.
r be the monthly interest rate expressed as a decimal.
n be the total number of monthly payments.
M be the monthly payment.
The monthly payment is:
If the annual interest rate is entered as a percentage and the loan term is in years, the values used by the formula are:
The calculation can use the Math.pow method to raise 1+r to the power of n. The result can then be formatted as a currency value for display.
Choosing types and constants
A principal amount needs a numeric type large enough for the expected loan range. The annual interest rate needs a floating-point type. A whole-number loan term can use an integer type suited to the supported range.
Named constants, such as the number of months in a year and the percentage conversion factor, make the calculation easier to understand and help avoid magic numbers.
Validating user input
Input validation checks that values meet the program’s requirements before the calculation proceeds. A calculator might require:
The principal to fall within a supported minimum and maximum.
The annual interest rate to be greater than zero and no higher than a supported maximum.
The loan term to fall within a supported range of years.
A loop can repeatedly prompt the user until a valid value is entered. An infinite loop with a break statement is one possible structure:
Ask the question.
Read the value.
Check whether it is valid.
If it is valid, leave the loop.
Otherwise, display an error message and ask again.
Variables needed after the loop should be declared outside the loop’s local code block. Otherwise, they may be out of scope where the final calculation needs them.
13. Comparison and Logical Operators
Comparison operators
Comparison operators compare values and produce a Boolean result: true or false. They include:
Equality:
==Inequality:
!=Greater than:
>Greater than or equal to:
>=Less than:
<Less than or equal to:
<=
The equality operator == is different from the single assignment operator =. A Boolean expression is an expression whose result is either true or false.
Logical operators
Logical operators combine or reverse Boolean conditions:
AND (
&&): True only when both conditions are true.OR (
||): True when at least one condition is true.NOT (
!): Reverses a Boolean result.
Java’s logical AND and OR operators use short-circuit evaluation. With &&, if the first condition is false, the second condition does not need to be evaluated. With ||, if the first condition is true, the second condition does not need to be evaluated.
These operators allow programs to express rules involving multiple requirements. For example, a loan applicant might qualify by having high income or good credit, while also having no disqualifying criminal record.
14. Conditional Statements
Conditional statements choose which code to execute based on a condition.
if, else if, and else
An if statement executes its body when its condition is true. An else if clause checks another condition if earlier conditions were false. An else clause handles the remaining case.
Curly braces define a code block. They are necessary when a clause contains multiple statements. Even where braces are optional for a single statement, consistent use can make code easier to maintain and less prone to errors.
Conditions should be arranged so that each branch is meaningful. If an earlier branch has already ruled out a possibility, repeating that condition in a later branch may be unnecessary.
Boolean values from comparisons
When a Boolean variable is determined directly by a comparison, the comparison can be assigned to the variable:
boolean hasHighIncome = income > 100_000;This avoids a longer if/else sequence that separately assigns true or false.
The ternary operator
The ternary operator selects one of two values based on a condition. It has three parts:
condition ? valueIfTrue : valueIfFalseIt can be useful when a variable should receive one of two simple values. For example, a class name might be selected based on whether income exceeds a threshold. More complicated logic is often clearer as a regular conditional statement.
Switch statements
A switch statement selects a branch based on the value of an expression. It is useful when several cases correspond to different possible values, such as a user role.
A switch commonly contains:
caseclauses for specific values.A
defaultclause for unmatched values.breakstatements to leave the switch after handling a case.
Without a break, execution can continue into later cases. Switch statements can be an alternative to a chain of if and else if statements, especially when comparing one expression against several discrete values.
15. Loops and Repetition
Loops repeat instructions. Java provides several loop forms suited to different situations.
for loops
A for loop is useful when the number of repetitions is known or controlled by a counter. It includes:
Initialization of a loop variable.
A condition checked before each iteration.
An update, often an increment or decrement.
For example, a counter beginning at 0 and continuing while it is less than 5 executes five times. At the end of each iteration, the counter is updated. Once the condition becomes false, execution continues after the loop.
while loops
A while loop repeats as long as its condition is true. It checks the condition before each iteration, so it may execute zero times.
It is useful when the number of repetitions is not known in advance, such as repeatedly asking for input until the user enters a particular word.
When comparing strings by their contents, use a method such as equals. Using == on reference variables compares references rather than reliably checking whether their text is the same.
do-while loops
A do-while loop checks its condition after the body runs. It therefore executes at least once, even if the condition is false at the beginning.
This is useful when the program must perform an action before it can decide whether another iteration is needed. In many other situations, a while loop is more common.
break and continue
breakimmediately exits the loop.continueskips the remaining statements in the current iteration and moves to the next iteration.
An intentional infinite loop can use a condition that is always true, but it must have a valid exit path, such as a break triggered by user input. Without an exit path, the loop never terminates.
For-each loops
A for-each loop iterates through the elements of an array or collection without requiring an explicit numeric index.
It is convenient when the program needs to process each item and does not need its index. Its limitations include:
It naturally iterates forward rather than providing direct reverse iteration.
It does not directly provide the current index.
A standard for loop is preferable when the index is needed, the iteration must proceed in reverse, or the code needs precise control over the iteration.
16. Problem Solving with Conditions and Loops
Checking divisibility
The modulus operator % returns the remainder after division. A whole number is divisible by another number when the remainder is zero.
This provides a simple way to build rules such as printing one word when a number is divisible by one value, another word when it is divisible by another, and a combined word when both conditions are true.
The most specific condition should be checked first. If a number divisible by both values is checked first only against one individual value, that earlier branch may run and prevent the combined case from being reached.
Avoiding repetition and nesting
The DRY principle—“don’t repeat yourself”—encourages avoiding duplicated logic. However, removing every repeated expression is not always the best choice. One approach may reduce repetition but create deeply nested conditionals; another may repeat a small condition but remain flatter and easier to read.
Programming involves trade-offs. The best solution is not simply the one with the fewest repeated characters; it should also be understandable and maintainable.
17. Clean Code, Scope, and Maintainability
Clean code is code that other people can understand and maintain. Good programming is not only about producing instructions a computer can execute; it is also about communicating intent clearly to human readers.
Meaningful names and constants
Use descriptive names for variables, methods, and classes.
Use constants to explain values that would otherwise be magic numbers.
Prefer names that reveal the role of a value, such as
monthlyInterest, rather than unexplained abbreviations.
Scope and code blocks
A variable’s scope is the region of code where it can be accessed. A variable declared inside a code block is generally available only within that block. This matters when using loops and conditionals: a result needed after the block may need to be declared before entering it.
Breaking large methods into smaller parts
When a method becomes long and handles many tasks, it becomes harder to understand and maintain. A useful improvement is to separate the program into smaller methods, each with a clear responsibility. This makes it easier to locate behavior, test pieces of logic, and change the program safely.
Exceptions and error handling
An exception is Java’s way of reporting an error during program execution. Examples include entering input in an unexpected format or accessing an array index that does not exist.
A program should handle foreseeable problems appropriately. Input validation can prevent many errors by checking values before using them, while exception handling provides a way to respond when an operation still fails.
18. Core Takeaways
Java programs are built from classes and methods, and execution begins in the
mainmethod.The JDK provides tools to compile and build Java applications; the JVM executes compiled bytecode.
Primitive variables store simple values, while reference variables refer to objects.
Variables should be initialized before use, and constants help prevent unintended changes.
Strings are immutable, arrays have fixed length, and object references can point to shared objects.
Casting, parsing, and formatting are distinct operations: casting converts compatible types, parsing converts text into values, and formatting prepares values for display.
Conditional statements make decisions; loops repeat work;
breakandcontinuealter loop execution.Clear naming, sensible scope, validation, and well-structured code make programs easier to maintain.

Ask anything
We've read this whole study set, so questions about it get the best answers.