I/O, Formatting, Methods, and Math, CSE 101 – Study Notes
offline

Source: CSE 101 Final Exam Review, Arizona State University

Tags: Java Scanner, System.out.printf, printf format specifiers, escape sequences, Java methods, method stubs, Math class, Random class, String methods, CSE 101 ASU

Difficulty: Beginner | Prerequisites: Data Types, Variables, and Identifiers (CSE 101 Study Notes Part 1).

Big Picture

Once you know what types of data Java can hold, you need to get data in and push data out. The Scanner class reads user input; System.out.print, println, and printf write output with varying levels of formatting control. From there, you start organising your logic into methods (reusable blocks of code with parameters and return values), and using Java's built-in Math and Random classes for calculations. This material covers the plumbing of nearly every CSE 101 programme, so if any of it is shaky, everything built on top wobbles.

TL;DR

Scanner reads input (nextInt(), nextDouble(), nextLine()); System.out.printf() gives you precise control over output formatting with format specifiers like %d, %f, and %s. Methods let you package reusable logic with defined parameters and return types. Math provides constants (Math.PI) and functions (sqrt, pow, max, min, ceil), while Random generates pseudo-random numbers within a range.


Key Terms

Scanner

A class in java.util that reads input from the keyboard (System.in) or other sources. Created with: Scanner scnr = new Scanner(System.in);. Provides methods like nextInt(), nextDouble(), next(), and nextLine(). Think of it as the programme's ears: it listens for whatever the user types.

Format specifier

A placeholder inside a printf() format string that tells Java what type of value to insert and how to display it. Begins with % and ends with a conversion character: %d (int), %f (float/double), %s (String), %c (char), %e (scientific notation). In simple terms, it is a slot in your output template that gets filled with a value.

Escape sequence

A backslash followed by a character, representing a special character that cannot be typed directly. Common ones: \n (newline), \t (tab), \\ (backslash), " (double quote). Think of it as a secret code: the backslash tells Java "the next character is special, not literal."

Method

A named block of code that performs a specific task, optionally takes parameters, and optionally returns a value. Declared with: public static returnType methodName(parameterList) { body }. In simple terms, a method is a recipe you write once and use whenever you need it.

Method stub

A placeholder method that has the correct signature but contains only a print statement and a dummy return value. Used during development to let code compile before all logic is written. Think of it as a "coming soon" sign on a shop front.

Math class

A built-in Java class providing mathematical constants (Math.PI) and functions (Math.sqrt(), Math.pow(), Math.max(), Math.min(), Math.ceil()). All methods are static, so you call them on the class itself, not on an object. In simple terms, it is Java's built-in calculator.

Random class

A class in java.util that generates pseudo-random numbers. Created with: Random randGen = new Random();. The method nextInt(n) returns a random integer from 0 (inclusive) to n (exclusive). Think of it as a digital dice roller.


Core Content: Scanner Input Methods

To read user input, create a Scanner object:

Scanner scnr = new Scanner(System.in);
  • scnr.nextInt() reads the next integer from input

  • scnr.nextDouble() reads the next double

  • scnr.next() reads the next token (word, up to whitespace)

  • scnr.nextLine() reads the entire remaining line, including spaces

Example from the notes:

int seedVal = scnr.nextInt();
double side = scnr.nextDouble();
int yarns = scnr.nextInt();
String userState = scnr.nextLine();  // reads the rest of the line

Common pattern for reading multiple values:

String str1 = scnr.next();
String str2 = scnr.next();
String str3 = scnr.next();
String str4 = scnr.next();

Note: calling nextLine() after nextInt() or nextDouble() can cause problems because the newline character left in the buffer gets consumed immediately. The typical fix is to add an extra scnr.nextLine() call to clear the buffer.

Core Content: Output with print, println, and printf

  • System.out.print() outputs text without a newline at the end

  • System.out.println() outputs text followed by a newline

  • System.out.printf() outputs formatted text using format specifiers

printf Format Specifiers

The general form is: %[flags][width][.precision]conversion

  • %d integer

  • %f floating-point (default 6 decimal places)

  • %e scientific notation (e.g. 3.141248e+01)

  • %s string

  • %c character

Width and Precision

The width sets the minimum number of characters in the output. The precision sets the number of decimal places for floating-point.

Examples from the notes:

myInt = 853;
System.out.printf("%.2d\n", myInt);    // output: 853
System.out.printf("%.5d\n", myInt);    // output: --853 (padded)

myDouble = 31.4124;
System.out.printf("%e\n", myDouble);   // output: 3.141248e+01

myInt = 674;
myDouble = 85.62;
System.out.printf("%05d\n", myInt);    // output: 00674
System.out.printf("%.06.2f\n", myDouble); // output: 085.62

Flags

  • 0 pads with zeros instead of spaces: %05d

  • + shows the sign for positive and negative: %+06d

  • - left-aligns within the width: %-7.3f

String Formatting with printf

name = "Harry";
System.out.printf("%-8s|\n", name);  // output: Harry---|  (left-aligned, 8 chars)

Combined Output Example

Printing a tip calculation:

tip30 = amount * 0.3;
System.out.printf("Total with 30%% tip ($%.2f) is $%.2f\n", tip30, tip30 + amount);

Note: use %% to print a literal percent sign in printf.

Formatted Output Pattern: Metrics Conversion

int foot = (int)(meter * 3.28);
double inches = (meter * 39.37) - (foot * 12);
System.out.printf("%.2f meters in feet & inches is: %d' %.2f\"\n", meter, foot, inches);

Core Content: Escape Sequences

Escape sequences represent special characters inside strings.

  • \t tab character

  • \\ literal backslash

  • \' single quote (needed inside char literals)

  • \" double quote (needed inside strings)

  • \n newline

  • %% literal percent sign (inside printf only)

Note: for char data, single quotes are required: char letter = 'A';. For String data, double quotes are required: String word = "Hello";.

Core Content: String Manipulation Methods

Strings in Java are objects with useful built-in methods.

  • indexOf(String str) returns the index of the first occurrence of str, or -1 if not found

  • indexOf(String str, int fromIndex) searches starting from fromIndex

  • lastIndexOf(String str) returns the index of the last occurrence

  • substring(int start, int end) returns characters from index start up to (but not including) end

  • substring(int start) returns characters from start to the end of the string

Example from the notes, parsing a course info string like "CSE 110 11276 Eng":

int firstSpace = courseInfo.indexOf(" ");
int secondSpace = courseInfo.indexOf(" ", firstSpace + 1);
int thirdSpace = courseInfo.lastIndexOf(" ");

String subject = courseInfo.substring(0, firstSpace);           // "CSE"
int courseNum = Integer.parseInt(
    courseInfo.substring(firstSpace + 1, secondSpace));          // 110

This pattern of finding delimiter positions and then extracting substrings is a common exam exercise. Integer.parseInt() converts a numeric string to an int.

Core Content: Methods, Parameters, and Return Types

A method is a reusable block of code with a defined signature.

Method Signature

public static returnType methodName(parameterType paramName, ...) {
    // body
}
  • public static access and scope modifiers (for now, always use these in CSE 101)

  • returnType what the method sends back: int, double, String, void (nothing)

  • parameters the inputs the method requires, each with a type and name

Examples from the Notes

A void method (returns nothing, just prints):

public static void printFeetInchShort(int numFeet, int numInches) {
    System.out.println(numFeet + "'" + numInches + "\" shorthand");
}

A method that returns a value:

public static double calculateBaseArea(double length, double width) {
    return length * width;
}

Method Stubs

A stub is a placeholder that compiles but does not contain real logic. Useful during development.

public static int getUserNum() {
    System.out.println("FIXME: Finish getUserNum()");
    return -1;
}

public static int computeAverage(int num1, int num2) {
    System.out.println("FIXME: Finish computeAvg()");
    return -1;
}

The stub prints a "FIXME" message so you remember to finish it, and returns a dummy value (-1) so the code compiles.

Calling Methods

You call a method by its name with the required arguments:

printAirportDetails(str1, str3);
printAirportDetails(str2, str4);

Arguments must match the parameter types in order.

Core Content: Math Class and Random Number Generation

Math Class

The Math class is part of java.lang (no import needed). All methods are static.

  • Math.PI the constant pi (3.14159...)

  • Math.sqrt(x) square root of x

  • Math.pow(base, exponent) base raised to the power of exponent, returns double

  • Math.max(a, b) the larger of a and b

  • Math.min(a, b) the smaller of a and b

  • Math.ceil(x) rounds x up to the nearest whole number, returns double

Distance formula example from the notes:

pointsDistance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));

Random Number Generation

Requires: import java.util.Random;

Random randGen = new Random();
  • randGen.nextInt(n) returns a random integer from 0 to n-1 (inclusive)

  • To get a range from min to max (inclusive): randGen.nextInt(max - min + 1) + min

Examples from the notes:

  • Random integer between 0 and 6 (inclusive): randGen.nextInt(7)

  • Random integer between 7 and 21 (inclusive): randGen.nextInt(15) + 7

    • Because: nextInt(21 - 7 + 1) + 7 = nextInt(15) + 7

Seeded Random

Using setSeed() produces repeatable random sequences, useful for testing:

randGen.setSeed(seedVal);
bowl1 = randGen.nextInt(maxVal - minVal + 1) + minVal;
bowl2 = randGen.nextInt(maxVal - minVal + 1) + minVal;

Change-Making Algorithm

A classic pattern using integer division and modulo:

totalPennies = scnr.nextInt();
numQuarters = totalPennies / 25;
numNickels = (totalPennies % 25) / 5;
numPennies = totalPennies - (numQuarters * 25) - (numNickels * 5);

This decomposes a total into the fewest coins by working from largest denomination to smallest.


Common Misconceptions

  • Students often think printf() automatically adds a newline. It does not. You must include \n in the format string yourself.

  • Students often confuse %d and %f. %d is strictly for integers; %f is for floating-point. Using %d with a double causes a runtime error.

  • Students often forget that nextInt(n) returns values from 0 to n-1, not 1 to n. To get 1 to 6 (like a die), use nextInt(6) + 1.

  • Students often think methods need to return a value. A void method returns nothing and simply performs an action (like printing).

  • Students often call nextLine() right after nextInt() and wonder why it reads an empty string. The leftover newline in the buffer is the culprit.


Why It Matters / Exam Flags

  • ⚠️ printf format specifiers are a guaranteed exam topic. Be able to predict the exact output of a printf call, including width, precision, and padding.

  • ⚠️ The Random range formula (nextInt(max - min + 1) + min) appears frequently. Know it cold.

  • ⚠️ Method signatures: expect questions asking you to write a method header from a description (return type, name, parameters).

  • ⚠️ String parsing with indexOf() and substring() is a common practical exam question. Practice extracting parts of a formatted string.

  • ⚠️ The change-making algorithm (decomposing a value with / and %) is a classic exam coding exercise.

  • ⚠️ Know the difference between print, println, and printf, and when to use each.


Quick Self-Test

  1. True or False: System.out.printf("Hello") adds a newline at the end.

  1. Fill in the blank: To generate a random integer between 10 and 20 inclusive, write randGen.nextInt(______) + ______.

  1. True or False: A method with return type void can still use the return keyword (with no value) to exit early.

  1. Fill in the blank: The format specifier for displaying a double with exactly 2 decimal places is ______.

  1. True or False: Math.pow(2, 3) returns an int.


Practice Q&A

Q: What is the output of System.out.printf("%05d\n", 674);?

A: 00674. The 0 flag pads with zeros, and 5 sets the minimum width.

Q: Write a method header for a method called printAirportDetails that takes two String parameters (code and city) and returns nothing.

A: public static void printAirportDetails(String code, String city)

Q: Given totalPennies = 87, what are the values of numQuarters, numNickels, and numPennies using the change-making algorithm?

A: numQuarters = 87 / 25 = 3. Remaining: 87 % 25 = 12. numNickels = 12 / 5 = 2. numPennies = 12 - (2 * 5) = 2. So: 3 quarters, 2 nickels, 2 pennies.

Q: How do you generate a random integer between 7 and 21 (inclusive) using the Random class?

A: randGen.nextInt(15) + 7. The range has 15 values (21 - 7 + 1 = 15), and adding 7 shifts the floor from 0 to 7.

Q: What does the following code print?

String s = "CSE 110 11276 Eng";
int i = s.indexOf(" ");
System.out.println(s.substring(0, i));

A: CSE. indexOf(" ") returns 3 (the position of the first space), and substring(0, 3) returns characters at indices 0, 1, 2.

Q: What is the value of Math.sqrt(Math.pow(3, 2) + Math.pow(4, 2))?

A: 5.0. Math.pow(3,2) = 9, Math.pow(4,2) = 16, 9 + 16 = 25, Math.sqrt(25) = 5.0. This is the Pythagorean theorem: a 3-4-5 right triangle.


Connections to Other Topics

This connects to Data Types and Variables (Part 1 notes), since every Scanner method returns a specific type and every method parameter has a declared type. Methods are the foundation for object-oriented programming later in the course, where you will write methods inside classes and work with instance variables. The Math and Random classes foreshadow how Java's standard library works, and the same pattern (import a class, create an object or call static methods) reappears with ArrayList, Arrays, and File I/O.


Related Terms / Search Tags

Java Scanner, System.out.printf, printf format specifiers, %d %f %s %c %e, printf width precision flags, escape sequences Java, newline tab backslash, Java methods, method signature, void method, return type, method stubs, FIXME placeholder, Math.sqrt, Math.pow, Math.max, Math.min, Math.ceil, Math.PI, Random class Java, nextInt range, seeded random, setSeed, String indexOf, substring, Integer.parseInt, change-making algorithm, coin change problem, CSE 101 ASU, Java fundamentals, intro to programming