OverloadedOperators StaticClassMembers and GarbageCollectionpdf 2024 09 16 11 48 33
OverloadedOperators StaticClassMembers and GarbageCollectionpdf 2024 09 16 11 48 33
Example-1,
int a = 10;
int b = 20;
int c = a + b;
System.out.println(c); // 30
30
Example-2,
String s1 = "Hello";
String s2 = "World";
Hello World
In The First Example + Operator Add Two Integer value but in Second it Add
Two String. This is Called Operator Overloading. In Above Example + operator
is overloaded as it perform different action depends on parameter passed.
It is the only operator overloading that Java supports. Aside from that, user-
defined operator overloading is not supported in Java. The handling of + for
concatenating strings is the only component of Java that comes close to operator
overloading in java.
In Java, static members are those which belongs to the class and you can
access these members without instantiating the class. The static keyword can
be used with methods, fields, classes (inner/nested), blocks.
Static Methods − You can create a static method by using the keyword
static. Static methods can access only static fields, methods. To access static
methods there is no need to instantiate the class, you can do it just using the
class name as –
Example,
Hello
Static Fields − You can create a static field by using the keyword static. The
static fields have the same value in all the instances of the class. These are
created and initialized when the class is loaded for the first time. Just like static
methods you can access static fields using the class name (without
instantiation).
Output
20
Static Blocks − These are a block of codes with a static keyword. In general,
these are used to initialize the static members. JVM executes static blocks
before the main method at the time of class loading.
Output
Hello this is a static block
This is main method
Study Material by Ms Manmeet Kaur
Garbage Collection
Garbage collection in Java is the process by which Java programs
perform automatic memory management. Java programs compile to
bytecode that can be run on a Java Virtual Machine, or JVM for short.
When Java programs run on the JVM, objects are created on the heap,
which is a portion of memory dedicated to the program. Eventually, some
objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.