Java Numbers and Strings

In Java, you can combine strings and numbers in various ways. When you use the + operator with a string and a number, the number is converted to a string.

Key Topics

1. Concatenating Numbers and Strings

When concatenating a string with a number, the number is implicitly converted to a string.

public class NumbersAndStrings {
    public static void main(String[] args) {
        int age = 30;
        String message = "I am " + age + " years old.";
        System.out.println(message);
    }
}

2. String Formatting

You can format strings using String.format() or System.out.printf().

public class StringFormatting {
    public static void main(String[] args) {
        double price = 9.99;
        String product = "Coffee";
        String formattedString = String.format("The price of %s is $%.2f", product, price);
        System.out.println(formattedString);
    }
}

3. Converting Strings to Numbers

To perform arithmetic operations on numbers represented as strings, you need to convert them to numeric types.

public class StringToNumber {
    public static void main(String[] args) {
        String strNumber = "100";
        int number = Integer.parseInt(strNumber);
        System.out.println(number + 50); // Outputs: 150
    }
}

Key Takeaways

  • When concatenating strings and numbers, numbers are converted to strings.
  • Use string formatting methods for more complex or formatted output.
  • Convert strings to numbers using parsing methods when you need to perform calculations.