Results 1 to 3 of 3

Thread: Learning Java

  1. #1
    dn54321 is offline Member
    Join Date
    Jul 2014
    Posts
    2
    Rep Power
    0

    Default Learning Java

    Hey Guys, I just recently started coding java and i have a problem.... So I was doing an exercise on LearnJavaOnline. The exercise was: Create all the the primitives with different values. Concatenate them into a string and print it to the screen so it will print: H3110 w0r1d 2.0 true

    I attempted it and this is what i wrote

    public static void main(String[] args) {
    char H = 'h';
    byte e = 3;
    short l = 1;
    int L = 1;
    long o = 0;

    char w = 'w';
    float O = 0;
    char r = 'r';
    int one = 1;
    char d = 'd';

    double two = 2.0;
    boolean hi = true;
    String HelloWorld = H+e+l+L+o+" "+w+0+r+one+d+" "+two+" "+hi;
    System.out.println(HelloWorld);
    }

    However it prints "109 w0r1d 2.0 true"
    But when i add 2 speech marks: String HelloWorld = H+""+e+l+L+o+" "+w+0+r+one+d+" "+two+" "+hi;
    It works perfectly, why is that? i'm dumb :C

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Learning Java

    The + operator is used two ways:
    math sum: 1+2 = 3
    String concatenation.: "1" + "2" = "12"

    The compiler looks at the operands on either side of the + to decide which operation to do.
    If the two operands can converted to an int, then they are summed.
    If there is a String, then the operands are concatenated.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    coolman50544 is offline Member
    Join Date
    Apr 2014
    Location
    Miami, FL
    Posts
    47
    Rep Power
    0

    Default Re: Learning Java

    Don't forget their are other methods like the append() method for the string class. You can also use a StringBuilder object if you'd like. For more information just look at the API or some tutorials. Happy Coding

Similar Threads

  1. Java Learning
    By JTUS in forum New To Java
    Replies: 2
    Last Post: 12-12-2011, 12:30 AM
  2. Replies: 12
    Last Post: 06-14-2011, 04:55 PM
  3. Learning Java...
    By Learning Java in forum New To Java
    Replies: 2
    Last Post: 09-24-2010, 09:03 PM
  4. Pls Help me in learning Java
    By SimranK in forum New To Java
    Replies: 6
    Last Post: 06-24-2010, 07:44 PM
  5. Learning Java
    By jjoshua2 in forum New To Java
    Replies: 2
    Last Post: 12-20-2008, 02:46 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •