Answers for "static and non static keyword in java"

1

static keyword in java

// example on static variable in java.
class EmployeeDetails
{
   // instance variable
   int empID;
   String empName;
   // static variable
   static String company = "FlowerBrackets";
   // EmployeeDetails constructor
   EmployeeDetails(int ID, String name)
   {
      empID = ID;
      empName = name;
   }
   void print()
   {
      System.out.println(empID + " " + empName + " " + company);
   }
}
public class StaticVariableJava
{
   public static void main(String[] args)
   {
      EmployeeDetails obj1 = new EmployeeDetails(230, "Virat");
      EmployeeDetails obj2 = new EmployeeDetails(231, "Rohit");
      obj1.print();
      obj2.print();
   }
}
Posted by: Guest on November-21-2020
1

static keyword in java

// example on static block in java.
public class StaticBlockExample
{
   // static variable
   static int a = 10;
   static int b;
   // static block
   static
   {
      System.out.println("Static block called.");
      b = a * 5;
   }
   public static void main(String[] args)
   {
      System.out.println("In main method");
      System.out.println("Value of a : " + a);
      System.out.println("Value of b : " + b);
   }
}
Posted by: Guest on November-21-2020
1

static vs non static java

// Static vs Object Called
// Static Methods don't require you to call a constructor

// Initialize statically
public class MyClass {

  private static int myInt;

  static {
      myInt = 1;
  }

  public static int getInt() {
      return myInt;
  }
}

// Then call it
System.out.println(MyClass.getInt());

// VS Constructor

public class MyClass {
 
  private int myInt;
  
  public MyClass() {
    myInt = 1;
  }
  
  public int getInt() {
	return this.myInt;
  }
}
// Then call it
MyClass myObj = new MyClass();
System.out.println(myObj.getInt());
Posted by: Guest on July-10-2020

Code answers related to "static and non static keyword in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language