Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.
Smalltalk is considered the first truly object-oriented programming language.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:- Object
- Class
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation
- Coupling
- Cohesion
- Association
- Aggregation
- Composition

Object

An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation.Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.Association
Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:- One to One
- One to Many
- Many to One, and
- Many to Many
Association can be undirectional or bidirectional.
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.Composition
The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically.Advantage of OOPs over Procedure-oriented programming language
1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented programming language, it is not easy to manage if code grows as project size increases.2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data can be accessed from anywhere.


3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.
Java Naming conventions
Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc.But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.The following are the key rules that must be followed by every identifier:
- The name must not contain any white spaces.
- The name should not start with special characters like & (ampersand), $ (dollar), _ (underscore).
Class
- It should start with the uppercase letter.
- It should be a noun such as Color, Button, System, Thread, etc.
- Use appropriate words, instead of acronyms.
- Example: -
- public class Employee
- {
- //code snippet
- }
Interface
- It should start with the uppercase letter.
- It should be an adjective such as Runnable, Remote, ActionListener.
- Use appropriate words, instead of acronyms.
- Example: -
- interface Printable
- {
- //code snippet
- }
Method
- It should start with lowercase letter.
- It should be a verb such as main(), print(), println().
- If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed().
- Example:-
- class Employee
- {
- //method
- void draw()
- {
- //code snippet
- }
- }
Variable
- It should start with a lowercase letter such as id, name.
- It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
- If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName.
- Avoid using one-character variables such as x, y, z.
- Example :-
- class Employee
- {
- //variable
- int id;
- //code snippet
- }
- It should be a lowercase letter such as java, lang.
- If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang.
- Example :-
- package com.javatpoint; //package
- class Employee
- {
- //code snippet
- }
Constant
- It should be in uppercase letters such as RED, YELLOW.
- If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY.
- It may contain digits but not as the first letter.
- Example :-
- class Employee
- {
- //constant
- static final int MIN_AGE = 18;
- //code snippet
- }
CamelCase in java naming conventions
Java follows camel-case syntax for naming the class, interface, method, and variable.If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
What is an object in Java

- State: represents the data (value) of an object.
- Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
- Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.

An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
Object Definitions:
- An object is a real-world entity.
- An object is a runtime entity.
- The object is an entity which has state and behavior.
- The object is an instance of a class.
What at is a class in Java?A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
- Fields
- Methods
- Constructors
- Blocks
- Nested class and interface

Syntax to declare a class:
- class <class_name>{
- field;
- method;
- }
Instance variable in Java
A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.Advantage of Method
- Code Reusability
- Code Optimization
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.Here, we are creating a main() method inside the class.
File: Student.java
- //Java Program to illustrate how to define a class and fields
- //Defining a Student class.
- class Student{
- //defining fields
- int id;//field or data member or instance variable
- String name;
- //creating main method inside the Student class
- public static void main(String args[]){
- //Creating an object or instance
- Student s1=new Student();//creating an object of Student
- //Printing values of the object
- System.out.println(s1.id);//accessing member through reference variable
- System.out.println(s1.name);
- }
- }
Output:
0 null
Object and Class Example: main outside the class
In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
File: TestStudent1.java
- //Java Program to demonstrate having the main method in
- //another class
- //Creating Student class.
- class Student{
- int id;
- String name;
- }
- //Creating another class TestStudent1 which contains the main method
- class TestStudent1{
- public static void main(String args[]){
- Student s1=new Student();
- System.out.println(s1.id);
- System.out.println(s1.name);
- }
- }
Output:
0 null
3 Ways to initialize object
There are 3 ways to initialize object in Java.- By reference variable
- By method
- By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
File: TestStudent2.java
- class Student{
- int id;
- String name;
- }
- class TestStudent2{
- public static void main(String args[]){
- Student s1=new Student();
- s1.id=101;
- s1.name="Sonoo";
- System.out.println(s1.id+" "+s1.name);//printing members with a white space
- }
- }
Output:
101 Sonoo
File: TestStudent3.java
- class Student{
- int id;
- String name;
- }
- class TestStudent3{
- public static void main(String args[]){
- //Creating objects
- Student s1=new Student();
- Student s2=new Student();
- //Initializing objects
- s1.id=101;
- s1.name="Sonoo";
- s2.id=102;
- s2.name="Amit";
- //Printing data
- System.out.println(s1.id+" "+s1.name);
- System.out.println(s2.id+" "+s2.name);
- }
- }
101 Sonoo 102 Amit
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java
- class Student{
- int rollno;
- String name;
- void insertRecord(int r, String n){
- rollno=r;
- name=n;
- }
- void displayInformation(){System.out.println(rollno+" "+name);}
- }
- class TestStudent4{
- public static void main(String args[]){
- Student s1=new Student();
- Student s2=new Student();
- s1.insertRecord(111,"Karan");
- s2.insertRecord(222,"Aryan");
- s1.displayInformation();
- s2.displayInformation();
- }
- }
Output:
111 Karan 222 Aryan

3) Object and Class Example: Initialization through a constructor
We will learn about constructors in Java later.Object and Class Example: Employee
Let's see an example where we are maintaining records of employees.
File: TestEmployee.java
- class Employee{
- int id;
- String name;
- float salary;
- void insert(int i, String n, float s) {
- id=i;
- name=n;
- salary=s;
- }
- void display(){System.out.println(id+" "+name+" "+salary);}
- }
- public class TestEmployee {
- public static void main(String[] args) {
- Employee e1=new Employee();
- Employee e2=new Employee();
- Employee e3=new Employee();
- e1.insert(101,"ajeet",45000);
- e2.insert(102,"irfan",25000);
- e3.insert(103,"nakul",55000);
- e1.display();
- e2.display();
- e3.display();
- }
- }
Output:
101 ajeet 45000.0 102 irfan 25000.0 103 nakul 55000.0
Object and Class Example: Rectangle
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
- class Rectangle{
- int length;
- int width;
- void insert(int l, int w){
- length=l;
- width=w;
- }
- void calculateArea(){System.out.println(length*width);}
- }
- class TestRectangle1{
- public static void main(String args[]){
- Rectangle r1=new Rectangle();
- Rectangle r2=new Rectangle();
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:
55 45
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:- By new keyword
- By newInstance() method
- By clone() method
- By deserialization
- By factory method etc.

Anonymous object
Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.If you have to use an object only once, an anonymous object is a good approach. For example:
- new Calculation();//anonymous object
- Calculation c=new Calculation();
- c.fact(5);
- new Calculation().fact(5);
- class Calculation{
- void fact(int n){
- int fact=1;
- for(int i=1;i<=n;i++){
- fact=fact*i;
- }
- System.out.println("factorial is "+fact);
- }
- public static void main(String args[]){
- new Calculation().fact(5);//calling method with anonymous object
- }
- }
Factorial is 120
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.Initialization of primitive variables:
- int a=10, b=20;
- Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
- //Java Program to illustrate the use of Rectangle class which
- //has length and width data members
- class Rectangle{
- int length;
- int width;
- void insert(int l,int w){
- length=l;
- width=w;
- }
- void calculateArea(){System.out.println(length*width);}
- }
- class TestRectangle2{
- public static void main(String args[]){
- Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:
55 45
Real World Example: Account
File: TestAccount.java
- //Java Program to demonstrate the working of a banking-system
- //where we deposit and withdraw amount from our account.
- //Creating an Account class which has deposit() and withdraw() methods
- class Account{
- int acc_no;
- String name;
- float amount;
- //Method to initialize object
- void insert(int a,String n,float amt){
- acc_no=a;
- name=n;
- amount=amt;
- }
- //deposit method
- void deposit(float amt){
- amount=amount+amt;
- System.out.println(amt+" deposited");
- }
- //withdraw method
- void withdraw(float amt){
- if(amount<amt){
- System.out.println("Insufficient Balance");
- }else{
- amount=amount-amt;
- System.out.println(amt+" withdrawn");
- }
- }
- //method to check the balance of the account
- void checkBalance(){System.out.println("Balance is: "+amount);}
- //method to display the values of an object
- void display(){System.out.println(acc_no+" "+name+" "+amount);}
- }
- //Creating a test class to deposit and withdraw amount
- class TestAccount{
- public static void main(String[] args){
- Account a1=new Account();
- a1.insert(832345,"Ankit",1000);
- a1.display();
- a1.checkBalance();
- a1.deposit(40000);
- a1.checkBalance();
- a1.withdraw(15000);
- a1.checkBalance();
- }}
Output:
832345 Ankit 1000.0 Balance is: 1000.0 40000.0 deposited Balance is: 41000.0 15000.0 withdrawn Balance is: 26000.0
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.- Constructor name must be the same as its class name
- A Constructor must have no explicit return type
- A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can have private, protected, public or default constructor in Java.
Types of Java constructors
There are two types of constructors in Java:- Default constructor (no-arg constructor)
- Parameterized constructor

Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
- <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. |
- //Java Program to create and call a default constructor
- class Bike1{
- //creating a default constructor
- Bike1(){System.out.println("Bike is created");}
- //main method
- public static void main(String args[]){
- //calling a default constructor
- Bike1 b=new Bike1();
- }
- }
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.Example of default constructor that displays the default values
- //Let us see another example of default constructor
- //which displays the default values
- class Student3{
- int id;
- String name;
- //method to display the value of id and name
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- //creating objects
- Student3 s1=new Student3();
- Student3 s2=new Student3();
- //displaying values of the object
- s1.display();
- s2.display();
- }
- }
0 null 0 null
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.- //Java Program to demonstrate the use of the parameterized constructor.
- class Student4{
- int id;
- String name;
- //creating a parameterized constructor
- Student4(int i,String n){
- id = i;
- name = n;
- }
- //method to display the values
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- //creating objects and passing values
- Student4 s1 = new Student4(111,"Karan");
- Student4 s2 = new Student4(222,"Aryan");
- //calling method to display the values of object
- s1.display();
- s2.display();
- }
- }
111 Karan 222 Aryan
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
- //Java program to overload constructors
- class Student5{
- int id;
- String name;
- int age;
- //creating two arg constructor
- Student5(int i,String n){
- id = i;
- name = n;
- }
- //creating three arg constructor
- Student5(int i,String n,int a){
- id = i;
- name = n;
- age=a;
- }
- void display(){System.out.println(id+" "+name+" "+age);}
- public static void main(String args[]){
- Student5 s1 = new Student5(111,"Karan");
- Student5 s2 = new Student5(222,"Aryan",25);
- s1.display();
- s2.display();
- }
- }
111 Karan 0 222 Aryan 25
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given below.Java Constructor | Java Method |
---|---|
A constructor is used to initialize the state of an object. | A method is used to expose the behavior of an object. |
A constructor must not have a return type. | A method must have a return type. |
The constructor is invoked implicitly. | The method is invoked explicitly. |
The Java compiler provides a default constructor if you don't have any constructor in a class. | The method is not provided by the compiler in any case. |
The constructor name must be same as the class name. | The method name may or may not be same as the class name. |

Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.There are many ways to copy the values of one object into another in Java. They are:
- By constructor
- By assigning the values of one object into another
- By clone() method of Object class
- //Java program to initialize the values from one object to another object.
- class Student6{
- int id;
- String name;
- //constructor to initialize integer and string
- Student6(int i,String n){
- id = i;
- name = n;
- }
- //constructor to initialize another object
- Student6(Student6 s){
- id = s.id;
- name =s.name;
- }
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- Student6 s1 = new Student6(111,"Karan");
- Student6 s2 = new Student6(s1);
- s1.display();
- s2.display();
- }
- }
111 Karan 111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.- class Student7{
- int id;
- String name;
- Student7(int i,String n){
- id = i;
- name = n;
- }
- Student7(){}
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- Student7 s1 = new Student7(111,"Karan");
- Student7 s2 = new Student7();
- s2.id=s1.id;
- s2.name=s1.name;
- s1.display();
- s2.display();
- }
- }
Output:
111 Karan 111 Karan
Q) Does constructor return any value?
Yes, it is the current class instance (You cannot use return type yet it returns a value).Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor as you perform in the method.Is there Constructor class in Java?
Yes.What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is found in the java.lang.reflect packageThe static can be:
- Variable (also known as a class variable)
- Method (also known as a class method)
- Block
- Nested class

1) Java static variable
If you declare any variable as static, it is known as a static variable.- The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
- The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).Understanding the problem without static variable
- class Student{
- int rollno;
- String name;
- String college="ITS";
- }
Java static property is shared to all objects.
Example of static variable
- //Java Program to demonstrate the use of static variable
- class Student{
- int rollno;//instance variable
- String name;
- static String college ="ITS";//static variable
- //constructor
- Student(int r, String n){
- rollno = r;
- name = n;
- }
- //method to display the values
- void display (){System.out.println(rollno+" "+name+" "+college);}
- }
- //Test class to show the values of objects
- public class TestStaticVariable1{
- public static void main(String args[]){
- Student s1 = new Student(111,"Karan");
- Student s2 = new Student(222,"Aryan");
- //we can change the college of all objects by the single line of code
- //Student.college="BBDIT";
- s1.display();
- s2.display();
- }
- }
111 Karan ITS 222 Aryan ITS
Program of the counter without static variable
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the count variable.- //Java Program to demonstrate the use of an instance variable
- //which get memory each time when we create an object of the class.
- class Counter{
- int count=0;//will get memory each time when the instance is created
- Counter(){
- count++;//incrementing value
- System.out.println(count);
- }
- public static void main(String args[]){
- //Creating objects
- Counter c1=new Counter();
- Counter c2=new Counter();
- Counter c3=new Counter();
- }
- }
Output:
1 1 1
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.- //Java Program to illustrate the use of static variable which
- //is shared with all objects.
- class Counter2{
- static int count=0;//will get memory only once and retain its value
- Counter2(){
- count++;//incrementing the value of static variable
- System.out.println(count);
- }
- public static void main(String args[]){
- //creating objects
- Counter2 c1=new Counter2();
- Counter2 c2=new Counter2();
- Counter2 c3=new Counter2();
- }
- }
Output:
1 2 3
2) Java static method
If you apply static keyword with any method, it is known as static method.- A static method belongs to the class rather than the object of a class.
- A static method can be invoked without the need for creating an instance of a class.
- A static method can access static data member and can change the value of it.
Example of static method
- //Java Program to demonstrate the use of a static method.
- class Student{
- int rollno;
- String name;
- static String college = "ITS";
- //static method to change the value of static variable
- static void change(){
- college = "BBDIT";
- }
- //constructor to initialize the variable
- Student(int r, String n){
- rollno = r;
- name = n;
- }
- //method to display values
- void display(){System.out.println(rollno+" "+name+" "+college);}
- }
- //Test class to create and display the values of object
- public class TestStaticMethod{
- public static void main(String args[]){
- Student.change();//calling change method
- //creating objects
- Student s1 = new Student(111,"Karan");
- Student s2 = new Student(222,"Aryan");
- Student s3 = new Student(333,"Sonoo");
- //calling display method
- s1.display();
- s2.display();
- s3.display();
- }
- }
Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT
Another example of a static method that performs a normal calculation
- //Java Program to get the cube of a given number using the static method
- class Calculate{
- static int cube(int x){
- return x*x*x;
- }
- public static void main(String args[]){
- int result=Calculate.cube(5);
- System.out.println(result);
- }
- }
Output:125
Restrictions for the static method
There are two main restrictions for the static method. They are:- The static method can not use non static data member or call non-static method directly.
- this and super cannot be used in static context.
- class A{
- int a=40;//non static
- public static void main(String args[]){
- System.out.println(a);
- }
- }
Output:Compile Time Error
Q) Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.3) Java static block
- Is used to initialize the static data member.
- It is executed before the main method at the time of classloading.
Example of static block
- class A2{
- static{System.out.println("static block is invoked");}
- public static void main(String args[]){
- System.out.println("Hello main");
- }
- }
Output:static block is invoked Hello main
Q) Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a java class without the main method.- class A3{
- static{
- System.out.println("static block is invoked");
- System.exit(0);
- }
- }
Output:
static block is invoked
Error: Main method not found in class A3, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application