A Java Example


The following Java program simply prints the user name entered from the webpage. It is to describe how a class is defined and being used. It includes the following components:
  • PrintName: a class,
  • main: the method being an entry point of any Java program,
  • name: a member property to store the input name,
  • setName: a member method for setting passed parameter as name, and
  • getName: a member method for returning the set name.
Name =

         
PrintName.java
// This example describes how a class is defined and being used.
//
// Syntax of defining a Java class is
//   <modifier> class <class-name> {
//     members and methods
//   }

public class PrintName {

  // The main( ) method is the entry point of any Java program
  // and is part of its class, but not part of objects.
  public static void main( String args[ ] ) {

    // Syntax of Java object creation is
    //   <class-name> object-name = new <class-constructor>;
    PrintName printName = new PrintName( );

    // Set name member of this object:
    printName.setName( args[0] );

    // Print the name:
    System.out.println( "Hello, " + printName.getName( ) );
  }

  // Syntax of defining a memeber variable of the Java class is
  //   <modifier> type <name>;
  private String name;

  // Syntax of defining a member method of the Java class is
  //   <modifier> <return-type> methodName( <optional-parameter-list> )
  //   <exception-list> {
  //       ...
  //   }
  public void setName( String n ) {
    // Set passed parameter as name.
    name = n;
  }

  public String getName( ) {
    // Return the set name.
    return name;
  }
}

// Output of the above given code would be: Hello, name




      You’re not completely useless, you can always serve as a bad example.