Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.
Simula is considered the first object-oriented
programming language. The programming paradigm where everything is
represented as an object is known as a truly object-oriented programming
language.
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
Apart from these concepts, there are some other terms which are used in Object-Oriented design:
- Coupling
- Cohesion
- Association
- Aggregation
- Composition
Object

Any entity that has state and behavior is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
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
Let's understand the relationship with real-time examples. For
example, One country can have one prime minister (one to one), and a
prime minister can have many ministers (one to many). Also, many MP's
can have one prime minister (many to one), and many ministers can have
many departments (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.

Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming
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).
Let's see some other rules that should be followed by identifiers.
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
- {
-
- }
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: -
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
- {
-
- void draw()
- {
-
- }
- }
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
- {
-
- int id;
-
- }
Package
- 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;
- class Employee
- {
-
- }
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
- {
-
- static final int MIN_AGE = 18;
-
- }
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

An entity that has state and behavior is known as an object e.g.,
chair, bike, marker, pen, table, car, etc. It can be physical or logical
(tangible and intangible). The example of an intangible object is the
banking system.
An object has three characteristics:
- 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.

For Example, Pen is an object. Its name is Reynolds; color is white,
known as its state. It is used to write, so writing is its behavior.
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
-
-
- class Student{
-
- int id;
- String name;
-
- public static void main(String args[]){
-
- Student s1=new Student();
-
- System.out.println(s1.id);
- System.out.println(s1.name);
- }
- }
Output:
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
-
-
-
- class Student{
- int id;
- String name;
- }
-
- class TestStudent1{
- public static void main(String args[]){
- Student s1=new Student();
- System.out.println(s1.id);
- System.out.println(s1.name);
- }
- }
Output:
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);
- }
- }
Output:
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
- class Student{
- int id;
- String name;
- }
- class TestStudent3{
- public static void main(String args[]){
-
- Student s1=new Student();
- Student s2=new Student();
-
- s1.id=101;
- s1.name="Sonoo";
- s2.id=102;
- s2.name="Amit";
-
- System.out.println(s1.id+" "+s1.name);
- System.out.println(s2.id+" "+s2.name);
- }
- }
Output:
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:

As you can see in the above figure, object gets the memory in heap
memory area. The reference variable refers to the object allocated in
the heap memory area.
Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.
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:
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.
We will learn these ways to create object later.
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:
Calling method through a reference:
- Calculation c=new Calculation();
- c.fact(5);
Calling method through an anonymous object
- new Calculation().fact(5);
Let's see the full example of an anonymous object in Java.
- 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);
- }
- }
Output:
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:
Initialization of refernce variables:
- Rectangle r1=new Rectangle(), r2=new Rectangle();
Let's see the example:
-
-
- 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();
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:
Real World Example: Account
File: TestAccount.java
-
-
-
- class Account{
- int acc_no;
- String name;
- float amount;
-
- void insert(int a,String n,float amt){
- acc_no=a;
- name=n;
- amount=amt;
- }
-
- void deposit(float amt){
- amount=amount+amt;
- System.out.println(amt+" deposited");
- }
-
- void withdraw(float amt){
- if(amount<amt){
- System.out.println("Insufficient Balance");
- }else{
- amount=amount-amt;
- System.out.println(amt+" withdrawn");
- }
- }
-
- void checkBalance(){System.out.println("Balance is: "+amount);}
-
- void display(){System.out.println(acc_no+" "+name+" "+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
In Java, a constructor is a block of codes similar to the method. It
is called when an instance of the class is created. At the time of
calling constructor, memory for the object is allocated in the memory.
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:
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. |
-
- class Bike1{
-
- Bike1(){System.out.println("Bike is created");}
-
- public static void main(String args[]){
-
- Bike1 b=new Bike1();
- }
- }
Output:
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
-
-
- class Student3{
- int id;
- String name;
-
- void display(){System.out.println(id+" "+name);}
-
- public static void main(String args[]){
-
- Student3 s1=new Student3();
- Student3 s2=new Student3();
-
- s1.display();
- s2.display();
- }
- }
Output:
Explanation:In the above class,you are not creating
any constructor so compiler provides you a default constructor. Here 0
and null values are provided by default constructor.
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.
-
- class Student4{
- int id;
- String name;
-
- Student4(int i,String n){
- id = i;
- name = n;
- }
-
- void display(){System.out.println(id+" "+name);}
-
- public static void main(String args[]){
-
- Student4 s1 = new Student4(111,"Karan");
- Student4 s2 = new Student4(222,"Aryan");
-
- s1.display();
- s2.display();
- }
- }
Output:
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
-
- class Student5{
- int id;
- String name;
- int age;
-
- Student5(int i,String n){
- id = i;
- name = n;
- }
-
- 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();
- }
- }
Output:
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
In this example, we are going to copy the values of one object into another using Java constructor.
-
- class Student6{
- int id;
- String name;
-
- Student6(int i,String n){
- id = i;
- name = n;
- }
-
- 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();
- }
- }
Output:
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:
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 package
The
static keyword in Java is used for memory
management mainly. We can apply java static keyword with variables,
methods, blocks and nested class.
The static keyword belongs to the class than an instance of the class.
The 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";
- }
Suppose there are 500 students in my college, now all instance data
members will get memory each time when the object is created. All
students have its unique rollno and name, so instance data member is
good in such case. Here, "college" refers to the common property of all
objects. If we make it static, this field will get the memory only once.
Java static property is shared to all objects.
Example of static variable
-
- class Student{
- int rollno;
- String name;
- static String college ="ITS";
-
- Student(int r, String n){
- rollno = r;
- name = n;
- }
-
- void display (){System.out.println(rollno+" "+name+" "+college);}
- }
-
- public class TestStaticVariable1{
- public static void main(String args[]){
- Student s1 = new Student(111,"Karan");
- Student s2 = new Student(222,"Aryan");
-
-
- s1.display();
- s2.display();
- }
- }
Output:
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.
-
-
- class Counter{
- int count=0;
-
- Counter(){
- count++;
- System.out.println(count);
- }
-
- public static void main(String args[]){
-
- Counter c1=new Counter();
- Counter c2=new Counter();
- Counter c3=new Counter();
- }
- }
Output:
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.
-
-
- class Counter2{
- static int count=0;
-
- Counter2(){
- count++;
- System.out.println(count);
- }
-
- public static void main(String args[]){
-
- Counter2 c1=new Counter2();
- Counter2 c2=new Counter2();
- Counter2 c3=new Counter2();
- }
- }
Output:
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
-
- class Student{
- int rollno;
- String name;
- static String college = "ITS";
-
- static void change(){
- college = "BBDIT";
- }
-
- Student(int r, String n){
- rollno = r;
- name = n;
- }
-
- void display(){System.out.println(rollno+" "+name+" "+college);}
- }
-
- public class TestStaticMethod{
- public static void main(String args[]){
- Student.change();
-
- Student s1 = new Student(111,"Karan");
- Student s2 = new Student(222,"Aryan");
- Student s3 = new Student(333,"Sonoo");
-
- 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
-
-
- 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);
- }
- }
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;
-
- 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:
Since JDK 1.7 and above, output would be:
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