Saturday, 11 March 2017

Shows the use of class in the program in java

This is a Java program which shows the use of class in the program

Program:

  1. class Rectangle
  2. {
  3.  int height;
  4.  int width;
  5.  void area()
  6.  {
  7.   int result=height*width;
  8.   System.out.println(“The area is ”+result); 
  9.  }
  10. }
  11. class classDemo
  12. {
  13.  public static void main(String args[])
  14.  {
  15.   Rectangle obj=new Rectangle();
  16.   obj.height=10;//setting the attribute values 
  17.   obj.width=20;//from outside of class
  18.   obj.area();//using object method of class is called
  19.  }
  20. }


Variables scope program in java


Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compiler time and independent of function call stack.

Program:

public class VarScopeProg
{
 public static void main(String[] args)
 {
   int A=10;
   {
     int B=20;
     System.out.println("Block A: "+A);
     System.out.println("Block B: "+B);
   }//scope of B=20 ends here
   {
   int B=30;//scope of B=30 starts here
   System.out.println("Block A: "+A);
   System.out.println("Block B: "+B);
   }//scope of B=30 ends here
   int B=40;//scope of B=40 starts here
   {
     System.out.println("Block A: "+A);
     System.out.println("Block B: "+B);

   }
 }//scope of all the variables end here
}