help needed to know how the code is running
class Char{
public static void main (String a[])
{
char c1,c2,c3;
c1=64;
c2=187;
//c3=64+187;
System.out.println("The symbol is "+ (c1+c2));
}
}
output 251
class Char{
public static void main (String a[])
{
char c1,c2,c3;
c1=64;
c2=187;
c3=64+187;
System.out.println("The symbol is "+ c3);
}
}
output a symbol
Why are the two outputs different plz explain i have[INDENT] written this code in notepad ++
Re: help needed to know how the code is running
In Java for an arithmetic expression involving two char variables, the operands are promoted to ints and the result is an int.
Then, when you use println("whatever" + (c1+c2)) it prints the integer value of the sum of integer 64 and integer 187
On the other hand...
When you write char c3 = 64+187, it automatically converts the integer sum of 64 and 187 to a char and stores it in c3. Then when you use println("whatever" + c3) you get the Java char corresponding to the integer value 251 (shows up on my system as a lower-case Latin u with circumflex).
The topic Numeric Promotions and its implications is spelled out in section 5.6 of the Java Language Specification. Maybe there is some information in whatever reference material you are learning Java from. (Class notes? Textbook? What?)
Maybe you can play around with something like
Code java:
public class Z
{
public static void main(String [] args)
{
char c1, c2, c3, c4;
c1 = 64;
c2 = 187;
c3 = 64 + 187;
c4 = (char)(c1 + c2);// Cast needed to prevent compiler warning
System.out.println(" c1 = " + c1);
System.out.println(" c2 = " + c2);
System.out.println(" c3 = " + c3);
System.out.println(" c4 = " + c4);
System.out.println();
System.out.println(" (int)c1 = " + (int)c1);
System.out.println(" (int)c2 = " + (int)c2);
System.out.println(" (int)c3 = " + (int)c3);
System.out.println(" (int)c4 = " + (int)c4);
System.out.println();
System.out.println(" c1+c2 = " + (c1+c2));
System.out.println("(char)(c1+c2) = " + (char)(c1+c2));
}
}
See if the output makes sense. If not, tell us what it printed and what you expected it to print and what you don't understand about the difference(s).
Cheers!
Z
Re: help needed to know how the code is running
thanx Zaphod_b you were a great help i have been referring complete reference for java i read about type promotion and casting and now i understand it completely...
Re: help needed to know how the code is running
class None{
public static void main(String args[])
{
byte b =-2;
b = (byte)(b>>>10);
System.out.println("the value of b is"+b);// output -1
}
}
I am not getting why this code is generating -1 ,as >>> this is an unsigned operator it should append zero at th higher priority bits kindly reply!!!1
Re: help needed to know how the code is running
What has this got to do with the subject of this thread?
To avoid getting more !!!1 than kindness in your replies, please decide to which of your threads people should post. And leave a note in the other one redirecting them.
Re: help needed to know how the code is running
Quote:
Originally Posted by
pbrockway2
What has this got to do with the subject of this thread?
Actually it is related because it concerns the effects of Numeric Promotions, and this question is a continuation of investigation of the concepts illustrated by the original post in this thread and by my previous response. The problem (from my point of view) is that the title of the thread is singularly uninformative.
The other recent thread from this Poster has a similar title, but is about a completely different topic, namely, about using an int condition in an if() statement.
To the Original Poster: Try to choose appropriate titles for your threads.
To the Community: Sometimes when people start threads they don't know the exact terminology to make the titles something that is "textbook-precise." If I think I can help, I'll give it a shot. If others think that it's not worth their efforts to try to figure out where it's coming from and don't want to try, well, as my dear old Earthling-adoptive grannie used to say, "Chacun à son goût!" Actually, she used the cajun equivalent "A chacun son goût," but her snobbish son (my adoptive Uncle Whose Name Must Not Be Spoken) tried to refine it by using textbook French. But that's another story...
Anyhow...
Quote:
Originally Posted by Dark knight
why this code is generating -1
In the expression (byte)(b >>> 10), b is promoted to an int. The int is shifted right (with zeros shifted into the upper bits), and then you cast it to a byte (which merely chops off the upper 24 bits of the int. Since the eight lower bits are '1' the result is decimal -1.
Here's an example, where I have separated out the conversion to byte. I lined up the bits of the byte variable below the place in the int variable where the byte got its value. I put everything in a loop so that we can see the results as it is shifted one bit at a time:
Code java:
public class z
{
public static void main(String [] args)
{
byte b =-2;
for (int i = 0; i < 11; i++)
{
int intc = (b >>> i);
byte bytec = (byte)intc; // Cast is necessary to make the compiler tolerate the loss of precision
System.out.printf("i = %2d: Decimal value of intc = %d\n", i, intc);// output -1
System.out.printf(" Binary value of intc = %32s\n", binaryInt(intc));
System.out.printf(" Binary value of bytec = %32s\n", binaryByte(bytec));
System.out.printf(" Decimal value of bytec = %d\n\n", bytec);// output -1
}
}
// Convert a byte to a binary string with leading zeros
static String binaryByte(byte x)
{
String str = "";
for (int mask = 0x80; mask != 0; mask >>>= 1)
{
if ((mask & x) == 0)
{
str += '0';
}
else
{
str += '1';
}
}
return str;
}
// Convert an int to a binary string with leading zeros
static String binaryInt(int x)
{
String str = "";
for (int mask = 0x80000000; mask != 0; mask >>>= 1)
{
if ((mask & x) == 0)
{
str += '0';
}
else
{
str += '1';
}
}
return str;
}
}
Output:
Code :
i = 0: Decimal value of intc = -2
Binary value of intc = 11111111111111111111111111111110
Binary value of bytec = 11111110
Decimal value of bytec = -2
i = 1: Decimal value of intc = 2147483647
Binary value of intc = 01111111111111111111111111111111
Binary value of bytec = 11111111
Decimal value of bytec = -1
i = 2: Decimal value of intc = 1073741823
Binary value of intc = 00111111111111111111111111111111
Binary value of bytec = 11111111
Decimal value of bytec = -1
i = 3: Decimal value of intc = 536870911
Binary value of intc = 00011111111111111111111111111111
Binary value of bytec = 11111111
Decimal value of bytec = -1
i = 4: Decimal value of intc = 268435455
Binary value of intc = 00001111111111111111111111111111
Binary value of bytec = 11111111
Decimal value of bytec = -1
.
.
.
i = 10: Decimal value of intc = 4194303
Binary value of intc = 00000000001111111111111111111111
Binary value of bytec = 11111111
Decimal value of bytec = -1
The bottom line for me is: If you have to use a cast, somewhere ("just to keep the compiler happy"), make absolutely sure that you understand the ramifications.
Cheers!
Z
Re: help needed to know how the code is running
Thanks for alerting everyone to the accidental duplicate in the other post.
What you're dealing with in the cast to byte is a so-called "narrowing primitive conversion" and is dealt with in JLS 5.1.3. (Casts in general are described at 5.6) This occurs after the unary numeric promotion you get as a result of using the >>> operator which had already been referred to.
The mark of such narrowing conversions is that they can do real "damage" to the value, not just the amount of precision involved. In the case of int->byte the docs actually warn us "A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value".
-----
You actually had an example of another narrowing primitive conversion in the original post of this thread: "c3=64+187;" where c3 is of type char.
The right hand side is a constant int expression. And when it gets assigned to a char variable a narrowing primitive conversion takes place. This only applies to constant expressions like "64+187", anything else requires a cast like that in #4 to byte. Either way though - cast (5.2) or assignment (5.6) - you get a potentially dangerous narrowing from int to something "smaller".
Re: help needed to know how the code is running
thanx zaphod_b for the clarification i get it now and i will keep in mind the thread thinng....
thanx pbrockway2 but i dont have JLS to refer with i am using complete reference for java should i switch over to JLS is it better
Re: help needed to know how the code is running
The JLS is available online (like this forum). It is probably *not* better than a (good) book because of all the lawyerly twists and turns. But it *is* authoritative and, hence, a necessary complement to any other resources. For questions like this (when and how values get associated with different types) there is ultimately no other source of truth.
Unlike Oracle's Tutorial which I link to because of the explanations and examples it gives, I would link to the JLS only because of the detail which it offers which would be tedious to repeat (and which is probably more than was asked about). If you are new to Java you should be aware of its existence and begin to get familiar with it, but should *not* be overwhelmed and feel that every last clause be understood at first reading.
Re: help needed to know how the code is running
Quote:
Originally Posted by
Zaphod_b
[url=docs.oracle.com/javase/specs/jls/se5.0/jls3.pdf]
This is a book for JAVA,isn't it?I want to learn JAVA,and the publisher of this book is well known to me.Take notice that i know C and C++ quite well.So it this book appropriate for me to read?Or is it too much for a BEGINNER² like me to study it?I have read only a small tutorial about JAVA on the net,but it was too brief i think.
Comment : I know that is off topic but starting a new thread just about it i do not if it was going to be appropriate :)