Free java course. Sign Up for tracking progress →

Java: Syntax sugar

Similar constructions index = index + 1 in Java are used quite often, so the creators of the language added an abbreviated version of the record: index + = 1.

It is important to understand that the differences are only in the way of recording.

Such abbreviations are called “syntactic sugar”, because they make the process of writing code a little easier and more pleasant, “sweetening” it :)

There are abbreviated forms for all arithmetic operations and for string concatenation:

  • a = a + 1a += 1
  • a = a - 1a -= 1
  • a = a * 2a *= 2
  • a = a / 1a /= 1
  • a = a +" bla"a +="bla"


Implement the countChars function, which counts repetitions of the specified character in a string. (In programming, they say "the number of occurrences of a character in a string").

The function takes two parameters as input: a string and a character. The function returns a number.

Call example:

var str = "If I look back I am lost";
countChars(str, 'I'); // => 3
countChars(str, 'z'); // => 0
countChars(str, 'o'); // => 3

The idea is to create a separate counter variable and increment it by 1 each time the specified character is found in a line. You will need to nest a conditional statement in the loop body. To increase the counter, use syntactic sugar.

If you got stuck and don't know what to do, you can ask a question in our huge and friendly community