Java4teachus

Sunday, May 19, 2019

Static Block in Java

Introduction Of Static Block


we know that as a part of class, we can define the instance data members & static data members in java program. To initialize this data members we used already in the constructor concept.

If we initialize instance data members and static data members in constructors then we get advantages of initialize instance data members but not recommended to initialize data members, because static data members values are replacing the same multiple times, which will take more execution time. To overcome this problem we use a concept called static block


Purpose Of Static Block


The Purpose of static block is used to the static data members of a class only once.

Static block will execute only once when the class is loaded the main memory.

Syntax-Of-Static-Block.jpeg


Static block will not return only value that is not return type. Static block is always written in the class definition but not the method definition.

Constructor will execute each and every time for initializing the instance data member but the static block will execute the only one time when the class is loaded by the static data members.

If we write the main method on static block in single block in single java program first static block will be call later main() method calls only once.+

Writing a static block is optional, whenever we initialize the static block  that time of point we write the static block.

Q . Write a java program which will initialize the data members with constructor by using static data member in the static block.

Program:-

class Student
{
int Id;
String name;
float marks;
static String crs;
static
{
crs="Java";
}
Student(int studentid, String studentname, float studentmarks)
{
Id=studentid;
name=studentname;
marks=studentmarks;
System.out.println("Student Id="+studentid);
System.out.println("Student name="+studentname);
System.out.println("Student marks="+studentmarks);
System.out.println("Student course="+crs);
}
}
class StudentInfo1
{
public static void main(String[] args)
{
Student s=new Student(1,"Lucky",80.1f);
Student s1=new Student(2,"Jameg Gossling",90.1f);
Student s2=new Student(3,"KVR",75.1f);
}
}

No comments:

Post a Comment

Thanks for visiting my site..