Question

Apologies, as I'm sure this is a stupid question, but...

Please could anyone explain to me why this:

public class java {
public static void main(String[] args) {
    byte zero = 0;
    short one = 1;
    int three = 3;
    long one2 = 1;
    float onepointnought = 1.0f;
    double onedotnone = 1.0;
    char letterh = 'H';
            char letterw = 'w';
            char letterr = 'r';
    char letterd = 'd';
            boolean bool = true;
    String output = letterh + three + one + one2 + zero + " " + letterw + zero + letterr + one + letterd + " " + (onepointnought+onedotnone) + " " + bool;
    System.out.println(output);
} }

Is outputting:

77 w0r1d 2.0 true

I'm expecting it to say "H3ll0 w0r1d 2.0 true"

It's from the interactive online java tutorials over at http://www.learnjavaonline.org/

Thanks!

Neil.

Was it helpful?

Solution

In this sentence

String output = letterh + three + one + one2 + zero + " " + letterw + zero + letterr + one + letterd + " " + (onepointnought+onedotnone) + " " + bool;

the letterh contains 'H' whose ASCII value is 72 & the addition of three + one + one2 + zero is 5 because these are non-string variables, so it is displaying (72 + 5)77 in the result, you must convert three , one , one2 , zero to sting variable

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top