First Java Programs

Write your first complete Java programs: build a class with a main method, compile and run it, and fix the errors the compiler and the running program report. Store values in variables of the primitive types and in Strings, calculate with arithmetic expressions including integer division and the remainder, and convert between types with casts and parsing. Read text and numbers from the keyboard with Scanner, format results with printf, and combine everything into small programs that you test against results worked out by hand.

BeginnerLesson 1 of 11 in Object-Oriented Programming with Java Course

What you will learn

  1. Build a complete Java program around a main method, turn it into a running program with the compiler and the Java launcher, fix the errors that stop it, and print text exactly as intended.
    • Build a program around the main method
      Recognize the parts of a minimal Java program, place statements correctly inside the main method, and follow the rules for names, braces, semicolons and comments.
    • Compile, run and fix errors
      Turn source code into a running program with the JDK, and tell compile-time, runtime and logic errors apart so each can be found and fixed.
    • Print text with print and println
      Print text and values on the screen line by line, control where new lines begin, and use escape sequences for quotation marks, tabs and backslashes.
  2. Declare and update variables, choose a suitable primitive type for each value, and store and combine text in String values.
    • Declare, assign and update variables
      Create variables with a type and a name, give them values, follow the naming rules, and predict the value of every variable as a program runs.
    • Choose a primitive type and write literals
      Pick the right primitive type for whole numbers, decimal numbers, characters and truth values, write literals of each type, and recognize when a value does not fit its type.
    • Store text and join it with concatenation
      Hold text in String variables and build output by joining strings, numbers and variables with the + operator, predicting exactly what will be printed.
  3. Write arithmetic expressions that Java evaluates in the intended order, use integer division and the remainder correctly, and calculate with decimal numbers and the Math class.
    • Write expressions with operators and precedence
      Combine values with the arithmetic operators, predict the order in which Java evaluates them, and update variables with compound assignment and increment.
    • Use integer division and the remainder
      Predict the results of / and % on whole numbers, use them to split quantities into units, and recognize division by zero.
    • Calculate with decimals and the Math class
      Calculate with double values, use the ready-made methods of the Math class for roots, powers and rounding, and present results with a sensible number of decimal places.
  4. Predict which conversions Java makes automatically, write casts where a conversion can lose information, and turn text into numbers and numbers into text.
    • Widen values and cast them explicitly
      Tell automatic widening conversions apart from narrowing ones that need a cast, place casts so calculations give the intended result, and predict what a cast does to a value.
    • Convert between text and numbers
      Turn strings that contain numbers into int and double values, turn numbers into strings, and recognize the error Java gives for text that is not a valid number.
  5. Read text and numbers typed by the user, present results in a clear format, and combine input, calculation and output into small, tested programs.
    • Read input with Scanner
      Create a Scanner for keyboard input, read lines, words and numbers with the right method, and avoid the common traps with line endings, wrong input and decimal separators.
    • Format output with printf
      Print numbers with a fixed number of decimal places and line up output in columns with printf and String.format, and know how the computer's settings change the decimal separator.
    • Combine input, calculation and output
      Plan, write and test complete programs that read values, calculate with them using the right types, and print clear results.

First Java Programs study guide

5 chapters

1

Write, compile and run a Java program

A Java program starts as text, but the computer needs a precise structure before it can run that text as instructions. Build a small class around a main method, then follow the source through compilation and execution. Printed messages make each step visible. When something fails, the stage at which it fails tells you whether to inspect the source, read a runtime exception, or compare the result with what you expected.

1.1 Build a program around the main method

A first Java program gives the computer a short list of instructions. The surrounding class and main method tell Java where those instructions belong and where execution begins.

Put instructions inside main
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

The outer braces enclose the class body. The inner braces enclose the method body. When this program starts, Java runs the first statement inside main. More statements placed underneath run from top to bottom. When main finishes, this small program ends.

Copy public static void main(String[] args) carefully. Here, public lets the launcher call the method, static allows it to run without first creating an object, and void says that the method returns no result. String[] args receives command-line words typed after the program name. You can print a message without using those words.

Match punctuation and names

A statement such as System.out.println("Hi"); ends with a semicolon. An opening brace { needs a closing brace }. The class and method headers shown above open blocks; do not replace those opening braces with semicolons. Indenting the statement four spaces farther than its method header makes the nesting visible.

Save public class Hello in Hello.java. The public class name and the part before .java must match exactly, including capitals. If the declaration says public class Other, the file must be Other.java. A compiler message saying that the class should be declared in another file points to this mismatch.

Java is case-sensitive. The name System must start with a capital S; system.out.println("Hi"); fails to compile. A method called Main is a different method from main. A class containing only Main can compile, yet the launcher cannot find the intended entry method when you run it.

Make the code readable

Use one statement per line and four spaces of indentation for each level of braces. Most spaces and line breaks between code elements do not affect compilation. Spaces inside quoted text do affect the output. Class names conventionally use PascalCase, as in TravelTime.

A comment explains code to people. Java ignores everything after // on that line. A block comment starts with /* and ends with */, and can span several lines. A useful comment explains a reason, such as // Convert hours to seconds, beside a conversion whose purpose might be unclear.

Recognize the shorter form

Java 25 and later also support a compact source file:

void main() {
    IO.println("Hello, world!");
}

This form omits the explicit class declaration. IO.println prints a line, and IO.readln("Your name: ") displays a prompt and returns the typed line. The classic class form works with older Java versions too; both forms provide a main method where execution starts.

Key Takeaways

  • Put executable statements inside the main method and match each opening brace with a closing brace.
  • End a statement such as a printing call with a semicolon.
  • The public class Hello belongs in Hello.java; capitalization matters.
  • Comments explain code to readers and are ignored during compilation.
  • Java 25 adds a compact source form; the classic class form also works on older releases.

1.2 Compile, run and fix errors

Writing source code and running a program are separate steps. Java first checks and translates your code, then executes it. Knowing which step failed helps you decide where to look.

Compile the source, then launch the class

Source code is the text in a .java file. The compiler, javac, translates valid source into bytecode in a .class file. The Java Virtual Machine (JVM) executes that bytecode. A suitable JVM lets the same bytecode run on different operating systems.

Open a terminal in the folder containing Hello.java and enter:

javac Hello.java
java Hello

The first command creates Hello.class when compilation succeeds. The second starts the program. Its argument is the class name, without .class: java Hello.class asks the launcher to find the wrong class name and fails.

The JDK, or Java Development Kit, provides both commands. An IDE, such as IntelliJ IDEA, Eclipse, NetBeans, or Visual Studio Code with Java support, performs compilation and launching when you press Run. It can mark errors while you type, but those are still errors in the same Java language.

Since Java 11, source-file mode offers a shortcut for a single small program:

java Hello.java

This compiles in memory and runs the source without leaving a .class file. Keep the two forms distinct: java Hello launches a compiled class, while java Hello.java launches source.

Read compile-time errors

A compile-time error prevents successful compilation. For example, a missing semicolon can produce:

Hello.java:3: error: ';' expected
        System.out.println("Hello")
                                   ^

The message identifies the file, line, and place where the compiler noticed the problem. The real mistake may be earlier: an unclosed quote on one line can confuse later lines. Read the marked line and the one before it. Fix the first reported error and compile again before changing several other lines. One repair can remove many later messages.

Separate runtime errors from wrong answers
Kind of problemWhat happensHow to investigate
Compile-time errorThe source cannot be successfully compiled.Read the first compiler message and inspect the nearby code.
Runtime errorExecution stops with an exception.Read the exception and locate the reported line.
Logic errorExecution finishes but the result is wrong.Compare output with a result calculated by hand.

If an integer variable divisor contains zero, 5 / divisor fails during execution with ArithmeticException: / by zero. The arithmetic statement can be valid source even though its runtime values make it fail.

A program that prints an average of 8 when the correct value is about 8.33 has a logic error. No compiler message can tell you that this is the wrong result for your task. Test with known inputs, inspect intermediate values, and find the first incorrect calculation.

Work in a short cycle: edit, save, compile, run, test. Saving matters: compilation reads the saved file, so unsaved edits cannot change the compiled program.

Key Takeaways

  • javac Hello.java compiles source; java Hello runs the resulting class.
  • The JDK supplies development commands; the JVM executes bytecode.
  • Fix the first compiler error and compile again before chasing later messages.
  • A runtime exception stops execution; a logic error needs an expected-result check.

1.3 Print text with print and println

Printed output is the first way to see what a program does. Java gives you control over the characters it prints and the point where the next line begins.

Follow the output position

System.out.print(...) writes its value and leaves the output position on the same line. System.out.println(...) writes its value and then starts a new line. Calling System.out.println() with empty parentheses adds just a line break.

System.out.print("Hello");
System.out.print(", ");
System.out.println("world");
System.out.println("Bye");

The first two calls leave the position after the space following the comma. The third adds world at that position, then moves to a new line. The exact output is:

Hello, world
Bye

Java inserts no spaces between calls. If you remove the space in ", ", the first line becomes "Hello,world". An empty println() between the final two statements would create a blank line between the messages.

Decide whether you want text or a value

A string literal is text enclosed in double quotation marks. Printing "7 * 6" displays the text "7 * 6". Printing 7 * 6 evaluates the multiplication and displays "42". The quotation marks are code punctuation; they are not printed as part of the literal.

Likewise, if name stores "Ada", System.out.println(name); displays "Ada", while System.out.println("name"); displays "name". Use the variable without quotes when you want its stored value.

Single quotes have a different role. 'A' is one char value. 'Hello' cannot hold a multi-character message and causes a compile-time error. Use "Hello" for that text.

Put special characters in a string

An escape sequence begins with a backslash and represents a character inside the literal.

Code inside a literalPrinted character
\nNew line
\tTab
\"Double quotation mark
\\One backslash

For example:

System.out.println("She said \"hi\"");
System.out.println("C:\\Users");

These statements display She said "hi" and C:\Users, on separate lines. The extra backslashes tell Java how to interpret the following character; they are not all copied to the output.

A single call can also print several lines:

System.out.println("Name:\tAda\nAge:\t36");

The tab separates the label from the value, and \n puts the age on the next line. The println call adds its own final line break too. A tab moves to a tab stop, so its visible width depends on the output environment.

An ordinary quoted string literal must open and close on the same source line. Pressing Enter in the middle of it leaves an unclosed literal. To split a long message across source lines, write two complete literals joined with +, or use separate printing calls.

Key Takeaways

  • print stays on the current line; println adds a line break after its value.
  • Quotes make text literal: "name" prints those letters, while name prints the variable’s value.
  • Use escape sequences for new lines, tabs, quotes, and backslashes.
  • Spaces inside a string are printed exactly; output calls add no separating spaces.
  • Use double quotes for a string and single quotes for one char value.
  • An ordinary string literal opens and closes on one source line.
2

Store data in variables of the right type

Variables let a program keep values between statements, but each stored value has a type. Follow assignments one step at a time to see what changes and what stays fixed. Choose whole-number, decimal, character, or truth-value types to match the data, then combine text and values into readable messages. Small differences in literal spelling or the order of plus signs can change both the type and the result of an expression.

2.1 Declare, assign and update variables

A variable gives a value a name so that later statements can use it. Its type tells Java what kind of value it can hold; assignment changes the stored value.

Declare and initialize
int age;
age = 36;

The declaration introduces age as an int. The assignment stores 36. The combined form int age = 36; is called initialization. A local variable must receive a value before you read it. Declaring int age; and immediately printing age gives an error that the variable might not have been initialized.

Declare a name once in the same method body. To change its value later, write age = 37;, without repeating int. A second int age = 37; in that body tries to declare the same variable again.

Read assignment from right to left

The right side of = is calculated first. Java then stores that result in the variable on the left:

int count = 5;
count = count + 1;

The second statement reads the current 5, adds 1, and stores 6. The = sign means assignment, not a mathematical claim that a number equals itself plus one. The left side must name somewhere to store the value; 36 = age; is invalid.

Assignment copies the value at that moment:

int a = 5;
int b = a;
a = 10;

Now a holds 10 and b holds 5. There is no continuing link that recalculates b when a changes.

Trace a swap

Suppose first holds 4 and second holds 9. The sequence first = second; second = first; loses the 4 at the first step and leaves both values at 9. Preserve the original value first:

int temp = first;
first = second;
second = temp;
After statementfirstsecondtemp
int temp = first;494
first = second;994
second = temp;944

A trace table records each variable after each statement. For int x = 3; x = x * 2; x = x + 1;, the values are 3, then 6, then 7. Update one row at a time using the latest stored values.

Choose useful names and fixed types

Names can contain letters, digits, underscores, and dollar signs. They cannot begin with a digit or be a reserved word such as class. Case matters: total and Total differ. Use descriptive camelCase names such as distanceKm or secondsLeft.

A final variable can be assigned only once. final int SECONDS_PER_HOUR = 3600; gives a fixed conversion factor a clear name. Reassigning it fails to compile. Constants conventionally use uppercase words separated by underscores.

Since Java 10, var can infer a local variable’s type from its initializer. var count = 10; infers int; var price = 2.5; infers double. The inferred type stays fixed. var count; fails because there is no initializer from which to infer a type.

Key Takeaways

  • A declaration names a variable and its type; initialization also gives it a starting value.
  • Assignment evaluates the right side, then stores the result on the left.
  • Copying a value does not link variables; use a temporary variable when swapping values.
  • Read a local variable only after it has received a value.
  • final prevents reassignment, and var infers a fixed type from an initializer.

2.2 Choose a primitive type and write literals

The type of a value controls its range, its literal spelling, and the calculations Java can perform with it. Use int for ordinary counts and double for ordinary measurements, while recognizing the other primitive types.

Compare the eight primitive types
TypeStorage and values
byte8-bit integer: −128 to 127
short16-bit integer: −32,768 to 32,767
int32-bit integer: −2,147,483,648 to 2,147,483,647
long64-bit integer: −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float32-bit floating point; about 7 significant digits
double64-bit floating point; about 15–17 significant digits
charOne 16-bit UTF-16 code unit: 0 to 65,535
booleantrue or false

Finite float values extend approximately from −3.4 × 10³⁸ to +3.4 × 10³⁸; finite double values extend approximately from −1.8 × 10³⁰⁸ to +1.8 × 10³⁰⁸. These wide ranges do not make every decimal within them exactly representable.

A char often represents a single character, such as 'A'. Some Unicode characters require two UTF-16 code units, so one char cannot represent every possible character. 'A' has numeric code 65, 'a' has 97, and '7' has 55. The character '7' is distinct from the integer 7. A boolean is not a number: boolean active = 1; fails.

Spell literals for their types

A literal writes a value directly in source. 42 is an int literal, 42L a long, 3.5 a double, and 3.5f a float. Character literals use single quotes; String literals use double quotes. Primitive type names are lowercase, while String begins with a capital letter.

Write long large = 3000000000L;. Without the L, that integer literal is too large. Write float rate = 3.5f;: plain 3.5 has type double, which Java does not silently narrow to float. A fitting whole-number constant can initialize a smaller integer type: byte b = 100; compiles, but byte b = 200; does not.

Underscores between digits make a literal readable: 1_000_000 has the same value as 1000000. Scientific notation uses e, as in 1.5e3, meaning 1500.0. Source-code decimals always use a point.

Watch the operation’s range

An integer calculation can overflow without an error message. Adding 1 to the largest int wraps to the smallest int. The product 50_000 * 50_000 uses int arithmetic and produces -1794967296. In 50_000L * 50_000, one operand is long, so the product is the correct 2500000000.

Changing only the receiving variable to long is too late to repair an int product that has already overflowed. Choose a wide enough operand before the multiplication.

Floating-point values have a different limitation. Many decimal fractions are stored as binary approximations: 0.1 + 0.2 prints 0.30000000000000004. Format such results for display. Exact money calculations can store whole cents in a long; the BigDecimal class is another exact-decimal option.

Key Takeaways

  • Java has eight primitive types; String is a class.
  • Use a literal’s suffix to choose long (L) or float (f).
  • Integer calculations can overflow silently; widen an operand before the calculation.
  • Floating-point types store many decimal fractions approximately.
  • A char stores one UTF-16 code unit, while a boolean stores a truth value.
  • A source-code decimal uses a point, even on a computer that uses decimal commas.

2.3 Store text and join it with concatenation

A String holds text, including spaces, digits, punctuation, or no characters at all. The + operator can combine that text with other values to build a message.

Join values into text
String firstName = "Ada";
String lastName = "Lovelace";
System.out.println(firstName + " " + lastName);

The output is "Ada Lovelace". The middle literal supplies the space. Without it, firstName + lastName would produce "AdaLovelace". Concatenation does not add separators for you.

Concatenation means joining values into a new string. If either operand of + is a String, Java converts the other value to text and joins them. Thus "Age: " + 36 becomes "Age: 36", and "Price: " + 2.5 becomes "Price: 2.5". The digits in the result are now part of a text value.

String begins with a capital S. Unlike the eight primitive types, it is a class. Writing string name = "Ada"; with a lowercase s fails to compile. The empty string "" is valid text with no characters; it is not a missing value.

Follow plus signs from left to right

Consider:

System.out.println("Sum: " + 2 + 3);

The first + joins the String and 2, making "Sum: 2". The second joins that String and 3, making "Sum: 23". Once the running result is text, the next + continues to join text.

Compare three forms:

ExpressionResultReason
"Sum: " + 2 + 3"Sum: 23"Text is present at the first addition.
2 + 3 + " apples""5 apples"The first operation adds two numbers.
"Sum: " + (2 + 3)"Sum: 5"Parentheses make the sum happen first.

Use parentheses when a message should contain the result of an addition or subtraction. For example, "Diff: " + (5 - 2) gives "Diff: 3". Without the parentheses, "Diff: " + 5 - 2 tries to subtract 2 from a String and fails to compile.

Multiplication and division have higher precedence than +. The expression "Area: " + 4 * 5 calculates the product first and gives "Area: 20".

Build a message in stages
String message = "Hi";
message += "!";

The updated variable holds "Hi!". For a String, += appends text by assigning the joined result back to the variable. You can assemble a short message with several statements and print it once at the end.

Be careful with characters. Two char operands do not trigger String concatenation. 'A' + 'B' adds their numeric codes, 65 and 66, producing the int 131. Starting with the empty String changes the chain: "" + 'A' + 'B' first creates "A", then "AB". Quotes determine the operand types, so they also determine the meaning of +.

Key Takeaways

  • Concatenation joins text; it inserts no extra spaces.
  • A chain of + operations proceeds left to right after higher-precedence operations.
  • Put numeric addition or subtraction in parentheses before joining its result to a label.
  • Two char values add numerically unless a String is already part of the operation.
3

Calculate with arithmetic expressions

Calculations depend on both the order of operations and the types of their operands. Trace expressions before running them, especially when division appears inside a larger calculation. Whole-number division and remainders split quantities into groups or time units; decimal arithmetic keeps fractions. Ready-made Math methods handle roots, powers, and rounding, with return types that matter when you store their results.

3.1 Write expressions with operators and precedence

An expression combines values to produce a result. Java evaluates it according to operator precedence, then a statement can store or print that result.

Write the operations explicitly

The arithmetic operators are +, -, *, /, and %: addition, subtraction, multiplication, division, and remainder. With int width = 4; and int height = 5;, width * height evaluates to 20.

Every multiplication needs *. The algebra-like form 2(3 + 4) is invalid Java; write 2 * (3 + 4). Java has no arithmetic power operator. 2 ^ 3 means a bitwise operation and produces 1, not 8. To square a value, write x * x; to calculate another power, use Math.pow.

Apply precedence before reading left to right
OrderOperators or grouping
FirstParentheses
NextUnary minus and casts
Next*, /, %
Last+, -

At the same level, these arithmetic operators group from left to right. 2 + 3 * 4 is 14; (2 + 3) * 4 is 20. In 10 - 4 - 3, the first subtraction gives 6 and the second gives 3. In 24 / 4 * 2, the division gives 6 and multiplication gives 12. Treating the denominator as 4 * 2 would require parentheses.

Build an average correctly

Suppose int a = 7, b = 8, c = 10;. The expression a + b + c / 3 divides only c. Integer division makes 10 / 3 equal 3, and the additions then give 18.

(a + b + c) / 3 groups the whole total, 25, but both operands of / are integers. The result is 8. Using (a + b + c) / 3.0 keeps the fractional part and produces 8.333333333333334.

The operand types control the arithmetic. Two int operands produce an int result. A double operand makes the other numeric operand convert to double, as in 5 * 2.0, whose result is 10.0. The receiving variable does not change how the earlier arithmetic was done.

Update a stored value
int total = 10;
total += 5;
total *= 2;
total--;

The stored values become 10, 15, 30, and 29. For these int operands, total += 5; performs the same update as total = total + 5;. The operators -=, /=, and %= similarly combine an operation with assignment. count++; increases a variable by 1, and count--; decreases it by 1. Used as separate statements, their effect is easy to trace.

An expression such as a + b does not change either operand. To use its result, assign it or pass it to a printing call: int sum = a + b; or System.out.println(a + b);. The isolated line a + b; does not compile because Java does not allow that arithmetic expression as a standalone statement. Assignments, increments, decrements, and method calls can stand alone and can have effects.

Key Takeaways

  • Use explicit operators: * multiplies, and ^ does not calculate a power.
  • Apply precedence first; at the same arithmetic level, work from left to right.
  • Parenthesize a whole total before dividing it to find an average.
  • Operand types decide arithmetic results before assignment occurs.
  • Compound assignment stores an updated value; standalone ++ and -- change it by 1.

3.2 Use integer division and the remainder

Whole-number division answers how many complete groups fit. The remainder tells you what is left. Together, these operations split a quantity into useful parts.

Predict quotient and remainder

When both operands are integers, / discards the fractional part, moving toward zero. 7 / 2 is 3, 2 / 3 is 0, and -7 / 2 is −3. This is truncation, not rounding to the nearest integer.

The remainder operator % returns what remains after the division. 17 / 5 gives 3, and 17 % 5 gives 2. Three groups of 5 account for 15, leaving 2. For integer operands and a nonzero divisor, (a / b) * b + a % b reconstructs a using Java integer arithmetic.

The sign of a nonzero remainder follows the left operand: -7 % 3 is −1, while 7 % -3 is 1. For nonnegative integers, n % 2 is 0 for even values and 1 for odd values.

Split seconds into larger units

Start with 3725 seconds:

int totalSeconds = 3725;
int hours = totalSeconds / 3600;
int secondsAfterHours = totalSeconds % 3600;
int minutes = secondsAfterHours / 60;
int seconds = secondsAfterHours % 60;

The first division finds 1 complete hour. The remainder is 125 seconds. Dividing that remainder by 60 finds 2 minutes, with 5 seconds left. The result is 1 h 2 min 5 s. Rebuilding the total gives 3600 seconds plus 120 seconds plus 5 seconds, or 3725.

Use the remainder after removing hours to find minutes within the current hour. Dividing the original total by 60 would give all 62 complete minutes, including the minutes already counted as an hour.

The same operators extract decimal digits from a nonnegative integer. 4827 % 10 gives the last digit, 7; 4827 / 10 gives the remaining leading digits, 482.

Distinguish full groups from enough containers

For 50 eggs and boxes holding 12 eggs, 50 / 12 gives 4 full boxes and 50 % 12 gives 2 eggs left. Holding every egg needs a fifth box. For nonnegative counts and positive box sizes, the integer expression (count + size - 1) / size rounds the container count up, provided the addition does not overflow. For this example, (50 + 12 - 1) / 12 gives 5.

Choose fractional division before it happens
ExpressionStored or calculated result
double result = 7 / 2;3.0
double result = 7 / 2.0;3.5
double result = (double) 7 / 2;3.5

A double destination cannot recover a discarded fraction. Make an operand double before dividing when you need the fraction.

Division or remainder by integer zero throws ArithmeticException during execution. Floating-point division behaves differently: 5.0 / 0 gives Infinity, -5.0 / 0 gives -Infinity, and 0.0 / 0 gives NaN, meaning "not a number". A result can therefore be unusable even when execution does not stop.

Key Takeaways

  • Integer / truncates toward zero; % returns the remainder.
  • A nonzero integer remainder has the sign of the dividend.
  • Use successive quotients and remainders to split seconds into hours, minutes, and seconds.
  • Full boxes and boxes needed for every item answer different questions.
  • Make an operand double before division to keep a fraction.
  • Integer division by zero throws an exception; floating-point division can produce infinity or NaN.

3.3 Calculate with decimals and the Math class

Decimal arithmetic is useful for measurements and averages. The Math class adds ready-made calculations, while rounding lets you choose how to store or present a result.

Keep fractions and recognize approximations

150 / 2.5 gives 60.0, a speed in km/h when distance is 150 km and time is 2.5 hours. Because an operand is double, the division keeps a fractional result when needed. Ordinary whole-valued doubles print with a decimal part, such as 60.0.

A double stores a binary approximation of many decimal values. Consequently, 1.1 * 3 prints 3.3000000000000003, and 10.0 / 3 prints 3.3333333333333335. Keep the working value through later calculations and round when presenting it.

Large or small values can print in scientific notation. 1.23456789E7 represents 12345678.9, and 1.0E-4 represents 0.0001. For positive finite values, ordinary notation is used from 0.001 up to, but not including, 10000000. Scientific notation changes the displayed form, not the underlying value.

Call useful Math methods

Math is in java.lang, so no import is needed.

CallResult and purpose
Math.sqrt(16)4.0, a square root
Math.pow(2, 10)1024.0, a power
Math.abs(-7)7, an absolute value
Math.max(3, 9)9, the larger value
Math.min(3, 9)3, the smaller value

Math.sqrt and Math.pow return double. The constant Math.PI is approximately 3.141592653589793. For a circle with radius 2.5 cm, Math.PI * 2.5 * 2.5 gives 19.634954084936208 cm², about 19.63 cm². For a right triangle with legs of 3 cm and 4 cm, Math.sqrt(3 * 3 + 4 * 4) first adds the squared legs to get 25, then gives 5.0 cm.

Choose a rounding direction
CallResult
Math.round(2.4)2
Math.round(2.5)3
Math.round(-2.5)-2
Math.floor(2.7)2.0
Math.ceil(2.1)3.0
Math.floor(-2.7)-3.0

round chooses the nearest whole number, with exact halfway values going toward positive infinity. floor goes down toward negative infinity; ceil goes up toward positive infinity. For negatives, "down" means a more negative value, so flooring −2.7 gives −3.0.

For a double argument, Math.round returns a long. Store that result in a long, or explicitly convert it when an int is appropriate: int rounded = (int) Math.round(2.7); stores 3. floor and ceil return double values.

To round a stored value to two decimal places, use Math.round(12.3456 * 100) / 100.0, which gives 12.35. The scale-up step makes the hundredths position the whole-number boundary. Dividing by 100.0 scales back with floating-point division; dividing by integer 100 would discard the fraction and give 12. If only the printed text needs rounding, printf can format the original value directly.

Key Takeaways

  • A double keeps fractional results but approximates many decimal fractions.
  • Math.sqrt, Math.pow, and Math.PI support geometric calculations without an import.
  • round selects the nearest integer; floor and ceil choose a direction.
  • Math.round(double) returns long, while floor and ceil return double.
  • When scaling a rounded value back, use a decimal divisor to preserve its fraction.
4

Convert values between types

A value can move between numeric types or cross the boundary between numbers and text. Each route has its own rules: some numeric conversions happen automatically, some require a cast, and numeric text must be parsed before arithmetic. Follow the conversion at the exact point it occurs. Converting after an operation cannot recover information already lost, while a successful conversion can still change a large or fractional value.

4.1 Widen values and cast them explicitly

Java sometimes converts a numeric value automatically. Other conversions need an explicit cast. A cast changes the type of a value at a particular point in an expression, so its position affects the answer.

Widen automatically

The main numeric widening path is byte → short → int → long → float → double. A char also widens to int and onward. For example, double d = 5; stores 5.0, and any int value fits exactly in a long.

Widening into a floating-point type can lose precision. int to float, long to float, and long to double may round a large integer. Converting an int to a double is exact. For example, (float) 16777217 becomes 1.6777216E7, representing 16777216.

Cast a narrowing conversion

A cast writes the target type in parentheses before the value:

int n = (int) 3.99;

The stored result is 3. Without (int), Java rejects assigning the double literal to an int. Converting a finite, in-range double to an integer truncates toward zero: (int) -3.99 gives −3 too. Truncation differs from rounding; (int) Math.round(3.99) gives 4.

Narrowing conversions generally need a cast. One useful exception allows a fitting constant integer expression to initialize a byte, short, or char. Thus byte b = 100; is valid without (byte). A nonconstant int variable does not receive this constant-assignment exception simply because its current value fits.

Put the cast before the operation that needs it

Let int sum = 25; and int count = 3;.

ExpressionWhat happensResult
(double) sum / countConvert sum, then divide with a double.8.333333333333334
(double) (sum / count)Divide integers, then convert the whole-number result.8.0

A cast binds more tightly than multiplication and division. Parentheses determine whether it applies to one operand or a completed calculation. Casting after integer division cannot restore discarded information.

Predict changes to characters and small integers

(int) 'A' gives its character code, 65. Adding 1 to 'A' produces the int 66. To turn the complete result back into a character, write (char) ('A' + 1), giving 'B'. Without the outer parentheses around the sum, the cast would apply only to 'A'.

Narrowing between integer types keeps only the lower bits. (byte) 200 becomes −56; (int) 3_000_000_000L becomes −1294967296. A cast permits the conversion but does not check that the original value fits.

Compound assignment has a built-in conversion to the left-hand type. With int x = 10;, x += 2.7; calculates 12.7 and narrows it to 12. The plain assignment x = x + 2.7; fails because its right side is double.

Key Takeaways

  • Widening is automatic, but some conversions to floating point can round large integers.
  • A narrowing conversion generally needs a cast; fitting integer constants have a small-type assignment exception.
  • An in-range decimal-to-integer cast truncates toward zero.
  • Cast an operand before division when the operation must keep a fraction.
  • Integer narrowing can change a value by dropping high bits.
  • Compound assignment includes conversion back to the variable’s type.

4.2 Convert between text and numbers

Text can contain digits without being a number. To calculate with typed or stored text, parse it into a numeric type. To build a message, convert a numeric value back into text.

Parse text before calculating

The expression "42" + 1 produces "421". Because the left operand is a String, + performs concatenation. Integer.parseInt("42") + 1 produces 43 because parsing supplies an int before addition.

String first = "12";
String second = "30";
int total = Integer.parseInt(first) + Integer.parseInt(second);

Here total holds 42. Joining the original strings would give "1230". Choose conversion based on the value’s intended use, not on whether its characters happen to look numeric.

Integer.parseInt(text) returns an int; Long.parseLong(text) returns a long. Integer.valueOf("42") returns an Integer object, which Java automatically converts to int when an int is required. For a direct text-to-int operation, parseInt states the intended result clearly.

Parse decimals and truth values

Double.parseDouble("3.75") returns the double 3.75. Its text format uses a decimal point on every computer, regardless of regional settings. Double.parseDouble("3,5") fails. Java source literals also use a point, though keyboard-reading methods can follow a locale.

Boolean.parseBoolean(text) follows a separate rule: it returns true for "true" in any mix of capital and lowercase letters, such as "TRUE". Every other text returns false, including "yes". It does not interpret a general affirmative word as true.

Recognize invalid numeric text

Invalid numeric text causes a NumberFormatException while the program runs. Integer.parseInt("4.5") fails because decimal text is not an integer representation. Integer.parseInt("") and Integer.parseInt(" 42") fail too. The exception message identifies the text that could not be converted.

Whitespace handling depends on the parser. Double.parseDouble ignores spaces at the start and end, while Integer.parseInt does not. Choose test inputs that reveal these differences when reading user data.

A convenient input pattern is to read one whole line and parse it:

int age = Integer.parseInt(scanner.nextLine());
double height = Double.parseDouble(scanner.nextLine());

Each call consumes its entire line, including the line ending. That keeps text and numeric input consistent and avoids mixing token reads with whole-line reads.

Turn a number into text

String.valueOf(42), Integer.toString(42), and "" + 42 all produce the String "42". Double.toString(2.50) produces "2.5". The original decimal spelling does not remain attached to the stored number, so this conversion does not add a trailing zero to preserve it.

Use String.format when you need stored text with a fixed number of decimal places. Use printf when you want to print that formatted text directly. Neither a numeric cast nor basic concatenation supplies a fixed two-place display.

Key Takeaways

  • Numeric-looking text remains a String until it is parsed.
  • Integer.parseInt and Double.parseDouble produce numeric values for arithmetic.
  • Double.parseDouble uses a decimal point independently of locale.
  • Invalid numeric text causes NumberFormatException; integer parsing rejects surrounding spaces.
  • Boolean.parseBoolean accepts "true" in any capitalization and returns false for other text.
  • Basic number-to-text conversion does not preserve extra trailing zeros.
5

Read input and build complete programs

Input and output turn a calculation into a program someone can use. Match each prompt to a suitable Scanner read, decide how decimals will be entered, and choose clear output labels and numeric formats. Build a complete program from an input–calculation–output plan, then test it with results worked out by hand. A program can compile and finish successfully while still reading the wrong line or displaying the wrong value.

5.1 Read input with Scanner

Keyboard input arrives as text. A Scanner can read a whole line, one word, or a word converted into a number. Choose a consistent reading plan before asking the user for values.

Create one Scanner and read a line
import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("What is your name? ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}

The import goes before the class. The creation statement goes inside main and connects the Scanner to System.in. One Scanner is enough for this program. nextLine() waits for the typed line and returns its text without the line break. Typing "Ada" makes the final statement print "Hello, Ada!". Using print for the prompt keeps typing beside the question.

Choose lines or tokens
MethodWhat it reads
nextLine()The rest of the current line, without the ending
next()The next whitespace-separated token as text
nextInt()The next token as an int
nextLong()The next token as a long
nextDouble()The next token as a double
nextBoolean()The next token as a truth value

For "Ada Lovelace", next() returns "Ada". A following nextLine() returns " Lovelace", including its leading space. Two nextInt() calls can read "3 4" from one line. A numeric token that does not fit the method, such as "4.5" or "abc" for nextInt(), causes an InputMismatchException.

Account for the unread line ending

Suppose the user types "30", presses Enter, then types "Ada Lovelace" and presses Enter. This code does not read the name as intended:

int age = scanner.nextInt();
String name = scanner.nextLine();

nextInt() consumes 30 but leaves the line ending. nextLine() immediately consumes the empty remainder of that same line, so name is "". Add scanner.nextLine(); between the two statements to discard that remainder before reading the name on the next line.

Another solution is to read every answer with nextLine() and parse numeric lines: int age = Integer.parseInt(scanner.nextLine());. This avoids switching between two different units of input.

Make the decimal convention clear

nextDouble() follows the Scanner’s locale, initially the computer’s default formatting locale. A comma-decimal locale accepts "3,5" as a decimal and rejects "3.5" in this example. To read point decimals consistently, add import java.util.Locale; and create:

Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

Reading a whole line with Double.parseDouble(scanner.nextLine()) also uses a point. Changing the Scanner locale does not change Java source-code literals or the locale used by later printf calls.

Read values in the order requested by the prompts. If you ask for a name and then an age, the first read must store the name. A misplaced read can either put data in the wrong variable or trigger a conversion error.

Key Takeaways

  • Import java.util.Scanner before the class and create one Scanner inside main.
  • nextLine() reads the rest of a line; token methods read whitespace-separated values.
  • A numeric token of the wrong kind causes InputMismatchException.
  • After a numeric token read, consume the remaining line before reading text on the next line.
  • useLocale(Locale.US) fixes point-decimal Scanner input; line parsing is another consistent route.
  • Match input reads to the order of the prompts.

5.2 Format output with printf

Formatted output controls how values appear inside a message. printf can show a fixed number of decimal places, add a line break, and align values in columns without changing their stored values.

Match placeholders with values

A format string contains ordinary text plus specifiers that begin with %. Each value-consuming specifier takes the next value supplied after the format string:

System.out.printf("%s is %d years old%n", "Ada", 36);

This prints "Ada is 36 years old" and starts a new line. %s displays text or another value as text, %d displays an integer such as an int or long, and %f displays a floating-point value. %n inserts a line break without consuming a value. %% prints one percent sign.

printf adds no line break automatically. Include %n when the next output should start on a new line. An ordinary \n escape also represents a newline character inside Java text; %n is the formatter’s platform-specific line separator.

Set decimal places for display

Plain %f prints six places after the decimal separator: formatting 2.5 gives "2.500000". The precision in %.2f requests two places:

System.out.printf("Total: %.2f%n", 12.3456);

With US formatting, the output is "Total: 12.35". The value is rounded in the displayed text. A variable containing 12.3456 still contains that working value after printing.

For System.out.printf("%d items at %.2f each, total %.2f%n", 3, 1.5, 3 * 1.5);, the values fill the three placeholders in order. With US settings the output is "3 items at 1.50 each, total 4.50".

Line up fields with width

A width is a minimum field size. %5d right-aligns an integer within at least five characters; %-6s left-aligns text within at least six. %6.1f combines width 6 with one decimal place.

System.out.printf("[%5d][%-6s][%6.1f]%n", 42, "Ada", 9.25);

With US settings, the exact output is [ 42][Ada ][ 9.3]. The square marks make the padding visible. A value longer than its width is still printed in full; width does not cut characters off.

A mismatched specifier causes a runtime error. printf("%d%n", 2.5) compiles but throws IllegalFormatConversionException because %d expects an integer value. Too few supplied values, as in printf("%d %d%n", 2), cause MissingFormatArgumentException.

Choose printing or stored text

String.format applies the same formatting rules but returns a String:

String line = String.format("%.1f km", 12.345);

With US settings, line holds "12.3 km"; nothing has been printed by that statement.

Both formatting methods use the default locale unless you pass one. Add import java.util.Locale;, then use System.out.printf(Locale.US, "%.2f%n", 12.3456); to ensure "12.35" instead of the "12,35" used by a comma-decimal locale. String.format can take Locale.US first too. Printing a double with println uses a point independently of the formatting locale.

Key Takeaways

  • Match each consuming specifier with the next value of a suitable type.
  • Use %n for a line break and %% for a literal percent sign.
  • %.2f rounds displayed text to two places without changing the stored value.
  • Width pads a field to a minimum size; it does not truncate longer values.
  • String.format returns text, while printf prints it.
  • Pass a locale to control the decimal separator in formatted output.

5.3 Combine input, calculation and output

A complete calculation program connects three stages: read the inputs, calculate with them, and print the results. Planning the values and their units before typing helps you choose types and test the result.

Plan a travel-time program

The inputs are distance in kilometers and average speed in km/h. Dividing distance by speed gives time in hours. Both measurements need double so the division can keep a fraction. The output will be whole hours and minutes, rounded to the nearest minute.

import java.util.Scanner;

public class TravelTime {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Distance (km): ");
        double distance = Double.parseDouble(scanner.nextLine());
        System.out.print("Speed (km/h): ");
        double speed = Double.parseDouble(scanner.nextLine());
        int totalMinutes = (int) Math.round(distance / speed * 60);
        int hours = totalMinutes / 60;
        int minutes = totalMinutes % 60;
        System.out.println("Travel time: " + hours + " h " + minutes + " min");
    }
}

For 150 km at 80 km/h, division gives 1.875 hours. Multiplication by 60 gives 112.5 minutes. Math.round returns the long 113, and the cast converts it to int. Integer division and remainder then give 1 hour and 53 minutes. The output is "Travel time: 1 h 53 min".

If distance and speed were both int, 150 / 80 * 60 would produce 60. The fraction disappears at the division, before the multiplication. Type choices belong in the plan, not just in the final output statement.

Choose display and arithmetic separately

For a bill total of 87.60 shared among 4 people, store the total in double and the count in int. double share = total / people; gives 21.9. With US formatting, System.out.printf("Each person pays %.2f%n", share); prints "Each person pays 21.90". Formatting supplies the second decimal place without changing the calculation.

For whole-number scores 7, 8, and 10, double average = (a + b + c) / 3.0; gives 8.333333333333334, displayed as "8.33" with %.2f. Parentheses group the total and the decimal divisor keeps its fraction.

Test against results you know

Work out expected results before running the program. For travel time, 120 km at 60 km/h should print 2 h 0 min. A distance of 0 km at a positive speed should print 0 h 0 min. Try inputs near a rounding boundary and larger valid distances to exercise more than the simplest calculation.

Include zero, negative, and large inputs when checking the program’s behavior. Decide whether each input makes sense for the task. A count of zero people makes total / people produce Infinity when total is a nonzero double; integer division by zero throws ArithmeticException. Successful execution alone does not establish a useful answer.

When output differs from your expectation, print intermediate values or trace them in a table. Find the first value that is wrong, fix the responsible statement, and rerun the known tests. Compare spaces and labels as well as numbers.

Use names such as totalMinutes, named constants such as MINUTES_PER_HOUR, units in prompts, and short comments that explain the purpose of a calculation.

Key Takeaways

  • List inputs, outputs, formulas, units, and types before writing a calculation program.
  • Keep measurement fractions during arithmetic, then round when the output calls for whole units.
  • Test ordinary, boundary, and unsuitable inputs against expected behavior.
  • Trace intermediate values to locate the first incorrect step.
  • Clear names, constants, and units make a program easier to check.

First Java Programs examples

5 Walkthroughs

1

Build and run a small message program

13 steps
Follow a program from its class structure to exact output, then locate the stage at which a mistake occurs.
  1. 1
    IntroductionFollow instructions from main

    A Java program needs an entry point and a sequence of instructions. In the classic form, a class contains main, and main contains the statements that run.

    You will build a short notice, launch it, and trace the output position through several printing calls. The same sequence helps with debugging: first check that the source compiles, then that it runs, then that its output matches the intended notice.

  2. 2
    ExamplePlace the notice inside the method

    Start with this complete structure:

    public class Notice {
        public static void main(String[] args) {
            System.out.println("Studio open");
        }
    }
    

    The outer braces enclose the class; the inner pair encloses the method. Java begins with the printing statement inside main. Its semicolon ends the statement, while the closing braces end the two surrounding bodies.

  3. 3
    TipCheck names before adding more code

    Save the public class Notice in Notice.java. Match the capital N exactly. Also preserve System and the lowercase method name main: Java treats different capitalizations as different names.

    Indent each nested body by four spaces so that a misplaced brace is easy to spot. A short // comment can explain a reason for a step without becoming an executable instruction.

  4. 4
    ChallengeRepair the entry method

    A file correctly declares public class Bulletin, but its only method is public static void Main(String[] args). It compiles and the launcher cannot find the main method. What change is needed?

    ---reveal---

    Change Main to main. The capitalized name declares a different method, so it does not supply the intended entry point. The file must also remain named Bulletin.java to match its public class.

  5. 5
    ExplanationCompile and launch the notice

    From the source folder, enter:

    javac Notice.java
    java Notice
    

    javac checks the source and produces Notice.class bytecode. java starts the JVM to run that class. A JDK supplies both commands; an IDE runs these stages behind its Run button. In the compiled-class launch command, leave off the .class extension. java Notice.java is a separate source-file launch form available since Java 11.

  6. 6
    ChallengeRead the first error first

    After deleting the closing quotation mark of a message, a learner sees several compiler messages on that and later lines. Should each later statement be rewritten immediately? Explain the next step.

    ---reveal---

    Repair the first error by closing the string literal, save, and compile again. One unclosed quote can make later code appear malformed. Recompiling shows whether those later messages disappear before any further edits are needed.

  7. 7
    ExampleTrace the first two printing calls

    Replace the original message with:

    System.out.print("Studio ");
    System.out.print(3);
    

    The first call prints the word and its trailing space. Because print adds no line break, the second call places 3 immediately after that space. The current output is "Studio 3", and the next call would still continue on this line. Output calls insert no extra separators of their own.

  8. 8
    ExampleEnd one line and begin another

    Continue the same program with:

    System.out.println(" open");
    System.out.println("Welcome");
    

    The first call adds its leading space and the word "open" to the existing line, then ends that line. The second prints "Welcome" and ends the next line. The finished text is:

    Studio 3 open
    Welcome
    

    There is no blank line between the messages; an empty println() would add one.

  9. 9
    Key InsightQuotes and escapes choose the text

    Quotation marks decide whether Java prints literal text or evaluates code. println("3 + 4") prints "3 + 4"; println(3 + 4) prints 7.

    To include a quote within a literal, write \". For a new line within a literal, write \n; a tab is \t, and one backslash is \\. The escape sequences become characters in the resulting text. An ordinary literal itself must open and close on one source line.

  10. 10
    ChallengePredict line boundaries

    What does this code print?

    System.out.print("A");
    System.out.println("B");
    System.out.println();
    System.out.print("C");
    

    ---reveal---

    The first line is "AB", the second line is blank, and the third contains "C". The first call stays on its line, the next finishes it, and the empty println() supplies another line break. No spaces appear between A and B because no statement prints one.

  11. 11
    ConnectionLocate the failure stage

    Suppose a modified notice compiles, starts, and then stops at an integer division by zero. That is a runtime error, reported by an exception. If it finishes but labels a room with the wrong number, that is a logic error.

    Compilation checks Java’s rules; it does not know which room you intended. Work out the expected notice before testing and compare every label, value, space, and line break.

  12. 12
    ChallengeSeparate two repairs

    A program first fails to compile because a printing statement has no semicolon. After that repair, it runs but prints two messages on one line when two lines are required. What should change at each stage?

    ---reveal---

    Add the semicolon to repair the compile-time error. Then change the first message’s print to println, or print a line break there, to repair the output logic. Check the second change by comparing the actual line layout with the expected layout.

  13. 13
    RecapCheck structure, execution, and output

    Use the class and main structure to locate the executable statements. Match the public class name to the source file, then compile and launch with the appropriate commands.

    Trace printing calls by following the current output position: print stays, println advances. When a result is wrong, identify whether compilation failed, execution stopped, or the finished output differs from your expectation. Each case points to a different check.

2

Trace stored values and build a message

12 steps
Follow copies and updates, select types, and see how text changes the meaning of plus.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrack values before predicting output
  2. 2
    ExampleCreate two independent stored values
  3. 3
    ExampleUpdate only the named destination
  4. 4
    ChallengePreserve a value during a swap
  5. 5
    TipUse final and var deliberately
  6. 6
    ExplanationChoose a type that matches the data
  7. 7
    ExampleLet literal spelling choose the type
  8. 8
    ChallengeWiden before multiplication
  9. 9
    ExampleBuild a message from the trace
  10. 10
    ChallengeDecide when plus means addition
  11. 11
    ChallengeCombine a copied value with new output
  12. 12
    RecapUse the latest value and the actual type
3

Split a duration and calculate with fractions

14 steps
Work through arithmetic order, time units, decimal calculations, and rounding choices.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose the operation that fits the question
  2. 2
    ExplanationGroup a complete calculation
  3. 3
    ChallengeRepair an average expression
  4. 4
    ExampleCount complete hours
  5. 5
    ExampleKeep the seconds after those hours
  6. 6
    ExampleExtract minutes and seconds
  7. 7
    ChallengeSplit a different duration
  8. 8
    Key InsightTruncation moves toward zero
  9. 9
    ExampleKeep the fraction of a measurement
  10. 10
    ExplanationUse Math for a root or power
  11. 11
    ChallengeChoose the rounding rule
  12. 12
    TipScale back with a decimal divisor
  13. 13
    ChallengeKeep an average before rounding it
  14. 14
    RecapTrace type and grouping at each operation
4

Convert values at the right point

11 steps
Compare widening, casting, parsing, and number-to-text conversion through short traces.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk what value reaches the conversion
  2. 2
    ExplanationWiden a numeric value automatically
  3. 3
    ExampleCompare two cast positions
  4. 4
    ChallengeConvert and round a negative value
  5. 5
    TipDo not treat a cast as a range check
  6. 6
    ExampleParse before adding
  7. 7
    ExplanationMatch the parser to the text
  8. 8
    ChallengePredict parsing results
  9. 9
    ConnectionPrepare text for display
  10. 10
    ChallengeFollow the whole conversion chain
  11. 11
    RecapChoose a conversion for its job
5

Read, calculate, format, and test

16 steps
Build a measured-rate program while following whole-line input, format strings, and useful tests.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild a program around its data
  2. 2
    ExplanationConnect one Scanner to keyboard input
  3. 3
    ExampleRead a label as a whole line
  4. 4
    ExampleParse numeric lines consistently
  5. 5
    ChallengeFix a skipped label
  6. 6
    TipSet numeric input conventions explicitly
  7. 7
    ExampleCalculate with the intended types
  8. 8
    ExplanationMake the format string match the values
  9. 9
    ExamplePrint a rounded measurement
  10. 10
    ChallengeRepair the specifier
  11. 11
    ExampleStore or align formatted text
  12. 12
    ExplanationChoose tests before running
  13. 13
    ChallengeFind a calculation bug with a test
  14. 14
    TipTrace the first unexpected value
  15. 15
    ChallengeTransfer the plan to a rate
  16. 16
    RecapCheck the whole path from input to text

First Java Programs practice questions

50 Practice Questions in 5 sets

Set 1: Choose types and connect input to output10 Practice Questions

Question 1 of 10

In a classic program, where does execution begin?
  1. At the first import.
  2. At the class declaration.
  3. At the last statement in main.
  4. At the first statement in main.
Show answerHide answer
Answer: D
The launcher enters main and begins executing its first statement, continuing through the method in order. Imports and the class declaration organize the source; they are not the first executable instructions. Starting at the last statement would reverse the program’s stated sequence.

Question 2 of 10

A program compiles and finishes, but prints 4.0 for double average = 19 / 4;. What kind of error explains the inaccurate average?
  1. A logic error from integer division.
  2. A runtime error from integer division.
  3. A compile-time error from assignment.
  4. A runtime error from overflow.
Show answerHide answer
Answer: A
The program has a logic error: 19 / 4 completes as integer division and gives 4, which is then stored as 4.0. This code is legal and does not stop with an exception. A double destination does not make the preceding division fractional; an operand must be changed before the operation.

Question 3 of 10

What are left and right after this attempted swap?

int left = 2;
int right = 7;
left = right;
right = left;
  1. left = 7, right = 2
  2. left = 2, right = 7
  3. left = 7, right = 7
  4. left = 2, right = 2
Show answerHide answer
Answer: C
The first assignment replaces the original 2 in left with 7. The next assignment copies that current 7 into right, so both variables end at 7. A real swap needs to preserve the original left value in a temporary variable before overwriting it; the attempted swap has already lost it.

Question 4 of 10

A program must store the whole-number count 4,200,000,001 exactly. What declaration does this?
  1. int count = 4_200_000_001;
  2. long count = 4_200_000_001L;
  3. long count = 4_200_000_001;
  4. float count = 4_200_000_001f;
Show answerHide answer
Answer: B
The count exceeds the int range, so use long and mark the literal with L. A long destination alone does not make an oversized, unsuffixed integer literal valid. A float has a wide range but insufficient precision to store every whole number of this size exactly.

Question 5 of 10

A recording lasts 247 seconds. What minute-and-second values result from splitting it into complete minutes and remaining seconds?
  1. 4 min 11 s
  2. 5 min 7 s
  3. 4 min 7 s
  4. 4 min 47 s
Show answerHide answer
Answer: C
Integer division 247 / 60 gives 4 complete minutes. The remainder 247 % 60 is 7 seconds, since four minutes account for 240 seconds. Keeping the final two decimal digits as 47 confuses base-ten notation with time units, which group seconds in sixties.

Question 6 of 10

What value does Math.floor(-4.2) return?
  1. -4.0
  2. -5.0
  3. 4.0
  4. 5.0
Show answerHide answer
Answer: B
Math.floor returns the greatest whole-valued double no larger than its argument, so −4.2 becomes −5.0. Truncation toward zero would give −4, but flooring chooses the direction toward negative infinity. The return value remains a double, which is why the result is shown with .0.

Question 7 of 10

String quantity = "16"; What expression produces the integer 21 from this text?
  1. quantity + 5
  2. (int) quantity + 5
  3. Integer.toString(16) + 5
  4. Integer.parseInt(quantity) + 5
Show answerHide answer
Answer: D
Integer.parseInt(quantity) converts the digit text into the int 16, and numeric addition then gives 21. quantity + 5 instead concatenates and produces "165". A numeric cast cannot parse a String, while Integer.toString converts in the opposite direction, from a number to text.

Question 8 of 10

A user types the full name "Noor van Dijk" on a fresh input line. What Scanner call reads the whole name into one String?
  1. scanner.nextLine()
  2. scanner.next()
  3. scanner.nextInt()
  4. scanner.nextBoolean()
Show answerHide answer
Answer: A
nextLine() reads all remaining text on the current line, so it includes every word of the name and the spaces between them. next() reads only one token, "Noor", leaving the rest unread. The numeric and Boolean methods do not match this text and cannot read the full name.

Question 9 of 10

With US formatting, what text does System.out.printf("Mass: %.2f kg%n", 6.375); print before its line break?
  1. Mass: 6.37 kg
  2. Mass: 6.375 kg
  3. Mass: 6.38 kg
  4. Mass: 6.375000 kg
Show answerHide answer
Answer: C
The precision .2 requests two digits after the decimal point and rounds the displayed value, so the text is "Mass: 6.38 kg". Keeping "6.375" ignores the requested precision. Truncating to "6.37" also misses the formatter’s rounding; the numeric value passed into the call is not modified.

Question 10 of 10

A speed program uses int km = 45; int minutes = 50; double speed = km / minutes * 60;. It prints zero. What replacement computes the speed in km/h while preserving the inputs?
  1. double speed = (double) km / minutes * 60;
  2. double speed = (double) (km / minutes) * 60;
  3. double speed = km / minutes * 60.0;
  4. double speed = km / (minutes * 60.0);
Show answerHide answer
Answer: A
The distance must be divided with floating-point arithmetic before converting kilometers per minute to kilometers per hour. Casting km first gives 0.9, then multiplying by 60 gives 54.0 km/h. Introducing a double only at the final multiplication is too late: integer 45 / 50 has already become zero.
Set 2: Read and trace your first Java code10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

With int total = 19; int groups = 4;, what expression gives a fractional quotient?
  1. (double) (total / groups)
  2. (double) total / groups
  3. total / (int) groups
  4. (int) (total / 4.0)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What value does saved hold after these statements?

int stock = 8;
int saved = stock;
stock = stock + 6;
  1. 14
  2. 8
  3. 6
  4. 22
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What suffix makes 4.25 a float literal in Java?
  1. L
  2. d
  3. f
  4. No suffix
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does System.out.println("Seats: " + 6 + 2); print?
  1. Seats: 8
  2. Seats: 62
  3. Seats: 6 2
  4. Seats: 6+2
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What value is assigned by int result = 18 - 6 / 3 * 2;?
  1. 14
  2. 8
  3. 16
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What is the value of the Java expression -11 / 4?
  1. -2.75
  2. -3
  3. 2
  4. -2
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A classic program declares public class TrailLog. What must its source file be named?
  1. TrailLog.txt
  2. TrailLog.class
  3. TrailLog.java
  4. TrailLog
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

javac Desk.java succeeds. What terminal command launches the compiled class?
  1. java Desk
  2. java Desk.class
  3. javac Desk
  4. Desk.class
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What exact text is printed, with / representing a line break?

System.out.print("Gate ");
System.out.println(4);
System.out.print("Open");
  1. Gate /4/Open
  2. Gate4/Open
  3. Gate 4Open
  4. Gate 4/Open
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A Scanner receives "27", Enter, "Mina Chen", Enter. What does this code print?

int age = scanner.nextInt();
scanner.nextLine();
String first = scanner.next();
String rest = scanner.nextLine();
System.out.println(age + ":" + first + ":" + rest);
  1. 27:Mina:Chen
  2. 27::Mina Chen
  3. 27:Mina: Chen
  4. 27:Mina Chen:
Show answerHide answer

Save this lesson to see this answer.

Set 3: Trace calculations and formatted results10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What Java string literal prints the text Path: C:\Work with exactly one backslash?
  1. "Path: C:\Work"
  2. "Path: C:\\Work"
  3. "Path: C:/Work"
  4. "Path: C:\nWork"
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does System.out.println(3 + 4 + " / " + 3 * 4); print?
  1. 7 / 12
  2. 7 / 34
  3. 34 / 34
  4. 34 / 12
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What value is printed?

int value = 20;
value -= 3 * 2;
value /= 4;
System.out.println(value);
  1. 8
  2. 3.5
  3. 7
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What value is stored by double value = Math.round(8.276 * 100) / 100;?
  1. 8.28
  2. 8.27
  3. 8.0
  4. 828.0
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What int value results from (int) -6.8?
  1. -7
  2. -6
  3. 6
  4. 7
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What happens when Integer.parseInt(" 58") is evaluated?
  1. It returns the int 58.
  2. It returns the String "58".
  3. It throws InputMismatchException.
  4. It throws NumberFormatException.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Input is "Lina Park" followed by Enter. What String does rest receive?

String first = scanner.next();
String rest = scanner.nextLine();
  1. " Park"
  2. "Park"
  3. ""
  4. "Lina Park"
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

With US formatting, what exact text is printed by System.out.printf("[%4d][%-5s]", 7, "Oak");?
  1. [7 ][Oak ]
  2. [ 7][ Oak]
  3. [ 7][Oak ]
  4. [ 7][Oak ]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A program receives 10.5 liters shared equally among 4 containers. It must keep the fractional share for later use and print "2.63 L" with US formatting. What calculation and output meet both needs?
  1. int share = (int) (10.5 / 4); System.out.printf(Locale.US, "%.2f L", (double) share);
  2. double share = 10.5 / 4; System.out.printf(Locale.US, "%.2f L", share);
  3. double share = Math.round(10.5 / 4); System.out.printf(Locale.US, "%.2f L", share);
  4. double share = 10.5 / 4; System.out.printf(Locale.US, "%d L", share);
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A timer stores int seconds = 7_489;. What pair of expressions gives the complete hours and the remaining whole minutes within the current hour?
  1. seconds / 3600, seconds / 60
  2. seconds % 3600, seconds / 60
  3. seconds / 3600, seconds % 60
  4. seconds / 3600, seconds % 3600 / 60
Show answerHide answer

Save this lesson to see this answer.

Set 4: Find the first step that goes wrong10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What is printed?

int value = 9;
value += 2.8;
double result = value / 4;
System.out.println(result);
  1. 2.95
  2. 2.75
  3. 3.0
  4. 2.0
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A right triangle has legs 5 cm and 12 cm. What value does Math.sqrt(5 * 5 + 12 * 12) return?
  1. 13.0
  2. 17.0
  3. 169.0
  4. 60.0
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What punctuation ends the Java statement System.out.println("Ready")?
  1. A closing brace: }
  2. A colon: :
  3. A semicolon: ;
  4. A comma: ,
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

After deleting one closing brace, a learner sees several compiler errors on later lines. What is the best next action?
  1. Inspect the first error and the nearby braces, repair the missing brace, and compile again.
  2. Repair the last error first, then change every earlier line named by the compiler.
  3. Run the last compiled class repeatedly until the compiler messages disappear.
  4. Rename the class and run it before checking the saved source again.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What happens after var count = 6; when the same method executes count = 6.5;?
  1. The variable changes from int to double.
  2. The decimal is silently stored as 6.
  3. The program compiles but stops at runtime.
  4. Compilation fails because count is int.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A counter uses int edge = 70_000; long area = edge * edge;. The stored area is wrong. What replacement computes the exact whole-number product while leaving edge as int?
  1. long area = (long) (edge * edge);
  2. long area = (long) edge * edge;
  3. long area = (int) edge * edge;
  4. long area = edge * edge + 0L;
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does this code print?

int width = 12;
int height = 7;
int total = 2 * (width + height);
total -= 5;
double part = total / 4;
System.out.println(part);
  1. 8.25
  2. 9.0
  3. 8.0
  4. 6.0
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What does Boolean.parseBoolean("Yes") return?
  1. true, because Yes is affirmative.
  2. false, because the text is not true.
  3. It throws NumberFormatException.
  4. It throws InputMismatchException.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A test of a seconds converter uses 61 seconds and expects "1 min 1 s". The program prints "1 min 61 s". It uses minutes = totalSeconds / 60; seconds = totalSeconds;. What correction fixes the calculation?
  1. seconds = totalSeconds / 60;
  2. seconds = minutes % 60;
  3. seconds = totalSeconds % 60;
  4. seconds = totalSeconds - minutes;
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A Scanner uses Locale.US and reads two lines with double mass = scanner.nextDouble(); String label = scanner.nextLine();. Input is "2.75", Enter, "Sample B", Enter. What change preserves both intended values?
  1. Use next() for the label after the numeric read.
  2. Remove Locale.US and keep both reads unchanged.
  3. Read the label twice and concatenate the results.
  4. Read mass with Double.parseDouble(scanner.nextLine()).
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine the rules in complete program traces10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

With US formatting, what text is stored in line?

String line = String.format("%d%% / %.1f", 25, 4.25);
  1. 25% / 4.2
  2. 25% / 4.3
  3. 25%% / 4.3
  4. 25% / 4.250000
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What escape sequence puts a double quotation mark inside an ordinary Java string literal?
  1. \n
  2. \t
  3. \"
  4. \\
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does this code print?

int a = 4;
int b = 7;
String text = "R=" + a + b;
a += 2;
text += ":" + (a + b);
System.out.println(text);
  1. R=47:13
  2. R=11:13
  3. R=67:13
  4. R=47:67
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A workshop has 83 parts. Each tray holds 15 parts. How many complete trays and leftover parts are there?
  1. 5 trays and 3 parts
  2. 6 trays and 8 parts
  3. 6 trays and 7 parts
  4. 5 trays and 8 parts
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What value is printed?

int number = 6_843;
int last = number % 10;
number /= 10;
int next = number % 10;
System.out.println(last * 10 + next);
  1. 34
  2. 43
  3. 84
  4. 33
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What expression converts the result of adding 2 to the character code of 'C' back into the character 'E'?
  1. (char) 'C' + 2
  2. (char) ('C' + 2)
  3. (int) ('C' + 2)
  4. "C" + 2
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does this code print?

int total = 23;
int count = 4;
double a = (double) (total / count);
double b = (double) total / count;
System.out.println((int) (b - a) + ":" + b);
  1. 1:5.75
  2. 0:5.0
  3. 0:5.75
  4. 1:5.0
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A Scanner using Locale.US receives "3 2.5", Enter, "West Lab", Enter. What values do name and full receive?

int count = scanner.nextInt();
double mass = scanner.nextDouble();
String name = scanner.nextLine();
String full = scanner.nextLine();
  1. name = "West", full = " Lab"
  2. name = "West Lab", full = ""
  3. name = "", full = "West"
  4. name = "", full = "West Lab"
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A program reads two whole-number test scores on separate lines, 11 and 14. It must store their fractional average and display "Mean: 12.50" with a final line break, using a point on every computer. What input, calculation, and output code meets these requirements? A Scanner named scanner is ready, and Locale is imported.
  1. int a = scanner.nextInt(); int b = scanner.nextInt(); double mean = (a + b) / 2; System.out.printf(Locale.US, "Mean: %.2f%n", mean);
  2. int a = Integer.parseInt(scanner.nextLine()); int b = Integer.parseInt(scanner.nextLine()); double mean = (a + b) / 2.0; System.out.printf("Mean: %.2f%n", mean);
  3. int a = Integer.parseInt(scanner.nextLine()); int b = Integer.parseInt(scanner.nextLine()); double mean = (a + b) / 2.0; System.out.printf(Locale.US, "Mean: %.2f%n", mean);
  4. int a = Integer.parseInt(scanner.nextLine()); int b = Integer.parseInt(scanner.nextLine()); double mean = (a + b) / 2.0; System.out.println("Mean: " + mean);
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A program reports a route’s travel time as whole hours and remaining minutes, rounded to the nearest minute. For 121.5 km traveled at a steady 54 km/h, what output should it produce?
  1. 2 h 15 min
  2. 2 h 25 min
  3. 2 h 0 min
  4. 3 h 0 min
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

75 Key Terms, each with its definition

A

Assignment
An assignment evaluates a right-hand expression and stores its value in the variable or other location on the left.
After count = count + 2;, count holds two more than the value it held before that statement.

B

Block
A block is a group of statements enclosed in matching curly braces, allowing Java to treat them as one body.
The braces after the main header surround the statements that belong to that method’s body.
boolean
The boolean type stores one of the two truth values, true and false, and does not accept numbers as substitutes.
The declaration boolean isMember = true; stores a truth value without using quotes or a number.
Bytecode
Bytecode is the compiled instruction form stored in Java .class files and executed by a suitable Java Virtual Machine.
A successful compilation creates bytecode that the java launcher can run through the JVM.

C

Cast
A cast explicitly requests a type conversion by placing the target type in parentheses before the value being converted.
In (double) total / count, the cast changes an operand’s type before the division is performed.
Ceiling
The ceiling of a value is the least integer-valued number no smaller than that value; Math.ceil returns it as a double.
For 4.2 groups, the ceiling is 5.0, representing the next whole number in the upward direction.
char
The char type stores one 16-bit UTF-16 code unit, written as a literal in single quotes and numbered from 0 to 65,535.
The character '7' has code 55, so storing it as char does not make it the integer value 7.
Class
A class is a named Java program structure whose body contains members such as methods; a classic first program declares one class.
The declaration public class Greeting opens the class that holds the program’s main method.
Comment
A comment is explanatory source text ignored by the compiler, written after // or between /* and */.
The comment // Convert to minutes explains why a time calculation multiplies an hour value by 60.
Compile-time error
A compile-time error is a violation detected while Java checks source code, preventing that source from compiling successfully.
An unclosed ordinary string literal produces a compile-time error before the program can run.
Compiler
A compiler checks source code against language rules and translates valid code into another form, such as Java bytecode.
Running javac Notice.java invokes the compiler, which reports an error if a semicolon is missing.
Compound assignment
A compound assignment combines an operation with assignment and includes conversion back to the left-hand variable’s type.
The statement total += 5; increases an int total by 5 and stores the updated value in total.
Concatenation
Concatenation joins values into a new String, converting a non-String operand to text when the other operand is a String.
The concatenation "Count: " + 8 builds one message containing a label, a space, and a digit.
Constant
A constant is a fixed value; a Java final variable can receive a value once and cannot be reassigned afterward.
The constant MINUTES_PER_HOUR gives the number 60 a useful name in time conversion calculations.

D

Declaration
A declaration introduces a variable’s name and type; it may also include an initializer that supplies a starting value.
The declaration int count; introduces a name, but count still needs a value before it is read.
Decrement
A decrement decreases a variable’s value by one; Java’s -- operator performs this update without a separate subtraction assignment.
The statement secondsLeft--; reduces the stored number of remaining seconds by exactly one.
Dividend
A dividend is the value being divided, written to the left of / or % in a two-operand Java division expression.
In -11 % 4, the negative dividend explains why the nonzero remainder is negative too.
double
The double type stores 64-bit binary floating-point values, usually keeping about 15–17 significant decimal digits.
A distance of 18.75 km can be stored as a double so later arithmetic can keep fractional results.
Double.parseDouble
The Double.parseDouble method converts valid floating-point text into a double using a decimal point regardless of locale.
A whole input line containing "2.75" can be parsed as a double on either point- or comma-decimal systems.

E

Empty string
An empty string is a String with no characters, written as two adjacent double quotation marks with nothing between them.
Starting with "" + 'A' + 'B' makes the additions build text and gives the String "AB".
Escape sequence
An escape sequence is a backslash-led code inside a literal that represents a character such as a newline or a quote.
The escape sequence lets one printing call place the next part of its message on another line.
Expected output
Expected output is the text and values a correct program should produce for specified inputs, worked out before the test.
Comparing expected output with actual output can reveal a wrong number, missing unit, or extra space.
Expression
An expression is Java code that computes a value or performs an operation, such as adding two values or calling a method.
The expression width * height computes an area that can be assigned or passed to a printing call.

F

Field width
A field width is the minimum number of characters reserved for a formatted value, with spaces added when the value is shorter.
Formatting 7 with %4d produces three leading spaces before the digit to fill the four-character field.
float
The float type stores 32-bit binary floating-point values with about seven significant decimal digits of precision.
The f suffix in 2.75f marks a float literal, while plain 2.75 is a double literal.
Floating-point approximation
A floating-point approximation is a nearby representable binary value used when a decimal fraction cannot be stored exactly.
A small extra decimal tail in 1.1 * 3 reveals floating-point approximation in the displayed result.
Floor
The floor of a value is the greatest integer-valued number no larger than that value; Math.floor returns it as a double.
For a negative fraction such as -4.2, the floor is -5.0, which lies below it on the number line.
Format specifier
A format specifier is a percent-led instruction inside a format string, such as %d for an integer or %n for a line break.
Each %f consumes a floating-point value, while %n adds a line separator without consuming a value.
Format string
A format string combines literal text with percent-led specifiers that control where and how supplied values appear.
The format string "Mass: %.2f kg%n" places a two-decimal measurement between its label and unit.
Formatting precision
Formatting precision controls detail in formatted output; with %f, it sets the number of digits after the decimal separator.
The precision in %.2f turns a displayed 4.5 into "4.50" without modifying the numeric variable.

I

Increment
An increment increases a variable’s value by one; Java’s ++ operator performs this update in a single statement.
A standalone count++; changes a stored count of 8 to 9 before the following statement runs.
Initialization
Initialization gives a variable its first value, often in the same statement that declares the variable’s name and type.
The line double speed = 72.5; declares speed and initializes it to a measurement in km/h.
Input–calculation–output plan
An input–calculation–output plan identifies what a program reads, how it processes those values, and what results it presents.
A speed calculator reads distance and time, divides them using compatible units, and labels its result.
InputMismatchException
An InputMismatchException is a runtime exception from a Scanner token read when the token does not fit the requested type.
Typing "3.5" for a nextInt() call causes InputMismatchException because an integer is required.
int
The int type stores 32-bit signed whole numbers, ranging from −2,147,483,648 through 2,147,483,647.
A small inventory count fits in an int, but a count above its maximum needs a larger integer type.
Integer division
Integer division divides two integer operands and discards any fractional part of the quotient toward zero.
The Java expression 23 / 5 gives 4 complete groups, leaving the fraction out of the quotient.
Integer overflow
Integer overflow occurs when an integer calculation exceeds its type’s range and wraps around to a different value.
Multiplying two large int values can overflow before their product is assigned to a long variable.
Integer.parseInt
The Integer.parseInt method converts valid integer text into an int and rejects invalid text with NumberFormatException.
Integer.parseInt("72") returns 72, but adding a leading space makes that integer text invalid.
Intermediate value
An intermediate value is a result produced during a calculation before the final answer, useful for tracing where an error begins.
Printing the intermediate totalMinutes can show whether a wrong time split started before division.

J

JDK
The JDK, or Java Development Kit, is the software toolkit that supplies Java development tools, including javac and java.
A computer needs a JDK to compile the source from a terminal and then launch the resulting program.
JVM
The JVM, or Java Virtual Machine, is the runtime system that executes Java bytecode on a particular computer.
The same compatible class file can run on different operating systems that have suitable JVMs.

L

Literal
A literal is a value written directly in source code, with its form and suffix determining the type of that written value.
The literals 8, 8L, and 8.0 express similar quantities but have int, long, and double types.
Locale
A locale is a language-and-region setting that controls conventions such as the decimal separator in numeric input and formatting.
Setting a Scanner to Locale.US makes point-decimal input consistent across different computers.
Logic error
A logic error is a mistake that makes a program produce an incorrect result even though it compiles and completes execution.
Printing an average of 4.0 when the expected result is 4.75 reveals a logic error in the calculation.
long
The long type stores 64-bit signed whole numbers and is useful when an exact integer can exceed the range of int.
The suffix in 5_000_000_000L makes a literal that can initialize a large whole-number count.

M

Main method
The main method is the entry method where the Java launcher begins executing the instructions in a small program.
Placing two printing statements inside main makes their messages appear in the order written.
Math class
The Math class supplies ready-made static methods and constants for numeric work, including roots, powers, and rounding.
The call Math.sqrt(81) finds a square root without requiring an import or a method definition.

N

NaN
NaN, meaning "not a number," is a special floating-point result for an undefined numeric operation such as zero divided by zero.
The double calculation 0.0 / 0 produces NaN instead of throwing an integer-division exception.
Narrowing conversion
A narrowing conversion moves to a more restricted numeric representation, such as double to int, and can lose information.
Converting 6.75 to an int is narrowing because the destination cannot retain its fractional part.
nextLine
The nextLine method reads the remaining text on the current input line and consumes its ending without returning that ending.
After an integer token at a line’s end, nextLine() can return an empty String immediately.
NumberFormatException
A NumberFormatException is a runtime exception raised when numeric parsing cannot convert the supplied text to the requested type.
Trying to parse "eight" with Integer.parseInt causes NumberFormatException during execution.

O

Operand
An operand is a value or expression supplied to an operator; operand types help decide which operation Java performs.
In "N=" + count, the String operand makes plus join text instead of adding two numbers.
Operator precedence
Operator precedence is the priority that determines how operations group when an expression contains different operators.
Multiplication takes precedence over addition in 4 + 3 * 2, so the product is formed first.

P

Parsing
Parsing interprets text according to a format and converts it to a usable value, such as an int or a double.
Parsing the String "72" lets a program add 8 numerically instead of building the text "728".
Precision
Precision describes how much significant detail a numeric type can represent; a wide range does not guarantee exact values.
Converting a large int to float can reduce precision even though Java permits the widening conversion.
Primitive type
A primitive type is one of Java’s eight built-in value types: byte, short, int, long, float, double, char, or boolean.
A count stored as int uses a primitive type, while a name stored as String uses a class type.
print
The print method writes a value to the output without adding a line break, leaving the next output on the same line.
Using print("Name: ") lets a user type an answer directly beside the prompt on the screen.
printf
The printf method writes values according to a format string and adds a line break only if that string requests one.
Using printf("%d items%n", 8) prints the count, the word "items", and a final line separator.
println
The println method writes a value followed by a line break; with no argument, it writes only the line break.
Two successive println calls display two separate lines even when their literals contain no newlines.

R

Remainder
A remainder is the value left after integer division; Java’s % operator gives a nonzero result with the dividend’s sign.
With 23 parts packed in groups of 5, 23 % 5 gives the 3 parts outside the complete groups.
Rounding
Rounding replaces a value with a nearby value at a chosen precision; Math.round uses the nearest integer with ties upward.
Rounding a time to whole minutes can happen after calculating the duration as a double in minutes.
Runtime error
A runtime error is a failure during program execution, often reported as an exception that stops the running program.
Dividing by an integer variable holding zero produces a runtime error on the division statement.

S

Scanner
A Scanner is a Java class that reads input as lines or tokens and can convert tokens to primitive values such as numbers.
A Scanner connected to System.in can read a user’s name and the measurements needed by a program.
Scientific notation
Scientific notation displays a number as a coefficient multiplied by a power of ten, using E in Java’s printed values.
The printed value 1.0E-4 represents 0.0001, so the negative exponent describes a small magnitude.
Source code
Source code is the human-readable Java text saved in a .java file before the compiler translates it for execution.
Editing a message in the source code changes the next compiled program after you save and compile.
Statement
A statement is a Java instruction, such as an assignment or a method call; a printing statement ends with a semicolon.
The line System.out.println("Ready"); is one statement that prints a message and a line break.
String
A String is a Java class type for a sequence of text characters, including the valid empty sequence written as "".
A String can hold the label "Room 204" without treating its digits as a number for arithmetic.
String literal
A string literal is text written between double quotation marks in Java source, with escape sequences for special characters.
The string literal "Hello, team" includes a comma and a space that appear exactly in the output.
String.format
The String.format method applies a format string and returns the resulting text instead of printing it directly.
A program can store String.format(Locale.US, "%.1f km", 8.25) and print that text later.

T

Test case
A test case specifies inputs and an expected result so that a program’s actual behavior can be checked against a known answer.
The test case 120 km at 60 km/h expects 2 h 0 min from a travel-time conversion program.
Token
A token is a piece of input separated by a delimiter; a default Scanner uses whitespace to separate its tokens.
The input "4 7" contains two numeric tokens that two successive nextInt() calls can read.
Trace table
A trace table records variable values after successive statements so that changes can be followed without running the code.
A trace table for a swap shows which original value is preserved in the temporary variable.
Truncation
Truncation discards the fractional part toward zero when an in-range floating-point value is converted to an integer.
Casting -8.6 to int gives -8 through truncation, while rounding down would instead give -9.

V

Variable
A variable is named storage for a value of a particular type, allowing later statements to read or update the stored value.
The variable distanceKm stores a measurement that a later time calculation divides by speed.

W

Widening conversion
A widening conversion is an automatic numeric conversion along Java’s permitted type paths, such as int to long or double.
Assigning an int count to a double measurement converts it automatically, producing a decimal form.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started