A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println().
Call a Method
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
Types of Method
There are two types of methods in Java:
Predefined Method
User-defined Method
Predefined Method :
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
System.out.println().
User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.
Method Overloading
Method overloading is a feature in Java that allows multiple methods with the same name but different parameter lists to exist within the same class. It enhances the flexibility and readability of the code.
Example :
public class PrintUtil {
public void print(String message) {
System.out.println(message);
}
public void print(String message, int times) {
for (int i = 0; i < times; i++) {
System.out.println(message);
}
}
}
Method Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. It is a key aspect of polymorphism in Java, allowing subclasses to customize or extend the behavior of inherited methods.
The static keyword in Java is used for memory management primarily. It can be applied to variables, methods, blocks, and nested classes. When a member is declared static , it belongs to the class rather than instances of the class.
This means that only one instance of the static member exists, regardless of how many objects of the class are created.
Usage of Static Variables
Static variables are shared among all instances of a class. They are also known as class variables.
Example:
class Example {
static int counter = 0;
}
Static Methods
Static methods can be called without creating an instance of the class. They can access static data members and can change their values.
Example:
class Example {
static void display() {
System.out.println("Static method called");
}
}
Static Blocks
Static blocks are used for static initializations of a class. This code inside the static block is executed only once when the class is loaded into memory.
Example :
class Example {
static {
System.out.println("Static block executed");
}
}
Static Nested Classes
Static nested classes do not have access to other members of the enclosing class.
Example:
class OuterClass {
static class NestedStaticClass {
void display() {
System.out.println("Static nested class method called");
}
}
}
Tips and Best Practices
Memory Efficiency: Use static variables and methods to save memory and improve performance when the same value or method is used across all instances.
Utility Methods: Declare utility methods as static, as they do not require any state from the class instances. (TBD).
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
Initialization: Use static blocks for complex static variable initialization.
Access Control: Be mindful of access control; static members can be accessed directly using the class name, which might expose them unintentionally.
Avoid Overuse: Overusing static members can lead to code that is difficult to test and maintain. Use them judiciously. (TBD).
Common Mistakes and Errors
Non-static Context: Attempting to access non-static members from a static context will result in a compilation error.
Overuse of Static: Overusing static variables/methods can lead to issues with thread safety and maintenance complexity. Use static members only when necessary.
In Java, the static keyword typically flags a method or field as existing not once per instance of a class, but once ever. A class exists once anyway so in effect, all classes are “static” in this way and all objects are instances of classes.
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
Advantage of method overloading :
Method overloading increases the readability of the program.
Different ways to overload the method :
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
//Method overloading changing no of arguments
class Adder {
public static int add(int a,int b) { return a+b; } public static int add(int a,int b,int c) { return a+b+c; } public static void main(String[] srga) { System.out.println(Adder.add(1,12)); System.out.println(Adder.add(1,12,2)); } }
Out put :
13
15
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
class Adder { static int add(int a,int b) { return a+b; } static double add(double a,double b) { return a+b; } public static void main(String[] args) { System.out.println(Adder.add(2,13)); System.out.println(Adder.add(2.3,2.3)); } }
Out put :
15
4.6
2. What is Constructor ?
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.
Rules for Creating Java 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.(TBD).
Types of Java Constructors :
There are two types of constructors in Java:
Default Constructor (no-arg constructor)
Parameterized Constructor
Default Constructor :
A constructor is called “Default Constructor” when it does not have any parameter.
Syntax:
<class_name>(){}
Example :
public class Customer {
Customer()
{
System.out.println(“Customer”);
} public static void main(String[] args) {
Customer prod = new Customer();
}
}
Out put :
“Customer”.
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.
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 :
public class Constroctor1 { String name; int price;
public Constroctor1(String name, int price) { System.out.println(“Milk rate is”); this.name = name; this.price = price; } public static void main(String[] args) {
Constroctor1 cus = new Constroctor1(“milk”, 35); System.out.println(cus.name); System.out.println(cus.price);
} }
Out put :
Milk rate is milk 35
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:
public class SuperMarket { String name; int price;
public static void main(String[] args) { SuperMarket prod1 = new SuperMarket(“milk”,30); SuperMarket prod2 = new SuperMarket(“curd”,20); SuperMarket prod3 = new SuperMarket(); System.out.println(prod1.name); System.out.println(prod1.price); System.out.println(prod2.name); System.out.println(prod2.price); prod1.buy();
}
public void buy() { System.out.println(price); System.out.println(name);
}
}
Out put :
milk 30 curd 10 30 milk
Difference Between Constructor and Method in Java
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 we do not 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 the following ways to copy the values of one object into another:
By Using Constructor
By Assigning the Values of One Object into Another
By Using clone() Method of the Object Class
Java Super Class Constructor :
In Java, the concept of the “super constructor” refers to a subclass’s ability to explicitly invoke a constructor of its superclass. It is a fundamental aspect of Java’s inheritance feature, which allows one class to inherit fields and methods from another. Using the super keyword to call a superclass’s constructor is crucial for the proper initialization of an object’s inheritance hierarchy.
In object-oriented programming, a class is a basic building block. It can be defined as template that describes the data and behaviour associated with the class instantiation. Instantiating is a class is to create an object (variable) of that class that can be used to access the member variables and methods of the class.
Modifiers: A class can be public or has default access.
class keyword: The class keyword is used to create a class.
Class name: The name must begin with an initial letter (capitalized by convention).
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }.
2. What is Object ?
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.
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.
3. What is data types ?
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
Non-Primitive Data Types in Java
In Java, non-primitive data types, also known as reference data types, are used to store complex objects rather than simple values. Unlike primitive data types that store the actual values, reference data types store references or memory addresses that point to the location of the object in memory. This distinction is important because it affects how these data types are stored, passed, and manipulated in Java programs.
4. What is variables ?
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
String – stores text, such as “Hello”. String values are surrounded by double quotes
int – stores integers (whole numbers), without decimals, such as 123 or -123
float – stores floating point numbers, with decimals, such as 19.99 or -19.99
char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
boolean – stores values with two states: true or false
Syntax :
1
type variableName = value;
5. What is Methods ?
The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python.
A method is like a function i.e. used to expose the behavior of an object.
It is a set of codes that perform a particular task.
Two types of Method :
Static vs Non-static Method
This table summarizes the key differences between static and non-static methods in Java or similar object-oriented programming languages.
Aspect
Static Methods
Non-static Methods
Associated with
Class
Instance
Accessing Members and Methods
Can only directly access static members and methods of the class.
Can directly access both static and non-static members and methods of the class.
Initialization
Initialized when the class is loaded into memory.
Initialized when an instance of the class is created.
Scope
Available throughout the program execution
Available as long as the instance exists
Usage
Useful for utility methods, where the method does not depend on instance-specific data.
Useful for operations that require access to instance-specific data.
Calling Process
Can be called using the class name.
Must be called using an instance of the class.
Binding Process
Bound at compile-time.
Bound at runtime.
Overriding Process
Cannot be overridden.
Can be overridden in subclasses.
Memory Allocation
Memory is allocated only once for the entire program execution.
Memory allocated each time an instance is created.
6. Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of interpretation and compilation. It defines all the processes involved in creating a Java program. Java Architecture explains each and every step of how a program is compiled and executed.
Java Architecture can be explained by using the following steps:
There is a process of compilation and interpretation in Java.
Java compiler converts the Java code into byte code.
After that, the JVM converts the byte code into machine code.