-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

Shravan Kumar
  • 41
  • 1
  • 2
  • 8
  • The default value for `int[]` is `0`. This, `int ar1[] = new int[26];` fills the array with twenty-six zeros. – Elliott Frisch Nov 29 '18 at 05: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. – Tim Biegeleisen Nov 29 '18 at 05:37

1 Answers1

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

LonelyCpp
  • 2,533
  • 1
  • 17
  • 36