27  previous  | toc  | next 
Parameters Passing

  1. Passing parameters to an Applet
    • /* filename: Message.java */
      
      import java.awt.*;
      import java.applet.*;
      public class Message extends Applet
      
      {
        public void paint(Graphics g)
        {
          g.drawRect(20, 5, 140, 50);
          // Draw the parameter string
          g.drawString(getParameter("message"), 30, 30);
        }
      }
      
    • <!-- filename: Message.html -->
      	<APPLET code = "Message.class"   
      	       	width  = 200
      	        height = 60>         
      		<PARAM NAME= "message" VALUE="Welcome!">
      	</APPLET>  
      
  2. Passing arguments to main() method
  3. Passing references as parameters
    • The simple program to swap two number:
      class SwapTwoInt {
        public static void main(String[] args) {
      
          int temp;
          int a = Integer.parseInt(args[0]);
          int b = Integer.parseInt(args[1]);
      
          System.out.println("before swapping a and b  : " + a + " " + b);
      
          temp = a;
          a = b;
          b = temp;
      
          System.out.println("after swapping a and b  : " + a + " " + b);
        }
      }
      
    • Use a swap function :
      class SwapTwoInt1 {
        public static void main(String[] args) {
      
          int a = Integer.parseInt(args[0]);
          int b = Integer.parseInt(args[1]);
      
          System.out.println("before swapping a and b  : " + a + " " + b);
      
          swap(a,b);    
      
          System.out.println("after swapping a and b  : " + a + " " + b);
        }
        
        private static void swap(int a, int b) {
          int temp = a;
          a = b;
          b = temp;
        }
      }
      
    • SwapTwoInt2 :
      class SwapTwoInt2 {
      
        static class IntObj { 
          int value;
          public IntObj(int i) { 
      	value=i; 
          }
        }
      
        public static void main(String[] args) {
          
          IntObj a = new IntObj(Integer.parseInt(args[0]));
          IntObj b = new IntObj(Integer.parseInt(args[1]));
      
          System.out.println("before swapping a and b  : " + a.value + " " + b.value);
      
          swap(a,b);    
      
          System.out.println("after swapping a and b  : " + a.value + " " + b.value);
        }
        
        private static void swap(IntObj a, IntObj b) {
          int temp = a.value;
          a.value = b.value;
          b.value = temp;
        }
      }
      

 27  previous  | toc  | next