Skip to content

[java] UnnecessaryCast: False positive for long cast before bit-shift operations on int/byte #6427

@blacelle

Description

@blacelle

Affects PMD Version:
7.20.0

Rule:
UnnecessaryCast

Description:

Code Sample demonstrating the issue:

long l2 = ((long) someInt & 0xFF) << 32;

The cast is necessary as the expression is immediately bit-shifted, which leads to different behavior over an int or a long. For instance, the following demonstrates the assertion is false:


	@Test
	public void testCastLongIsUseful() {
		int someInt = 1;
		long withCast = ((long) someInt & 0xFF) << 32;
		long withoutCast = (someInt & 0xFF) << 32;
		Assertions.assertThat(withCast).isEqualTo(withoutCast);
	}

The cast would be unecessary if the expression without cast was guaranteed to be a long (e.g. if 0xFF was actually a long/written as 0xFFL).

Expected outcome:

PMD reports a violation at line 0, but that's wrong. That's a false positive.

Running PMD through: [CLI | Ant | Maven | Gradle | Designer | Other]
maven

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions