0

Does Java have a :: operator? Please, do not close this question, I did search the docs and I'm sure it does not but I want to be completely sure.

I.e can there be something like MyClass::x or anything visually resembling that in Java.

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158

4 Answers4

7

In Java 8 the operator :: has been introduced as a way to refer to a method. Basically, it turns the method into a first-class object, something you can pass to other methods as an argument, store in a variable, and return from a method.

This addition to the syntax is a part of the overall orientation towards the Functional Programming paradigm which is being introduced with Java 8. The elementary feature of FP are higher-order functions—such functions which accept other functions as argument, or return functions. This paradigm allows one to eliminate much boilerplate which now pervades the Java source code.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
4

until and including Java 7: No!

Java 8: Yes!

simply as that.

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
0

In Java 8 it allows for referencing of static members of a class, similar to PHP.

public class YourClass {

    public static int comparer(String one, String two){
        return one.length() - two.length();
    }

    public static void main(String[] args) {
        Arrays.sort(args, YourClass::comparer);
        //args are now sorted
    } 

}

As stated in comments, this is Java 8 (and later) only. JDK 7 and below does not have this.

Rogue
  • 11,105
  • 5
  • 45
  • 71
  • I'm pretty sure that's not how you use it. There's already `YourClass.doSomething()` for that. – user2357112 Dec 13 '13 at 09:43
  • @MarkoTopolnik and user2357112 You are both correct, that was my own mistake having not used it yet myself. I'll update the answer – Rogue Dec 13 '13 at 09:44
-1

Upto Java 7 there is no double colon operator(::) in java as in C++. But Java 8 introduce double colon operator which is used to refer the methods.

Example(For Static Method)

public class TestClass {

    public void functionTest() {...}

}

We can call function 'functionTest()' by using double colon operator(::).

TestClass t=new TestClass();
t::functionTest

If 'functionTest()' is static then we can refer directly by using class name

TestClass::functionTest

There are four kinds of method references(as written in java doc)

For more information refer java doc

  • 1
    The documentation you refer to contradicts your answer, which is because your answer is wrong. So you could learn something by reading the very document you are referring OP to. – Marko Topolnik Dec 13 '13 at 09:55
  • that was my mistake...now i think this is correct answer – sumit gupta Dec 13 '13 at 10:15
  • It is still wrong because the term "escape resolution" has nothing to do with Java---or with C++. BTW the downvote is not mine. – Marko Topolnik Dec 13 '13 at 10:20