wolfie/JavaChallenge

Java Challenge: A Java question will be published every Saturday. Stay tuned!

Follow publication

JavaChallenge42

Govinda Raj
wolfie/JavaChallenge
2 min readOct 8, 2021

--

Try to solve the challenge by yourself first!

I got surprised when I saw the bytecode of the above code —

public class JavaChallenge42 {
public JavaChallenge42() {
}

public static void main(String[] args) {
int[] arr = new int[5];
int index = 0;
byte var10001 = index;
int index = true;
arr[var10001] = 3;
System.out.println("The value of first element is " + arr[0]);
System.out.println("The value of fourth element is " + arr[3]);
}
}

Before understanding the bytecode, let me tell you the answer which is —

The value of first element is 3
The value of fourth element is 0

Yes, that’s what the answer is. So this challenge is on Java Precedence. Let’s see that —

There are three operators- [], =, = as —

1. arr [index]
2. arr [index]= index
3. index = 3

So according to the precedence table arr[index] has become arr[0] because currently index=0; Now there are 2 = so which one will be evaluated first? So we can get that info from the precedence table itself. In case of = operator the evaluation happens from Right to Left, so now index=3 evaluated first and now the value of the indexis 3 which will be assigned to arr[0] . The value arr[3] is 0 which is a default value of primitive int.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

wolfie/JavaChallenge
wolfie/JavaChallenge

Published in wolfie/JavaChallenge

Java Challenge: A Java question will be published every Saturday. Stay tuned!

Govinda Raj
Govinda Raj

Written by Govinda Raj

Senior Software Developer. Tech Enthusiast and love coding. My portfolio: https://govinda-raj.github.io/

No responses yet

Write a response