Thursday, 29 November 2018

Java - Variables and Scopes


Three Scopes and Life time of Variable
1.   Instance Variable(Class Scope)
2.   Local Variable(Method Scope)
3.   Static variable
Instance Variables
Instance variables are already discussed
Local Variable (Method Scope)
Variables declared within method can be known as local scope. When run time invokes the method, the local scope variable has the memory and the memory destroys after runtime exits from method. Other methods can’t use the local variables.
Block scope is another feature of local scope. Variable declaration within if block, for block, while block can be known as block scope. The block scope variables can’t be visible in other blocks.
Example
   if (x==5)
         int y=10;
   S.o.p(y); // error
Static variable
Static variables are having common memory for all objects. It can be accessed by using objectname.varname or classname.varname. There are no differences to use two different syntaxes to access the static variables. Static variables can only be declared outside of methods and constructors. Static variable will have default values.
Consider following examples
Example 1
class A
{
static int x; // static variable
int b; // instance variable
   A()
         {
              static int y; //error
         }
   void get()
         {
              static int z; //error
         }
   public static void main(String arg[])
         {
              static int p; //error
              System.out.println(x);
         }
}
Example 2
class A
{
   static int a=100;
}
class B
{
   public static void main(String arg[])
         {
              System.out.println(A.a); // classname.variablename
              A ob=new A();
              System.out.println(ob.a); //objectname.variablename
         }
}

Java Program Samples


package java_test_programs.abstract_pack.abstract_1;

abstract class A {
       abstract int sum(int i, int j);

       abstract int mul(int i, int j);

       abstract void getString(String str);
}

class B extends A {
       public int sum(int i, int j) {
              return (i + j);
       }

       int mul(int i, int j) {
              return (i * j);
       }

       void getString(String str) {
              System.out.println(str);
       }
}

class AbstractClass1 {
       public static void main(String args[]) {
              B b = new B();
              System.out.println(b.sum(5, 6));
              System.out.println(b.mul(5, 6));
              b.getString("Java");
       }
}

Output :
11
30
Java


/* abstract methods with concrete methods */
package java_test_programs.abstract_pack.abstract_2;

abstract class Abstract {
       abstract int sum(int i, int j);

       abstract int mul(int i, int j);

       abstract void getString(String str);

       void callMe() {
              System.out.println("I am callMe() of abstractClass");
       }
}

class B extends Abstract {
       int sum(int i, int j) {
              return (i + j);
       }

       int mul(int i, int j) {
              return (i * j);
       }

       void getString(String str) {
              System.out.println(str);
       }
}

class AbstractClass2 {
       public static void main(String args[]) {
              B b = new B();
              System.out.println(b.sum(5, 6));
              System.out.println(b.mul(5, 6));
              b.getString("Java");
              b.callMe();
       }
}


Output :
11
30
Java
I am callMe() of abstractClass


package java_test_programs.abstract_pack.abstract_3;

abstract class A {
       abstract int sum(int i, int j);
}

abstract class B extends A {
       abstract int mul(int i, int j);
}

class C extends B {
       int sum(int i, int j) {
              return (i + j);
       }

       int mul(int i, int j) {
              return (i * j);
       }
}

class AbstractClass3 {
       public static void main(String args[]) {
              C c = new C();
              System.out.println(c.sum(3, 4));
              System.out.println(c.mul(3, 4));
       }
}

Output :
7
12


package java_test_programs.abstract_pack.abstract_4;

class A {
       void print(String str) {
              System.out.println(str + "-Printed by A");
       }

       void get() {
              System.out.println("I am get() of A");
       }
}

abstract class B extends A {
       abstract void callMe();
}

class C extends B {
       void callMe() {
              System.out.println("I am callMe");
       }

       void print(String str) {
              System.out.println(str + "-Printed by C");
       }

       void get() {
              System.out.println("I am get() of C");
       }
}

class AbstractClass4 {
       public static void main(String args[]) {
              C c = new C();
              c.callMe();
              c.print("Java");
              c.get();
       }
}
Output :

I am callMe
Java-Printed by C
I am get() of C


package java_test_programs.abstract_pack.abstract_5;

abstract class A {
       void get1() {
              System.out.println("I am get1() of A");
       }

       void get2() {
              System.out.println("I am get2() of A");
       }

       void get3() {
              System.out.println("I am get3() of A");
       }

       void get4() {
              System.out.println("I am get4() of A");
       }
}

class B extends A {
       void callMe() {
              System.out.println("I am callMe()");
       }

       void get2() {
              System.out.println("I am get2() of B");
       }

       void get4() {
              System.out.println("I am get4() of B");
       }
}

class AbstractClass5 {
       public static void main(String args[]) {
              B b1 = new B();
              b1.get1(); // A
              b1.get2(); // B
              b1.get3(); // A
              b1.get4(); // B
              b1.callMe(); // B

              A b2 = new B();
              b2.get1(); // A
              b2.get2(); // B
              b2.get3(); // A
              b2.get4(); // B

       }
}

Output :


I am get1() of A
I am get2() of B
I am get3() of A
I am get4() of B
I am callMe()
I am get1() of A
I am get2() of B
I am get3() of A
I am get4() of B


package java_test_programs.thread_pack.therad_1;

class Item {
       int x;

       void get() {
              System.out.println("I am get");
              try {
                     Thread.sleep(1000);
              } catch (Exception e) {
              }
              System.out.println("I am get after sleep");
              x = 10;
       }

       void calc() {
              System.out.println("I am Calc");
              System.out.println("x=" + x);
       }
}

class Thread1 implements Runnable {
       Item ob;
       Thread t;

       Thread1(Item ob) {
              this.ob = ob;
              t = new Thread(this);
              t.start();
       }

       public void run() {
              while (true) {
                     ob.get();
                     try {
                           Thread.sleep(1000);
                     } // try
                     catch (Exception e) {
                     }
              } // while
       }// run
}// class

class Thread2 implements Runnable {
       Item ob;
       Thread t;

       Thread2(Item ob) {
              this.ob = ob;
              t = new Thread(this);
              t.start();
       }

       public void run() {
              while (true) {
                     ob.calc();
                     try {
                           Thread.sleep(1000);
                     } // try
                     catch (Exception e) {
                     }
              } // while
       }// run
}// class

class AccessingObjectMembersMain {
       public static void main(String args[]) {
              Item ob = new Item();
              Thread1 t1 = new Thread1(ob);
              Thread2 t2 = new Thread2(ob);
       }
}


Output :

I am get
I am Calc
x=0
I am get after sleep
I am Calc
x=10
I am Calc
I am get
x=10
I am get after sleep
I am Calc
x=10
I am get
I am Calc
x=10



package java_test_programs.thread_pack.therad_2;
class Item {
       int x;

       synchronized void get() {
              System.out.println("I am get");
              try {
                     Thread.sleep(1000);
              } catch (Exception e) {
              }
              System.out.println("I am get after sleep");
              x = 10;
       }

       synchronized void calc() {
              System.out.println("I am Calc");
              System.out.println("x=" + x);
       }
}

class Thread1 implements Runnable {
       Item ob;
       Thread t;

       Thread1(Item ob) {
              this.ob = ob;
              t = new Thread(this);
              t.start();
       }

       public void run() {
              while (true) {
                     ob.get();
                     try {
                           Thread.sleep(1000);
                     } // try
                     catch (Exception e) {
                     }
              } // while
       }// run
}// class

class Thread2 implements Runnable {
       Item ob;
       Thread t;

       Thread2(Item ob) {
              this.ob = ob;
              t = new Thread(this);
              t.start();
       }

       public void run() {
              while (true) {
                     ob.calc();
                     try {
                           Thread.sleep(1000);
                     } // try
                     catch (Exception e) {
                     }
              } // while
       }// run
}// class

class AccessingObjectMembersSyncMain {
       public static void main(String args[]) {
              Item ob = new Item();
              Thread1 t1 = new Thread1(ob);
              Thread2 t2 = new Thread2(ob);
       }
}

Output :
I am get
I am get after sleep
I am Calc
x=10
I am get
I am get after sleep
I am Calc
x=10
I am get
I am get after sleep
I am Calc
x=10
I am Calc
x=10
I am get
I am get after sleep
I am Calc
x=10
I am get
I am get after sleep
I am Calc
x=10


package java_test_programs_exception_pack.exception_1;

class AgeException extends Exception {
       String msg = "";

       AgeException(String msg) {
              this.msg = msg;
       }

       AgeException() {
       }

       public String toString() // java.lang.Object
       {
              if (msg.equals(""))
                     return "Invalid age, please try to type within 100";
              else
                     return msg + " is a invalid age, please try to type within 100";
       }
}


package java_test_programs.operators_pack.operator_1;

class ArithAssignOp {
       public static void main(String args[]) {
              int a = 2;
              int b = 3;
              int c = 2;
              int d = 7;
              a += 5;
              b -= 2;
              c += a * b;
              // c=2+(7*1);
              d %= 2;
              System.out.println("a=" + a);
              System.out.println("b=" + b);
              System.out.println("c=" + c);
              System.out.println("d=" + d);
       }
}

Output :

a=7
b=1
c=9
d=1


package java_test_programs.operators_pack.operator_1;

class ArithOperators {
       public static void main(String args[]) {
              int x = 11, y = 5;
              System.out.println("x+y=" + (x + y));
              System.out.println("x-y=" + (x - y));
              System.out.println("x*y=" + (x * y));
              System.out.println("x/y=" + (x / y));
              System.out.println("x%y=" + (x % y));
       }
}

Output :

x+y=16
x-y=6
x*y=55
x/y=2
x%y=1


package java_test_programs_arrays_pack_arrays_1;
import java.io.*;

class Array1 {
       public static void main(String args[]) {
              try {
                     DataInputStream dis = new DataInputStream(System.in);
                     int a[] = new int[5];
                     System.out.println("Enter the Elements");
                     for (int i = 0; i < a.length; i++)
                           a[i] = Integer.parseInt(dis.readLine());
                     System.out.println("Result");
                     for (int i = 0; i < a.length; i++)
                           System.out.println(a[i]);
              } catch (Exception e) {
                     System.out.println(e);
              }
       }
}

Output :



package java_test_programs_arrays_pack_arrays_1;
class ArrayAssignDemo
{
public static void main(String args[])
{
int x[][][][]=new int[2][2][2][2];
int y[][]=x[0][0];

}
}


package java_test_programs_arrays_pack_arrays_1;

class ArrayDemo {
       public static void main(String args[]) {
              int a[] = { 1, 2, 3, 4 };
              for (int i = 0; i < 4; i++)
                     System.out.println(a[i]);
              String str[] = { "Java", "RMI", "JSP", "EJB" };
              for (int i = 0; i < 4; i++)
                     System.out.println(str[i]);
              char ch[] = { 'a', 'b', 'c', 'd' };
              for (int i = 0; i < 4; i++)
                     System.out.println(ch[i]);
       }
}

Output :
1
2
3
4
Java
RMI
JSP
EJB
a
b
c
d


package java_test_programs_arrays_pack_arrays_1;

class ArrayFor {
       public static void main(String ar[]) {
              int z = 10;
              int x[] = new int[z];
              for (int i = 0; i < x.length; i++) {
                     x[i] = i + 1;
                     System.out.println(x[i]);
              }
              for (int i = 0; i < x.length; i++) {
                     System.out.println("The Position is" + i);
                     System.out.println(x[i]);
              }
       }
}


Output :

1
2
3
4
5
6
7
8
9
10
The Position is0
1
The Position is1
2
The Position is2
3
The Position is3
4
The Position is4
5
The Position is5
6
The Position is6
7
The Position is7
8
The Position is8
9
The Position is9
10


package java_test_programs_arrays_pack_arrays_1;

import java.io.*;

class ArrayForEach {
       public static void main(String arg[]) {
              try {
                     int m[] = new int[10];
                     DataInputStream dis = new DataInputStream(System.in);
                     System.out.println("Enter The Length ");
                     int x = Integer.parseInt(dis.readLine());
                     for (int i = 0; i < x; i++) {
                           System.out.print("x[" + i + "]:");
                           m[i] = Integer.parseInt(dis.readLine());
                     }
                     for (int z : m) // For Each
                     {
                           System.out.println(z);
                     }
              } catch (IOException ex) {
                     System.out.println("Excepation Raised: " + ex);
              }

       }

}


package java_test_programs_arrays_pack_arrays_1;

class ArrayRunTime {
       public static void main(String args[]) {
              int s = 3;
              int x[] = new int[s];
              System.out.println("S");
              for (int i = 0; i < s; i++) {
                     x[i] = i + 1;
                     System.out.println(x[i]);
              }
              int t = 5;
              x = new int[t];
              System.out.println("t");
              for (int i = 0; i < 5; i++) {
                     x[i] = i + 5;
                     System.out.println(x[i]);
              }
       }
}

Output :

S
1
2
3
t
5
6
7
8
9