-
Static:
Belongs to the class: Static members (methods, variables, inner classes) belong to the class itself, not to any instance (object) of the class. This means they are shared across all instances of the class.
Access without creating an object: You can access static members directly through the class name, without creating an instance of the class.
Memory efficiency: Since static variables are class-level, they are created once per class (in memory), rather than for every object.
Use case: Static is used for constants, utility methods, and resources that should be shared across instances.
Example:
class MyClass {
static int staticVar = 10;
static void staticMethod() {
System.out.println("This is a static method.");
}
}
public class Test {
public static void main(String[] args) {
// Accessing static members
MyClass.staticMethod(); // No need to create an object
System.out.println(MyClass.staticVar);
}
}
This is a static method.
10
-
Non-static (Instance):
Belongs to the object: Non-static members (methods, variables) are specific to each object created from the class. Every object has its own copy of these members.
Access requires an object: To access non-static members, you must first create an instance of the class.
Memory usage: Non-static members are created separately for each object, meaning each instance can have its own unique values.
Use case: Non-static is used when you need distinct data for each instance of the class.
Example:
class MyClass {
int nonStaticVar = 5;
void nonStaticMethod() {
System.out.println("This is a non-static method.");
}
}
public class Test {
public static void main(String[] args) {
// Creating an instance of the class
MyClass obj = new MyClass();
// Accessing non-static members
obj.nonStaticMethod();
System.out.println(obj.nonStaticVar);
}
}
out put;
This is a non-static method.
5
What is an object in Java ?
A class is a blueprint for creating objects, providing initial values for member variables and implementations of behaviors (methods). An object is an instance of a class, representing a specific entity with a defined state and behavior.
Here are the key characteristics and aspects of an object in Java:
Instance of a Class:
An object is created from a class, inheriting its attributes (data or state) and methods (behaviors or actions).
State:
The state of an object is represented by its attributes, which are variables defined within the class. These attributes hold the data specific to that particular object.
Behavior:
The behavior of an object is represented by its methods, which are functions defined within the class. These methods define the actions an object can perform or the operations that can be performed on its data.
Identity:
Each object has a unique identity, allowing it to be distinguished from other objects, even if they are instances of the same class and have the same state.
Encapsulation:
Objects encapsulate their data and methods, meaning the internal details of an object are hidden from the outside world, and interaction occurs through defined interfaces (methods).
java.lang.Object Class:
Every class in Java implicitly or explicitly inherits from the java.lang.Object class. This means that all objects in Java have access to the methods defined in the Object class, such as equals(), hashCode(), toString(), wait(), and notify().
method ;
Key characteristics of method overloading:
Same Method Name:
All overloaded methods within a class must share the same name.
Different Parameter Lists:
The distinguishing factor between overloaded methods is their parameter lists. This difference can be in:
The number of parameters: For example, add(int a, int b) and add(int a, int b, int c).
The data types of parameters: For example, display(int a) and display(String a).
The order of parameters: For example, print(int a, String b) and print(String b, int a).
Return Type:
The return type of overloaded methods can be the same or different. The return type alone is not sufficient to differentiate overloaded methods; the parameter list must be different.
Access Modifiers and Exceptions:
Overloaded methods can have different access modifiers (e.g., public, private) and can declare different checked exceptions.
Example:
Java
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add three integers (overloaded)
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two doubles (overloaded)
public double add(double a, double b) {
return a + b;
}
}
Retun type;
In Java, the return type of a method specifies the type of value that the method will send back to the calling code after its execution. This return type is declared in the method signature before the method
The possible return types in Java include:
void: Used when a method does not return any value. For example, a method that simply prints output to the console or modifies the state of an object without returning a result.
Java
public void printMessage() {
System.out.println("Hello!");
}
Primitive Data Types: Methods can return any of Java's eight primitive data types:
byte
short
int
long
float
double
char
boolean
Java
public int add(int a, int b) {
return a + b;
}
Class Types (Objects): Methods can return instances of any Java class, including built-in classes (like String, ArrayList, Scanner) or custom classes defined by the programmer.
Java
public String getName() {
return "John Doe";
}
public MyObject createObject() {
return new MyObject();
}
Interface Types: Methods can also return objects that implement a specific interface. In such cases, the returned object must be an instance of a class that implements the declared interface.
Java
public MyInterface getImplementation() {
return new MyInterfaceImpl(); // MyInterfaceImpl implements MyInterface
}
The return keyword is used within the method body to send back the specified value (or to simply exit the method if the return type is void). The type of the value returned must match the declared return type of the method.
local & Global variables;
In Java, the concepts of "local" and "global" variables are understood in terms of their scope and lifetime within a program.
Local Variables:
Declaration:
Declared within a method, constructor, or a specific block of code (e.g., if block, for loop).
Scope:
Accessible only within the block or method where they are declared. They are not visible or usable outside that specific scope.
Lifetime:
Created when the method or block is entered and destroyed when the method or block exits.
Initialization:
Must be explicitly initialized before use. They do not have default values.
Global Variables (Instance Variables and Class/Static Variables):
In Java, there isn't a direct concept of a "global variable" in the sense of being accessible from anywhere in the entire program without any class association. Instead, variables with broader scope are categorized as:
Instance Variables (Non-static Fields):
Declaration: Declared within a class, but outside of any method, constructor, or block.
Scope: Accessible by all methods and constructors within the same class. To access them from outside the class, an object of that class must be created.
Lifetime: Created when an object of the class is instantiated and destroyed when the object is garbage collected.
Initialization: Automatically initialized to default values if not explicitly assigned (e.g., 0 for numeric types, false for boolean, null for objects).
Class Variables (Static Fields):
Declaration: Declared within a class, outside of any method, constructor, or block, and marked with the static keyword.
Scope: Accessible by all methods and constructors within the same class, and can be accessed directly using the class name from outside the class (e.g., ClassName.staticVariable).
Lifetime: Created when the class is loaded into memory and persists as long as the class remains loaded. There is only one copy of a static variable per class, regardless of how many objects are created.
Initialization: Automatically initialized to default values if not explicitly assigned.
Key Differences and Usage:
Local variables are used for temporary data within a specific operation.
Instance variables store data unique to each object of a class.
Class variables store data shared among all objects of a class or data associated with the class itself rather than individual instances.
Encapsulation principles in Java emphasize minimizing the scope of variables to improve code maintainability and prevent unintended side effects. Therefore, using local variables is generally preferred over instance or class variables unless a wider scope is truly necessary.
Top comments (0)