Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusing code, compiles fine. How this code works? [duplicate]

Tags:

java

types

Following code compiles and gives 1 as output, its a bit confusing for me. I tried javap for this but from there also I couldn't figure out. I have checked for similar posts but couldn't find out similar question here.

Take look at the code:

int i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);

here is bytecode for it

Compiled from "Test.java"
public class Test {
  public Test();
  public static void main(java.lang.String[]);
}

How the types are working here? is it dependent of size of datatype? How the code is working?

like image 535
eatSleepCode Avatar asked Jan 22 '14 06:01

eatSleepCode


People also ask

What is duplicate code called?

Code duplicate – identical or similar source code Source code that is used in identical form several times within a piece of software is called a code duplicate – alternatively also a software clone or source code clone. Similar code sections or fragments are also considered duplicates.

Is it okay to duplicate code?

Duplication is bad, but… It isn't a question of whether you'll remember: it's a question of when you'll forget.” Which makes perfect sense. It's time well spent when you try to make your code streamlined and readable. You'll end up with a cleaner, easier-to-maintain, and more extensible code base as a result.

Why is code duplication not recommended?

It's safe to say that duplicate code makes your code awfully hard to maintain. It makes your codebase unnecessary large and adds extra technical debt. On top of that, writing duplicate code is a waste of time that could have been better spent.


1 Answers

This is just a sequence of unary + and - operations mixed with type casts.

You start with -1, cast it to a long, the unary plus does nothing, cast it to an int, unary minus (value is now +1), cast to char, unary +, cast to byte.

like image 71
Henry Avatar answered Sep 29 '22 11:09

Henry