logotransparent.png

Legion of Learners

www.lol-101.com

  • Home

  • Classrooms

  • Courses

  • About Us

    • Executive Team
    • Board Members
  • Resources

  • More

    Use tab to navigate through the menu items.
    To see this working, head to your live site.
    • Categories
    • All Posts
    • My Posts
    sfolax6776
    Feb 13, 2020
      ·  Edited: Feb 14, 2020

    3.4 What happens if we mix strings, chars and numbers?

    in Introduction to Java

    A. Introduction

    We have learned what will happen if we mix int, float and double: the "lower" types such as int or float will be promoted to "higher" types such as double. We also learned we can add or subtract char types just like int. So what will happen if mix strings with characters and numbers?

    B. Case by case, you will see:

    1. aString + anotherString = aNewString - concatenation. e.g. "ABC"+"abc" = "ABCabc";

    2. aString-anotherString - does not compile, "-" is not defined for strings

    3. aString + aCharacter = aNewString - concatenation. e.g. "ABC"+'a'="ABCa"

    4. aString+aNumber=aNewString - concatenation. e.g. ""+12 = "12"

    5. aString - aNumber - does not compile

    6. aString -aCharacter - does not compile

    7. If you mix more than one type, please keep in mind the order of operations:

    System.out.println(10+5+4+""); // prints 19 as a string
    System.out.println(""+10+5+4); // prints 1054 as a string
    System.out.println(""+(10+5)+4); // prints 154 as a string
    System.out.println(""+(10+5)+'a'); // prints 15a as a string
    System.out.println((10+5)+""+'a'); // prints 15a as a string
    System.out.println((10+5)+'a'+"bc"); // prints 112bc as a string
    System.out.println((10+5)+'a'); // prints 112

    C. Try:

    This Kahoot! game for strings

    0 comments
    0
    0 comments

    Questions? Email us at legionoflearners@gmail.com or join our WeChat group!

    • lol-101dotcom

    ©2020 Legion of Learners