There is no need to escape the $
as String.startsWith
takes just a normal string as argument, not a regex.
if (w.startsWith("$") || w.startsWith(" $"))
will suffice.
If you use String.startsWith(String prefix, int offset)
(not required in this case I think) give 0
as offset, not 1 as you have to check from the beginning for a $
. It is required if you have to test whether a substring starts with the prefix. In that case, give the beginIndex of substring.