-1

i came across a code in java that doesn't have a array initialization. when there is an increment in the value,it changes to 1.

import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
  public static void main(String args[]){
    int ar1[] = new int[26];
    String first="abc";

    for (int i = 0; i < first.length(); i++) {
      ar1[first.charAt(i) - 'a']++;
      System.out.println(ar1[i]);
    }



  }


}

the output is 1 1 1. how does that happen

2
  • The default value for int[] is 0. This, int ar1[] = new int[26]; fills the array with twenty-six zeros. Commented Nov 29, 2018 at 5:32
  • It happens because the letters a, b, and c, only appear once in your input string. Take a string that has a appearing more than once, and your code should correctly record the count. Commented Nov 29, 2018 at 5:37

1 Answer 1

1

The default value is zero.

ar1[first.charAt(i) - 'a']++; increments the value which corresponds to the particular letter. What it basically does is count the frequency of letters in a string.

in abc, a is ar[0], b is ar1[1], and so on

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.