Wednesday, February 1, 2012

Puzzle code of function in Java

Q1)Output of the program
class base
{
 static void hello()
  {
    System.out.println("Hello world");
  };

};

class main
{
  public static void main(String args[])
   {
    base.hello();
   };
};
Output:-Hello world
Discussion:-Here hello() function is declared as static function.So using (.) operator we
            can access the hello() methode.

Q2)Output of the program
class base
{
 private String hello(String s)
 {
    System.out.println("I am hello function" +s );  
    return s;
 };
};

class main
{
  public static void main(String args[])
   {
    base b=new base();
    String s=b.hello("Java");
   };
};           
Output:-Compile time error
Discussion:-Here hello() function is declared as private.So it is not possible to access using (.) operator.


Q3)Output of the program
class base
{
 protected void call()
 {
    while(true)
    {
     call();
    } 
}    
};

class main
{
  public static void main(String args[])
   {
    base b=new base();
    b.call();
   
   };
};
Output:-Nothing will print
Discussion:-While(true) means loop condition always satisfies.So the loop will exhicute infinite number of times.


Q4)Output of the program
class main
{
  public static void main(String args[])
   {
    for(int i=0;i<args.length;i++)
    {
      System.out.println(args[i]);
    }
  };
};
Output:-It will print file name of program
Discussion:-args[] array takes command line argument.

Q5)Output of the program
class base
{
   final void hello()
   {
    System.out.println("I am final methode");
   };
  
};

class derive extends base
{
 void hello()
 {
 }
}

class main
{
  public static void main(String [] args)
   {
  
   };
};
Output:-Compile time error
Discussion:-hello() methode is declared as final,so overridden is not possible in derive class.

 Q6)Output of the program
 class C1
{
  public void m1()
   {  
    System.out.println("I am final function");
   };
};

class main extends C1
{
  private void  main()
  {  
    c1 c=new c1();
  };
};
Output:-Run time error
Discussion:-Here main() methode will declare privately.so from outside of the program it is not possible to call main() function
            directly.
       
           
           

No comments:

Post a Comment