Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Does The Colon Mean In Java?

Tags:

java

What does the colon mean in Java? I have this:

public static List<String> findAllAnagrams(List<String> words) {
    List<String> result = new LinkedList<String>();
    for(String i : words){
        for (String j : words){
            if (result.contains(i)) {
                break;
            }
            else if (i == j) {

            } else {
                if (areAnagrams(i,j)){
                    result.add(i);
                    System.out.println(result);
                }
            }
        }
    }          
    return result;
}
like image 700
Floyd Bostan Avatar asked Jan 17 '13 08:01

Floyd Bostan


People also ask

What does colon mean in coding?

In the esoteric programming language INTERCAL, the colon is called "two-spot" and is used to identify a 32-bit variable—distinct from a spot (.) which identifies a 16-bit variable.

What does full colon mean in Java?

What does a colon mean in Java Programming. According to Oracle docs, When you see the colon(:) read it as "in".

Why colon is used in for loop?

In the context of a for -loop, the colon specifies the loop iterations.

Is colon a character in Java?

No. The colon character has no special meaning in a Java regex. In a String no character is special except for \ used to escape other characters.


2 Answers

It means one thing, it is an enhanced for loop.

for (String i: words) 

means the same things as

for (int i = 0; i < words.length; i++) {
    //
}

Joshua Bloch, in Item 46 of his worth reading Effective Java, says the following:

The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

The preferred idiom for iterating over collections and arrays

for (Element e : elements) {
    doSomething(e);
} 

When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

like image 94
Abraham Avatar answered Oct 22 '22 12:10

Abraham


(String i : words)

For each item in words

: to indicate iterator item and item as i

so to answer - it represents for-each loop

like image 45
TheWhiteRabbit Avatar answered Oct 22 '22 13:10

TheWhiteRabbit