- Learn
- Computer Science & IT
- Programming
- Object-Oriented Programming with Java
- First Java Programs
First Java Programs
BeginnerLesson 1 of 11 in Object-Oriented Programming with Java Course
What you will learn
- 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 methodRecognize 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 errorsTurn 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 printlnPrint text and values on the screen line by line, control where new lines begin, and use escape sequences for quotation marks, tabs and backslashes.
- Build a program around the main method
- Declare and update variables, choose a suitable primitive type for each value, and store and combine text in String values.
- Declare, assign and update variablesCreate 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 literalsPick 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 concatenationHold text in String variables and build output by joining strings, numbers and variables with the + operator, predicting exactly what will be printed.
- Declare, assign and update variables
- 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 precedenceCombine 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 remainderPredict 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 classCalculate 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.
- Write expressions with operators and precedence
- 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 explicitlyTell 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 numbersTurn 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.
- Widen values and cast them explicitly
- 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 ScannerCreate 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 printfPrint 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 outputPlan, write and test complete programs that read values, calculate with them using the right types, and print clear results.
- Read input with Scanner
First Java Programs study guide
1Write, 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
Hellobelongs inHello.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 problem | What happens | How to investigate |
|---|---|---|
| Compile-time error | The source cannot be successfully compiled. | Read the first compiler message and inspect the nearby code. |
| Runtime error | Execution stops with an exception. | Read the exception and locate the reported line. |
| Logic error | Execution 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.javacompiles source;java Helloruns 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 literal | Printed character |
|---|---|
\n | New line |
\t | Tab |
\" | 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
printstays on the current line;printlnadds a line break after its value.- Quotes make text literal:
"name"prints those letters, whilenameprints 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
charvalue. - An ordinary string literal opens and closes on one source line.
2Store 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 statement | first | second | temp |
|---|---|---|---|
int temp = first; | 4 | 9 | 4 |
first = second; | 9 | 9 | 4 |
second = temp; | 9 | 4 | 4 |
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.
finalprevents reassignment, andvarinfers 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
| Type | Storage and values |
|---|---|
byte | 8-bit integer: −128 to 127 |
short | 16-bit integer: −32,768 to 32,767 |
int | 32-bit integer: −2,147,483,648 to 2,147,483,647 |
long | 64-bit integer: −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 32-bit floating point; about 7 significant digits |
double | 64-bit floating point; about 15–17 significant digits |
char | One 16-bit UTF-16 code unit: 0 to 65,535 |
boolean | true 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;
Stringis a class. - Use a literal’s suffix to choose
long(L) orfloat(f). - Integer calculations can overflow silently; widen an operand before the calculation.
- Floating-point types store many decimal fractions approximately.
- A
charstores one UTF-16 code unit, while abooleanstores 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:
| Expression | Result | Reason |
|---|---|---|
"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
charvalues add numerically unless a String is already part of the operation.
3Calculate 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
| Order | Operators or grouping |
|---|---|
| First | Parentheses |
| Next | Unary 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
| Expression | Stored 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
doublebefore 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.
| Call | Result 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
| Call | Result |
|---|---|
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
doublekeeps fractional results but approximates many decimal fractions. Math.sqrt,Math.pow, andMath.PIsupport geometric calculations without an import.roundselects the nearest integer;floorandceilchoose a direction.Math.round(double)returnslong, whilefloorandceilreturndouble.- When scaling a rounded value back, use a decimal divisor to preserve its fraction.
4Convert 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;.
| Expression | What happens | Result |
|---|---|---|
(double) sum / count | Convert 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.parseIntandDouble.parseDoubleproduce numeric values for arithmetic.Double.parseDoubleuses a decimal point independently of locale.- Invalid numeric text causes
NumberFormatException; integer parsing rejects surrounding spaces. Boolean.parseBooleanaccepts "true" in any capitalization and returns false for other text.- Basic number-to-text conversion does not preserve extra trailing zeros.
5Read 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
| Method | What 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.Scannerbefore the class and create one Scanner insidemain. 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
%nfor a line break and%%for a literal percent sign. %.2frounds 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.formatreturns text, whileprintfprints 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
1Build and run a small message program
13 steps
- 1IntroductionFollow instructions from main
A Java program needs an entry point and a sequence of instructions. In the classic form, a class contains
main, andmaincontains 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.
- 2ExamplePlace 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. - 3TipCheck names before adding more code
Save the public class
NoticeinNotice.java. Match the capitalNexactly. Also preserveSystemand the lowercase method namemain: 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. - 4ChallengeRepair the entry method
A file correctly declares
public class Bulletin, but its only method ispublic static void Main(String[] args). It compiles and the launcher cannot find the main method. What change is needed?---reveal---
Change
Maintomain. The capitalized name declares a different method, so it does not supply the intended entry point. The file must also remain namedBulletin.javato match its public class. - 5ExplanationCompile and launch the notice
From the source folder, enter:
javac Notice.java java Noticejavacchecks the source and producesNotice.classbytecode.javastarts 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.classextension.java Notice.javais a separate source-file launch form available since Java 11. - 6ChallengeRead 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.
- 7ExampleTrace 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
printadds no line break, the second call places3immediately 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. - 8ExampleEnd 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 WelcomeThere is no blank line between the messages; an empty
println()would add one. - 9Key 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. - 10ChallengePredict 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. - 11ConnectionLocate 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.
- 12ChallengeSeparate 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
printtoprintln, 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. - 13RecapCheck structure, execution, and output
Use the class and
mainstructure 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:
printstays,printlnadvances. 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.
2Trace stored values and build a message
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrack values before predicting output
- 2ExampleCreate two independent stored values
- 3ExampleUpdate only the named destination
- 4ChallengePreserve a value during a swap
- 5TipUse final and var deliberately
- 6ExplanationChoose a type that matches the data
- 7ExampleLet literal spelling choose the type
- 8ChallengeWiden before multiplication
- 9ExampleBuild a message from the trace
- 10ChallengeDecide when plus means addition
- 11ChallengeCombine a copied value with new output
- 12RecapUse the latest value and the actual type
3Split a duration and calculate with fractions
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose the operation that fits the question
- 2ExplanationGroup a complete calculation
- 3ChallengeRepair an average expression
- 4ExampleCount complete hours
- 5ExampleKeep the seconds after those hours
- 6ExampleExtract minutes and seconds
- 7ChallengeSplit a different duration
- 8Key InsightTruncation moves toward zero
- 9ExampleKeep the fraction of a measurement
- 10ExplanationUse Math for a root or power
- 11ChallengeChoose the rounding rule
- 12TipScale back with a decimal divisor
- 13ChallengeKeep an average before rounding it
- 14RecapTrace type and grouping at each operation
4Convert values at the right point
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk what value reaches the conversion
- 2ExplanationWiden a numeric value automatically
- 3ExampleCompare two cast positions
- 4ChallengeConvert and round a negative value
- 5TipDo not treat a cast as a range check
- 6ExampleParse before adding
- 7ExplanationMatch the parser to the text
- 8ChallengePredict parsing results
- 9ConnectionPrepare text for display
- 10ChallengeFollow the whole conversion chain
- 11RecapChoose a conversion for its job
5Read, calculate, format, and test
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBuild a program around its data
- 2ExplanationConnect one Scanner to keyboard input
- 3ExampleRead a label as a whole line
- 4ExampleParse numeric lines consistently
- 5ChallengeFix a skipped label
- 6TipSet numeric input conventions explicitly
- 7ExampleCalculate with the intended types
- 8ExplanationMake the format string match the values
- 9ExamplePrint a rounded measurement
- 10ChallengeRepair the specifier
- 11ExampleStore or align formatted text
- 12ExplanationChoose tests before running
- 13ChallengeFind a calculation bug with a test
- 14TipTrace the first unexpected value
- 15ChallengeTransfer the plan to a rate
- 16RecapCheck the whole path from input to text
First Java Programs practice questions
Set 1: Choose types and connect input to output10 Practice Questions
Question 1 of 10
Show answerHide answer
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
4.0 for double average = 19 / 4;. What kind of error explains the inaccurate average?Show answerHide answer
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;
Show answerHide answer
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
Show answerHide answer
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
Show answerHide answer
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
Math.floor(-4.2) return?Show answerHide answer
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?Show answerHide answer
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
Show answerHide answer
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
System.out.printf("Mass: %.2f kg%n", 6.375); print before its line break?Show answerHide answer
.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
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?Show answerHide answer
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
int total = 19; int groups = 4;, what expression gives a fractional quotient?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;
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
4.25 a float literal in Java?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
System.out.println("Seats: " + 6 + 2); print?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
int result = 18 - 6 / 3 * 2;?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
-11 / 4?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
public class TrailLog. What must its source file be named?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?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");
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);
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
Path: C:\Work with exactly one backslash?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
System.out.println(3 + 4 + " / " + 3 * 4); print?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);
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
double value = Math.round(8.276 * 100) / 100;?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
(int) -6.8?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Integer.parseInt(" 58") is evaluated?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();
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
System.out.printf("[%4d][%-5s]", 7, "Oak");?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
int seconds = 7_489;. What pair of expressions gives the complete hours and the remaining whole minutes within the current hour?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);
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Math.sqrt(5 * 5 + 12 * 12) return?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
System.out.println("Ready")?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
var count = 6; when the same method executes count = 6.5;?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?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);
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Boolean.parseBoolean("Yes") return?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
minutes = totalSeconds / 60; seconds = totalSeconds;. What correction fixes the calculation?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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);
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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);
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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);
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
'C' back into the character 'E'?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);
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();
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
scanner is ready, and Locale is imported.Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Assignment
count = count + 2;, count holds two more than the value it held before that statement.B
Block
boolean
boolean isMember = true; stores a truth value without using quotes or a number.Bytecode
.class files and executed by a suitable Java Virtual Machine.java launcher can run through the JVM.C
Cast
(double) total / count, the cast changes an operand’s type before the division is performed.Ceiling
char
'7' has code 55, so storing it as char does not make it the integer value 7.Class
public class Greeting opens the class that holds the program’s main method.Comment
// or between /* and */.// Convert to minutes explains why a time calculation multiplies an hour value by 60.Compile-time error
Compiler
javac Notice.java invokes the compiler, which reports an error if a semicolon is missing.Compound assignment
total += 5; increases an int total by 5 and stores the updated value in total.Concatenation
"Count: " + 8 builds one message containing a label, a space, and a digit.Constant
final variable can receive a value once and cannot be reassigned afterward.MINUTES_PER_HOUR gives the number 60 a useful name in time conversion calculations.D
Declaration
int count; introduces a name, but count still needs a value before it is read.Decrement
-- operator performs this update without a separate subtraction assignment.secondsLeft--; reduces the stored number of remaining seconds by exactly one.Dividend
/ or % in a two-operand Java division expression.-11 % 4, the negative dividend explains why the nonzero remainder is negative too.double
Double.parseDouble
E
Empty string
"" + 'A' + 'B' makes the additions build text and gives the String "AB".Escape sequence
lets one printing call place the next part of its message on another line.Expected output
Expression
width * height computes an area that can be assigned or passed to a printing call.F
Field width
%4d produces three leading spaces before the digit to fill the four-character field.float
f suffix in 2.75f marks a float literal, while plain 2.75 is a double literal.Floating-point approximation
1.1 * 3 reveals floating-point approximation in the displayed result.Floor
Format specifier
%d for an integer or %n for a line break.%f consumes a floating-point value, while %n adds a line separator without consuming a value.Format string
"Mass: %.2f kg%n" places a two-decimal measurement between its label and unit.Formatting precision
%f, it sets the number of digits after the decimal separator.%.2f turns a displayed 4.5 into "4.50" without modifying the numeric variable.I
Increment
++ operator performs this update in a single statement.count++; changes a stored count of 8 to 9 before the following statement runs.Initialization
double speed = 72.5; declares speed and initializes it to a measurement in km/h.Input–calculation–output plan
InputMismatchException
nextInt() call causes InputMismatchException because an integer is required.int
int, but a count above its maximum needs a larger integer type.Integer division
23 / 5 gives 4 complete groups, leaving the fraction out of the quotient.Integer overflow
Integer.parseInt
Integer.parseInt("72") returns 72, but adding a leading space makes that integer text invalid.Intermediate value
J
JDK
javac and java.JVM
L
Literal
8, 8L, and 8.0 express similar quantities but have int, long, and double types.Locale
Locale.US makes point-decimal input consistent across different computers.Logic error
long
5_000_000_000L makes a literal that can initialize a large whole-number count.M
Main method
main makes their messages appear in the order written.Math class
Math.sqrt(81) finds a square root without requiring an import or a method definition.N
NaN
0.0 / 0 produces NaN instead of throwing an integer-division exception.Narrowing conversion
nextLine
nextLine() can return an empty String immediately.NumberFormatException
Integer.parseInt causes NumberFormatException during execution.O
Operand
"N=" + count, the String operand makes plus join text instead of adding two numbers.Operator precedence
4 + 3 * 2, so the product is formed first.P
Parsing
Precision
Primitive type
int uses a primitive type, while a name stored as String uses a class type.print("Name: ") lets a user type an answer directly beside the prompt on the screen.printf
printf("%d items%n", 8) prints the count, the word "items", and a final line separator.println
println calls display two separate lines even when their literals contain no newlines.R
Remainder
% operator gives a nonzero result with the dividend’s sign.23 % 5 gives the 3 parts outside the complete groups.Rounding
Runtime error
S
Scanner
System.in can read a user’s name and the measurements needed by a program.Scientific notation
E in Java’s printed values.1.0E-4 represents 0.0001, so the negative exponent describes a small magnitude.Source code
.java file before the compiler translates it for execution.Statement
System.out.println("Ready"); is one statement that prints a message and a line break.String
"".String literal
"Hello, team" includes a comma and a space that appear exactly in the output.String.format
String.format(Locale.US, "%.1f km", 8.25) and print that text later.T
Test case
Token
nextInt() calls can read.Trace table
Truncation
V
Variable
distanceKm stores a measurement that a later time calculation divides by speed.W
Widening conversion
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.