Java Strings, Input/Output, and Type Casting – CSE, ASU – Study Notes
offline

Source: Final Exam Notes, Computer Science and Engineering, Arizona State University

Difficulty: Beginner | Prerequisites: Java Data Types, Variables, and Operators notes.

Big Picture

Once you can store numbers and booleans, the next step is handling text and getting input from users. Strings in Java are objects, not primitives, and they come with a rich set of built-in methods for searching, slicing, and comparing. The Scanner class is how your programs read keyboard input. Type casting lets you convert between types when Java will not do it automatically. These topics come up constantly in assignments and exams because they sit at the intersection of data types, objects, and basic I/O.

TL;DR

Java Strings are objects with methods like indexOf(), substring(), length(), charAt(), and equals(). User input is read via the Scanner class, which has type-specific methods. Type casting converts between types, either automatically (widening) or explicitly (narrowing), and random number generation uses java.util.Random.


Key Terms

String

A Java object (not a primitive) that represents a sequence of characters. Declared with a capital S: String name = "Bob Smith";. Strings are immutable, meaning once created, their content cannot be changed.

Think of it as a read-only sequence of characters that comes with built-in tools for searching and slicing.

indexOf()

A String method that returns the position (index) of the first occurrence of a character or substring. Returns -1 if the target is not found. Indices start at 0.

In simple terms, it answers "where does this character or word first appear?"

substring(a, b)

A String method that returns a new string starting at index a and ending before index b. If only one argument is given, it returns from that index to the end.

Think of it as a pair of scissors: you tell it where to start cutting and where to stop.

length()

A String method that returns the number of characters in the string, including spaces.

In simple terms, it counts every character in the string.

charAt(index)

A String method that returns the single character at the specified index position.

Think of it as pointing at a specific position in the string and asking "what letter is here?"

equals()

A String method that compares two strings for exact content equality, including case. Returns true or false. Do not use == to compare strings.

In simple terms, it checks whether two strings contain exactly the same characters.

Scanner

A class in java.util that reads input from various sources, most commonly the keyboard (System.in). You create one with Scanner scnr = new Scanner(System.in); and then call type-specific methods like nextInt(), nextDouble(), or next().

Think of it as the bridge between the user's keyboard and your program's variables.

parseFloat() / parseInt()

Static methods that convert a String representation of a number into its numeric type. Float.parseFloat("123") returns the float value 123.

In simple terms, they turn text that looks like a number into an actual number.

Random (java.util.Random)

A class that generates pseudo-random numbers. randGen.nextInt(n) returns a random integer from 0 (inclusive) to n (exclusive). The number of possible values equals n.

Think of it as a digital dice roller where you choose how many sides the die has.


Core Content

String Basics

Strings are declared with double quotes: String name1 = "Bob Smith";

Java Strings start indexing at 0. For "Harry", the indices are: H=0, a=1, r=2, r=3, y=4.

String is not a primitive type. It starts with a capital letter, which in Java signals a class/object type.

Key String Methods

  • indexOf(): name.indexOf("b") returns the index of the first occurrence of "b". Returns -1 if not found.

    • name.indexOf("b s") returns the index where the substring "b s" begins (index 2 for "Bob Smith")

  • length(): name.length() returns the number of characters. For "Bob Smith", this returns 9 (the space counts).

  • charAt(): greeting.charAt(4) returns the character at index 4.

  • substring(a, b): Returns characters from index a up to but not including index b.

    • name.substring(2, 6) on "Bob Smith" returns a portion starting at index 2

    • name.substring(0, 3) returns "Bob"

    • name.substring(3, 0) returns nothing useful (throws an exception if a > b)

  • equals(): Name1.equals(Name2) compares content. "Bob Smith".equals("bob smith") returns false because case matters.

Reading User Input with Scanner

To read input, import and create a Scanner:

  • import java.util.Scanner;

  • Scanner scnr = new Scanner(System.in);

  • Read a double: double squareSide = scnr.nextDouble();

  • Read an int: int age = in.nextInt();

The variable name for the Scanner can be anything (scnr, in, scanner), but it must be created with new Scanner(System.in) to read from the keyboard.

Primitive Types vs Reference Types

Java's type hierarchy (from broadest to narrowest for numeric types):

  1. boolean/bool

  1. double

  1. int

  1. float

  1. char

  1. long, short, byte

String is a reference type, not a primitive. You can identify primitive types by expression, by literal value, by name, or by data type.

Arrays of primitives are reference types: boolean[] a = new boolean[33]; declares an array of booleans.

A boolean a = false; declares a single boolean variable.

Type Casting

  • Widening cast (automatic): Converting a smaller type to a larger type, e.g. int to double. Java does this automatically.

  • Narrowing cast (explicit): Converting a larger type to a smaller type, e.g. float to int. Requires explicit syntax.

    • Float.parseFloat("123") converts the string "123" to the float value 123

    • 3f + 5 evaluates as float (the f suffix makes the literal a float, and 5 is widened to float)

    • 7.0/3f evaluates as double (7.0 is a double literal, so the float is widened to double)

Character literals use single quotes: char c = 'm';

Random Number Generation

  • Import: import java.util.Random;

  • Create: Random randGen = new Random();

  • randGen.nextInt() returns a random integer across the full int range (-2^31 to 2^31 - 1)

  • randGen.nextInt(8) returns a random integer from 0 to 7 (8 possible values)

  • How many values exist in the range 10 to 15? Answer: 6 (calculated as 15 - 10 + 1)

  • Random number from 16 to 25: randGen.nextInt(10) + 16

Brief History of C, C++, and Java

  • First C book published: 1978

  • First C++ book published: 1985

  • First public release of Java: 1995


Formulas and Key Syntax

  • String declaration: String varName = "text";

  • Index access: str.charAt(index) (0-based)

  • Substring: str.substring(startIndex, endIndex) (endIndex is exclusive)

  • Comparison: str1.equals(str2) (not ==)

  • Scanner creation: Scanner scnr = new Scanner(System.in);

  • Random range formula: randGen.nextInt(range) + min where range = max - min + 1

  • Range count: number of values from a to b inclusive = b - a + 1


Real-World Applications

String manipulation is the backbone of text processing, from parsing user input in web forms to searching through log files. The Scanner pattern (read input, validate, process) mirrors how real applications handle user interaction. Random number generation powers everything from games to cryptography to statistical simulations, though java.util.Random is not suitable for security-sensitive applications.


Common Misconceptions

  • Students use == to compare Strings. This compares object references (memory addresses), not content. Always use .equals() for String comparison.

  • Students forget that substring(a, b) excludes the character at index b. If you want characters at indices 0, 1, and 2, you call substring(0, 3).

  • Students assume length is a property (no parentheses). In Java, it is a method on Strings: str.length() with parentheses. (For arrays, length is a field without parentheses, which adds to the confusion.)

  • Students think nextInt(8) can return 8. It cannot. The upper bound is exclusive: nextInt(8) returns values 0 through 7.


Why It Matters / Exam Flags

  • ⚠️ String comparison with .equals() vs == is one of the most commonly tested Java concepts at any level.

  • ⚠️ Expect questions that ask you to trace through indexOf(), substring(), and charAt() calls with specific strings.

  • ⚠️ Random number range calculations ("generate a number between X and Y") appear regularly. Know the formula: nextInt(max - min + 1) + min.

  • ⚠️ Know the difference between widening and narrowing casts, and which direction is automatic.

  • ⚠️ Scanner method matching: be ready to identify which method (nextInt, nextDouble, next, nextLine) matches which data type.


Quick Self-Test

  1. True or false: "hello" == "hello" is a reliable way to compare Strings in Java. (False, use .equals().)

  1. Fill in the blank: "Bob Smith".length() returns ___. (9.)

  1. True or false: randGen.nextInt(5) can return the value 5. (False, it returns 0 through 4.)

  1. Fill in the blank: "Harry".charAt(0) returns ___. ('H'.)

  1. True or false: Converting an int to a double is an example of a narrowing cast. (False, it is a widening cast.)


Practice Q&A

Q: What does name.indexOf("b") return if name is "Bob Smith"?

A: It returns the index of the first lowercase "b". In "Bob Smith", there is no lowercase "b" (the B is uppercase), so it returns -1. indexOf is case-sensitive.

Q: What does name.substring(0, 3) return if name is "Bob Smith"?

A: "Bob" (characters at indices 0, 1, and 2; index 3 is excluded).

Q: Write the code to create a Scanner that reads from the keyboard.

A: Scanner scnr = new Scanner(System.in);

Q: How many values exist in the range 10 to 15 (inclusive)?

A: 6 (calculated as 15 - 10 + 1).

Q: Write code to generate a random number from 16 to 25.

A: randGen.nextInt(10) + 16 (10 possible values: 25 - 16 + 1 = 10, offset by 16).

Q: What is the result of Float.parseFloat("123")?

A: The float value 123.0.

Q: Does "Bob Smith".equals("bob smith") return true or false?

A: False. The equals() method is case-sensitive.


Connections to Other Topics

String methods connect directly to control flow, because you will often use indexOf() results in if-else conditions and loop through characters with charAt() and length(). Scanner input connects to exception handling, since invalid input (entering text when the program expects an integer) throws an InputMismatchException. Random number generation connects to arrays and loops when you need to fill collections with test data or simulate repeated trials.


Related Terms / Search Tags

Java String, String methods, indexOf, substring, length, charAt, equals, String comparison, == vs equals, Scanner, nextInt, nextDouble, nextLine, System.in, user input, java.util.Scanner, type casting, widening cast, narrowing cast, parseFloat, parseInt, Random, nextInt, java.util.Random, random number range, primitive vs reference type, boolean array, char literal, immutable String, ASU CSE, introductory Java