Why bother with Math and Scanner?
Imagine you’re building a simple calculator or a quiz that asks the user for answers. Without the right tools, you’d be writing a lot of extra code. Java’s library classes—Math and Scanner—are those handy tools. They save time and make your program neat.
💡 In Simple Words: The Math class is like a built‑in calculator that can do square roots, powers, rounding, and more. The Scanner class is like a friendly cashier who reads whatever you type on the keyboard and hands it to your program.
What is the Math class in Java?
The Math class lives in the java.lang package, which means you don’t even need to import it. It’s a collection of static methods—think of static as “you can call them directly without creating an object”. Each method does a specific mathematical job.
Common Math methods you’ll use
- Math.sqrt(double a) – returns the square root of a. If you give it 9, you get 3.
- Math.pow(double base, double exp) – raises base to the power of exp. Example:
Math.pow(2,3)gives 8. - Math.abs(int a) – absolute value; turns negative numbers positive.
- Math.max(int a, int b) – the larger of two numbers.
- Math.min(int a, int b) – the smaller of two numbers.
- Math.round(double a) – rounds to the nearest whole number.
All these methods return a value, so you can store the result in a variable or use it straight away.
Worked example: Simple grade calculator
int marks = 78;
int max = 100;
double percentage = (marks * 100.0) / max;
double rounded = Math.round(percentage);
System.out.println("Your percentage is " + rounded + "%");
Here Math.round turns 78.0 into 78, making the output look tidy.
How does the Scanner class work?
The Scanner class belongs to the java.util package, so you have to import it at the top of your file:
import java.util.Scanner;Think of a scanner as a device that “scans” whatever you type on the keyboard and converts it into a data type you ask for—like int, double, or String. You create a Scanner object that reads from System.in (the standard input stream).
Key Scanner methods
- nextInt() – reads the next integer.
- nextDouble() – reads the next floating‑point number.
- nextLine() – reads the whole line of text, including spaces.
- next() – reads the next word (stops at a space).
Don’t forget to close the scanner when you’re done; it frees the underlying resources.
Worked example: Temperature converter
import java.util.Scanner;
public class TempConvert {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double c = sc.nextDouble();
double f = (c * 9/5) + 32; // formula for Celsius to Fahrenheit
System.out.println(c + "°C = " + Math.round(f) + "°F");
sc.close();
}
}
We used nextDouble() to read a decimal number and Math.round to make the Fahrenheit value look neat.
Math vs. Scanner: Quick comparison
| Aspect | Math class | Scanner class |
|---|---|---|
| Package | java.lang (auto‑imported) | java.util (needs import) |
| Purpose | Perform mathematical operations | Read user input from keyboard |
| Typical use | Math.sqrt(25) | new Scanner(System.in).nextInt() |
| Object needed? | No (static methods) | Yes (create Scanner object) |
Tips to avoid common mistakes
- Don’t forget the import line for Scanner; otherwise the compiler will complain.
- When using
nextInt()followed bynextLine(), add an extranextLine()to consume the leftover newline character. - Math methods always return a value; you can’t call them without assigning or using the result.
- Use
Math.powfor exponentiation instead of writing your own loops—it’s faster and less error‑prone.
📝 Likely Exam Questions
- Write a Java program to read two integers and print their maximum using the Math class.
import java.util.Scanner; public class MaxDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println("Maximum = " + Math.max(a,b)); sc.close(); } } - Explain what Math.round(4.6) returns and why.
It returns 5 becauseMath.roundrounds to the nearest whole number; 4.6 is closer to 5 than to 4. - Describe how you would read a full name (first and last) from the user.
Create a Scanner object and callnextLine()once. This method captures the entire line, including spaces, so both first and last names are stored in a single String. - Given a radius r, write a one‑line expression using Math class to calculate the area of a circle.
double area = Math.PI * Math.pow(r, 2);(Math.PIis the constant 3.14159…) - What will happen if you forget to close a Scanner object?
The underlying input stream stays open, which can lead to resource leaks. In small programs it may not crash, but it’s good practice to callsc.close()when you’re done.