0

The below statement returns void

Pattern lazy = Pattern.compile("X??");
Matcher lazyMatcher = lazy.matcher("X");
if (lazyMatcher.matches()) {
  System.out.println(lazyMatcher.group());
}

Is there way to print void in java.

I tried below 2 statements , but does not help

System.out.println((String)lazyMatcher.group());
System.out.println(lazyMatcher.group().toString());

============================================================================= Updating

why am i getting String when i call below

System.out.println(lazyMatcher.group().getClass())  // returns string
System.out.println(lazyMatcher.group()) // returns void
upog
  • 4,965
  • 8
  • 42
  • 81

4 Answers4

14

void is nothing. You don't print it. If you wan't to print "void" you can do

System.out.println("void");
smerlung
  • 1,459
  • 1
  • 13
  • 32
12

void is not an object. All the void return type states is that nothing will be returned from the method. So the answer is no, there is no way to print void, as there is nothing to print.

With regards to your edited question, you are getting a String because Matcher.group() returns a string not void. See the documentation

Ben Green
  • 3,953
  • 3
  • 29
  • 49
  • It seems i can create object of type void... Object obj = java.lang.Void.TYPE; System.out.println(obj.toString()); – upog Sep 12 '13 at 10:33
  • If you view the documentation for that (http://docs.oracle.com/javase/7/docs/api/java/lang/Void.html) it says it is an 'uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void'. So this isn't saying that void is an object, it is a reference to the class object representing void. So the object you are creating is a Class object, not void. – Ben Green Sep 12 '13 at 11:04
  • That is not true. Check my answer. Java has the Void type just for the case the OP asked about. – Adam Arold Sep 12 '13 at 11:38
  • @AdamArold Apologies if I misunderstood it, but i assumed that the return type of TYPE was a class, as the documentation says that the return type is a Class? – Ben Green Sep 12 '13 at 12:26
3

You cant print something that isn't there.

Aneesh
  • 1,703
  • 3
  • 24
  • 34
3

There is the Void.class you can use. If you try Void.class.toString() it will return

class java.lang.Void
Adam Arold
  • 29,285
  • 22
  • 112
  • 207