Saturday, October 25, 2014

Which one is main function in Java Programs



Use of main function is optional in BlurJ editor. In mant schools, main function is not at all used and naturally students are confused about the main function.

Main function in java program is that function from where the execution of the program starts and ends.'public static void main (String args[])' is that main function and the function cannot be overloaded like 'public void main ()' or like that.

In many books, in java programs 'public void main ()' is defined and the program starts from the function in BlueJ edito but it is not the main function of java.

It is just like the other functions defined in the program, an user defined function.

I will use a simple program in different ways to clear the confusion among the students and few teachers who think that any function named 'main' is the function in java.

Take a number and display the factorial value of the number.

This program is using main function


import java.io.*;
class String1
{
  int i,n,fact;
 BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
   void show() throws Exception
 {
       fact=1;
       System.out.print("\nEnter the number:");
        n=Integer.parseInt(br.readLine());
      for(i=2;i<=n;i++)
      fact=fact*i;
      System.out.print("\nFactorial value="+fact);
    }
          
    public static void main(String args[])throws Exception
    {
         String1 ob=new String1();
         ob.show();
        }
    }

The second program is without main function, designed for BlueJ editor. Make one thing clear that there are many editors to run java program and in all editors main function 'public static void main(String args[])' is needed to run the program except Applet programs. Applet programs do not need any main function.:

Program without main function


import java.io.*;
class String1
{
  int i,n,fact;
 BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
   public void main() throws Exception
 {
       fact=1;
       System.out.print("\nEnter the number:");
        n=Integer.parseInt(br.readLine());
      for(i=2;i<=n;i++)
      fact=fact*i;
      System.out.print("\nFactorial value="+fact);
    }
       }
   
   
I think the third program will clear all confusions:

import java.io.*;
class String1
{
  int i,n,fact;
 BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
   public void show() throws Exception
 {
       fact=1;
       System.out.print("\nEnter the number:");
        n=Integer.parseInt(br.readLine());
      for(i=2;i<=n;i++)
      fact=fact*i;
      System.out.print("\nFactorial value="+fact);
    }
    private void main()
    {
        System.out.println("Try To Execute This Statement...");
    }
       
   }

   

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner