• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

urgent code problem!!!!

 
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello all,
could anyone please analyze this code.
public class Q1 {
static void processorB() {
System.out.println(" is a boolean Operator.");
}

static Q1 processorA(){
Q1 q=null;
if (("java").startsWith("null"))
return q;
else
return null;
}

static {
System.out.print("Java".startsWith(""));
}

public static void main(String[] args) {
processorA().processorB();
}

ans : true is a boolean Operator
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, it executes the static block and prints "true",
because "Java".startsWith("") returns true.
Then it enters the main method.
processorA() returns null at any case. Buy processorB
is static, so processorA().processorB() equals
Q1.processorB(). So the processorB is executed
and prints "is a boolean Operator".
 
Enthuware Software Support
Posts: 4810
52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is simple as well tricky.
It is printing true because of the static block. It will execute when the class is first referenced.
Now, as you might have already noticed, processorA always returns null, still processorB is getting called (without NullPointerException).
This is because processorB is a static method and the compiler knows that processorA returns an object of class Q1 which has a static method processorB. But as calls to static methods depend only on the class of object reference (as opposed to instance method, where it depends on actual class of object), the compiler binds the call to processorB().
The point is, it does not wait till runtime to bind the call. So, it does not need any object. So, there is no nullpointer!
HTH,
Paul.
------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern)
www.enthuware.com/jqplus

Try out the world's only WebCompiler!
www.jdiscuss.com

[This message has been edited by Paul Anil (edited March 27, 2001).]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic