Java Tutorial
Java Output
System.out.println sends text to the console. print stays on the same line. This is how every first program talks back.
println writes a line
System.out.println prints its argument and then starts a new line. Strings use double quotes. Numbers print without quotes.
Example
public class Main {
public static void main(String[] args) {
System.out.println("Hello, Java");
System.out.println(2026);
}
}print stays on the line
print does not add a newline. Use it when several pieces should sit on one line, then finish with println.
Example
public class Main {
public static void main(String[] args) {
System.out.print("Ada");
System.out.print(" ");
System.out.println(2026);
}
}Concatenation
The + operator glues a string to a number or another string. Parentheses around an expression force the math to run before the join.
Example
public class Main {
public static void main(String[] args) {
int a = 7;
int b = 5;
System.out.println(a + " + " + b + " = " + (a + b));
}
}Run this in /java/try. Change 7 and compile again.
printf for decimals
System.out.printf formats numbers. %.2f means two digits after the point. %n is a newline.
Example
public class Main {
public static void main(String[] args) {
System.out.printf("pi is %.2f%n", 3.14159);
}
}println and print are different: print leaves the cursor on the same line. Forgetting the final println is why several pieces sometimes end up jammed together with no line break.
Try It Yourself
Exercise: Print exactly this line, computing the total yourself with concatenation: 3 coffees cost 10.5 (3 at 3.5 each).
Show solution
int cups = 3;
double each = 3.5;
System.out.println(cups + " coffees cost " + (cups * each));The parentheses around cups * each matter: without them, Java joins left to right and you get text, not the product.
Key Takeaways
printlnprints and moves to a new line;printstays on the line.+joins strings and numbers — parenthesize math so it runs before the join.printfformats numbers:%.2ffor two decimals,%nfor a newline.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Physics
Print a voltmeter reading
A digital meter shows a number and a unit. println concatenates both so the line stays readable.
Example
public class Main {
public static void main(String[] args) {
System.out.println("V = " + 4.92 + " V");
}
}