You are on page 1of 78

Why Pointer feature is eliminated from Java?

There are mainly three reasons to eliminate the pointer concept from Java.
They are as follows:
1. The concept of Pointer leads to confusion for a programmer.
2. Pointer may break a program easily. For example, when we add two
pointers, the program can crash immediately.

3. The use of Pointer feature can break security because harmful programs
like virus and other hacking programs can be developed using pointer.
Because of the above reasons, the pointer feature has been completely
eliminated from Java technology.
Advantages of Java Bytecode

Java Bytecode has mainly two advantages that are as follows:


1. Byte code makes the java program portable across the different hardware
(processors) and operating system platforms. The poly requirement is that
Java Virtual Machine must be installed on them.
2. The second advantage is that it increases security of code because of
control of JVM over the execution of byte code file.

Difference between Bytecode vs Machine code

The main difference between the byte code and machine code is that byte
code can be run only on JVM whereas machine code is a set of instructions in
machine language that can be directly run by the CPU.
Difference between .java and .class

Java source code file (with a .java extension) are compiled into bytecode (with
a .class extension), which is then interpreted and executed by a Java
processor called JVM.

Key points:
1. A bytecode in Java is a set of byte-long instructions that Java compiler
produces and Java interpreter (JVM) executes.
2. When Java compiler compiles .java file, it generates a series of bytecode
(machine independent code)and stores them in a .class file.
3. JVM then interprets and executes the byte code stored in the .class file and
converts them into machine code.
4. The byte code remains the same on different platforms such as Windows,
Linux, and Mac OS.
Interpreter vs Compiler: How is Interpreter different
from a compiler in Java?

Here, we have listed the key differences between an interpreter and a


compiler. They are as follows:
1. An interpreter translates program line by line whereas, a compiler translates
the entire program together.
2. Execution process of Interpreter is slower whereas, execution process of
the compiler is faster.
3. Interpreter takes less compile-time whereas compiler takes more time.
4. It will not produce intermediate object code. Compiler produces
intermediate object code.
5. Interpreter compiles the program until an error is found. Compiler shows all
the errors once at the end of the compilation.
6. Python, PHP, Ruby, and Perl use an interpreter. Java, C++, Scala, and C
use a compiler.
Difference between C vs Java
1. Invention:
● C was invented by Dennis M. Ritchie in 1972 at Bell Lab of USA.
● Java was invented by James Gosling in 1995.

2. Types of language:
● C is a structural and procedural programming language.
● Java is a purely object-oriented programming language because
everything in java is an object. All the program code and data
remain within classes and objects.

3. Language level:
● C is a middle-level programming language because it combines
both machine-level and high-level languages.
● Java is a high-level programming language because the
translation of program source code takes place into machine
language using compiler or interpreter.

4. Approach:
● C language follows the top-down approach to design the
application program.
● Java language follows the bottom-up approach to design the
application program.

5. Translation:
● C is considered a compiled language because it converts the code
into machine language so that it could be understood by the
machine or system.
● Java is an interpreted language because the source code is first
converted into bytecode by the compiler and then that bytecode is
then executed by the JVM (Java Virtual Machine).
6. Platform Dependency:
● C is platform-dependent or system-dependent.
● Java is platform-independent. Program source code can be easily
moved from one computer system to another, anywhere, and
anytime.

7. Keywords:
● There are 32 keywords in the C language.
● Java has 50 keywords.

8. OOPs Concepts:
● C does not follow OOPs concepts mechanism.
● Java follows OOPs concepts mechanism.

9. File Extension:
● Source code file is saved with the extension .c.
● In Java, source code file is saved with the extension .java.

10. Variable Declaration:


● In C programming, variables are declared at the beginning of the
block.
● We can declare variables anywhere in Java programming.

11. Security:
● C is not secure.
● Java is a fully secured language.

12. Overloading:
● C does not support overloading functionality.
● Java supports method overloading concept that helps in code
readability.

13. Pointers:
● Pointer concept is supported by the C programming language.
● Java does not support pointers.

14. Call by value and Call by reference:


● C supports both call by value and call by reference.
● Java supports only call by value.

15. Robust:
● C is not robust.
● Java is robust.

16. Exception handling:


● Exception handling concept is not supported by C language.
● Java supports exception handling concept.

17. Inheritance:
● There is no inheritance concept present in the C language.
● Java supports inheritance that helps in code reusability.

18. Threading:
● There is no concept of threading in C language.
● Java programming language supports the concept of threading.

19. Memory Management:


● C programming language does not maintain memory, internally.
● Java maintains memory, internally.

20. Preprocessors:
● C language supports Preprocessors.
● Java does not support Preprocessors.

21. Union and Structure:


● Union and structure data types are supported by C.
● Whereas Java does not support union and structure data types.

22. Storage classes:


● C supports the storage classes.
● Whereas Java technology does not support the storage classes.

23. Virtual keywords:


● C language supports virtual keywords.
● Whereas virtual keywords are not supported by Java.

24. Go-to statements:


● Go-to statements are supported by C language.
● Whereas Java does not supports go-to statements.

25. Default members:


● Default members of C are public whereas default members of
Java are private.

26. Applications:
● C programming language is mainly used to develop system
applications and firmware.
● Whereas Java programming language is mainly used to develop
enterprise applications and web-based applications.

Main Key Difference between C++ vs Java :

a) C++ uses compiler only whereas Java uses both compiler and interpreter.
b) C++ supports both operator overloading and method overloading whereas
Java only supports method overloading, not operator overloading.
c) C++ has manual object management with the help of new and delete
keywords while Java has automatic built-in garbage collection.
d) C++ supports structures and unions whereas Java doesn’t support
structures and unions.
e) C++ supports pointers while Java doesn’t support pointers.
Q1) Which one is better C++ or Java?
Ans: Perhaps, it is difficult to say which is better. Both C++ and Java have
their own features, merits, and demerits.
C++ is a highly evolved language and is mostly good for system programming
with advanced features like templates and containers. In fact, C++ can do
anything in systems development from enterprise to gaming. We cannot do it
with Java.
Java is the most widely used to develop desktop applications, gaming, web
servers, and client-side web applications. It is also known as a native
language of the Android operating system that operates on Android phones
and tablets.
It’s also easier to find a Java developer than a “harder” language such as C+
+. Thus, the choice between C++ vs Java totally depends on which kind of
application we are developing.
So, before going to choose between better: C++ and Java, First, evaluate
beforehand the pros and cons of both the languages and then decide which is
the best programming language to develop your application should be.

Q2) Is C++ harder than Java?


Ans: If you learned the basics of C language then C++ will not be difficult for
you because it is just an extension of C with some advanced features.
But Java is easier to perceive without knowing C++. Frankly speaking,
learning of any programming language depends on your practice.

Q3) Can we learn Java without knowing C or C++?


Answer: Yes, surely! No need to learn C or C++ to learn Java. In fact, the
syntax of Java is easier than C++ or C.

Q4) Is C++ similar to Java?


Answer: In some ways, Yes but in some ways, No because both C++ and
Java are object-oriented programming languages. They can be used for
application development. They have similar syntax.
But when we move on to other topics like memory management, inheritance,
polymorphism, etc., C++ and Java are totally different. Similarly, when we
come to primitive data types, object handling, pointers, etc. both languages
are different.
Difference between Class and Object in Java

There are the following differences between class and object in java. They are
as follows:
1. A class is a user-defined data type whereas an object is an instance of
class data type.
2. A class generates objects whereas an object gives life to a class.
3. Classes do not occupy memory location but objects occupy memory
location.
4. Classes cannot be manipulated due to not available in the memory location
but objects can be manipulated.

Can we call Class as Data type in Java?

Yes, a class is also considered a user-defined data type. This is because a


user creates a class.

For which purpose we create an object of class in Java


We create an object in Java applications because of three reasons. They are
as follows:
1. Since Java is a purely object-oriented programming language. So
Everything is done in the form of objects only. Therefore, objects are required
in the Java programming language.
2. To store data temporarily in Java application, we require to create an
object. The object provides temporary storage for our data.
3. In Java, By creating an object, we can call the members of one class from
another class. It is useful when we need to use common code in every class
again and again.
4. To access members of any particular class, we have to create an object of
the respective class
Whenever we create an object in any program, the Object reference variable
is automatically generated. By using this object reference variable only, we
can access the members of a particular class.
The reference variable must have a reference value. The Dot(.) operator gives
you to access an object’s state and behavior (instance variables and
methods). These are the reasons for which we create objects in Java
programs.

How many ways to create an object in Java

There are several ways to create an object of class in Java. They are as
follows.
1. Using the new keyword
2. Using Class.forName
3. Using Clone.
4. Using Object Deserialization.
5. Using ClassLoader.
Difference between Primitive and Non-primitive Data
types in Java

1. Primitive data types are predefined in Java whereas non-primitive data


types are created by programmers. They are not predefined in Java.
2. In primitive data type, variables can store only one value at a time whereas,
in non-primitive data type, we can store multiple values either the same type
or different type or both.
3. All the data for primitive type variables are stored on the stack whereas, for
reference types, the stack holds a pointer to the object on the heap.
Difference between while loop and do-while loop

The difference between while loop and do-while loop in Java is as follows:
1. In the case of while loop, first test condition is verified and then executes
the statements inside the while block.
In the case of do-while loop, first statements inside do block are executed and
then the test condition is verified.
2. If the test condition is false for first time, then block of statement executed
zero times.
If the test condition is false for the first time, then the block of statement
executed at least once time.
3. In the while syntax, while statement is at the top.
In the do-while syntax, while statement is at the bottom.
Key points:
1. While importing another package, package declaration must be the first
statement and followed by package import.
2. A class can have only one package statement but it can be more than one
import package statement.
3. import can be written multiple times after the package statement and before
the class statement.
4. You must declare the package with root folder name (No subfolder name)
and the last file name must be class name with a semicolon.
5. When you import, it does mean that memory is allocated. It just gives the
path to reach the file.
Why cannot Static method directly access non-static
members?

We cannot directly access non-static members from a static method. That is,
we cannot directly call instance members within a static area because there is
a logical concept behind such restriction.
Static members such as static variables, methods, or blocks are linked with
the class. Therefore, they get memory only once when the class is loaded in
the memory.
But non-static members like instance variables, method, or block get memory
after the object creation of the class.
Therefore, If we call any non-static members from the static area, it means
that when the class is loaded in the memory, the static members also loaded
and it will look for non-static members which are not in existence because we
have not created an instance till now. Hence there is ambiguity.
That’s why we cannot call the non-static member from the static area. A non-
static method can access static members in Java. we will discuss in the static
tutorial.
Since static method cannot access directly the non-static members but if we
create the object of the class within the static method, In this case, we can
access non-static members within the static method.
Why public static void main in Java?

Basically, the public static void main(String [ ] args) acts as an entry point to
start the execution of Java application program. That’s why we use/write
public static void main in java program.

Why do we need to declare main method as static in


Java?

The main method is declared as static. It is called by JVM when we run a


class. The JVM does not know how to create an object of a class. It needs a
standard way to start the execution of a program.
Therefore, the main method is declared as static so that the JVM can call it
using the class name which is passed on the command line.

Why main method is declared as static in Java?

If we do not declare the main method as static, it will be considered as an


instance method. The code will be compiled successfully without generating
any error message. But at runtime, the code will generate an exception
named: “NoSuchmethodError: main”.

How to call main method in Java?

The main method is called by JVM when we run a class.

Can we have more than one main() method in class?

Yes, a class can have any number of main() methods but the execution
always starts from public static void main(String[ ] args) only. Let’s take an
example program where we will declare more than one method.
Can we execute a program without main() method in
Java?

Yes, we can execute a program without main() method in Java in the previous
version of JDK. One of the ways is a static block. But from onwards JDK 1.7
and above, is not possible.

Can we overload main method in java?

Yes, we can overload the main() method but we cannot override it. We can
declare any number of main() method in a class, but the method signature
must be different. Let’s make a program where we will overload the main
method.
Key Points:
1. public static void main(String args[ ]) is a line at which the program will start
executing.
2. main() method in java is always called by JVM (Java Virtual Machine)
before any objects are created.
3. It does not return any value.
4. Since Java is case-sensitive, Main is different from main. If you type Main
instead of main, java compiler would still compile your program but java will
report an error because it would not find main() method.
5. If a program does not contain the main method in a class, Java compiler
will compile it but cannot run it.
6. Java main() method can be overloaded but cannot override it.
Difference between Argument and Parameter in Java

The difference between parameter and argument is sometimes confusing in


Java because many programmers often, incorrectly, use them
interchangeably but they both have different meanings.
So, let’s see the actual difference between them.
1. A parameter is a variable in the definition of a method whereas an
argument is an actual value of this variable that is passed to the method’s
parameter.
2. A parameter is also called formal parameter whereas an argument is also
called actual parameter.
3. During the time of call, each argument is always assigned to the parameter
in the method definition whereas parameters are local variables that are
assigned by value of the arguments when method is called.

Call by Value (Pass by Value) in Java


“Call by value” in Java means that argument’s value is copied and is passed
to the parameter list of a method.
That is, when we call a method with passing argument values to the
parameter list, these argument values are copied into the small portion of
memory and a copy of each value is passed to the parameters of the called
method.
When these values are used inside the method either for “read or write
operations”, we are actually using the copy of these values, not the original
argument values which are unaffected by the operation inside the method.
That is, the values of the parameters can be modified only inside the scope of
the method but such modification inside the method doesn’t affect the original
passing argument.
When the method returns, the parameters are gone and any changes to them
are lost. This whole mechanism is called call by value or pass by value.

Call by Reference (Pass by Reference) in Java


In Java “Call by Reference” means passing a reference (i.e. address) of the
object by value to a method. We know that a variable of class type contains a
reference (i.e. address) to an object, not object itself.

Thus, when we pass a variable of class type as an argument to a method,


actually, a copy of a reference (address) to an object is passed by value to the
method, not a copy of the object itself. This is because Java does not copy the
object into the memory.
Actually, it copies reference of the object into the memory and passes the
copy to the parameters of the called method.
If we change the reference of the object then the original reference does not
get changed because this reference is not original. It’s a copy.

Key Points:
1. Java passes the arguments both primitives and the copy of object reference
by value.
2. Java never passes the object itself.
3. In realtime project, we pass class objects as parameters to method call in
java.
Can we have two methods having same name with different
parameters?

Yes, we can have two methods having the same name with different
parameters in a class. This technique is called method overloading in java.

Can a method be defined inside another method in


Java?

Declaring a method inside another method is called inner method in java but
in the entire Java, the inner method concept is not allowed.
Note: Java supports the inner class concept but does not support the inner
method concept.
Characteristics of Constructor

There are the following characteristics of constructor in java. They are as


follows:
1. Constructor’s name must be the same as the name of the class in which it
is declared and defined.
2. The constructor should not have any return type even void also because if
there is a return type then JVM would consider as a method, not a
constructor.
Compiler and JVM differentiate constructor and method definitions on the
basis of the return type.
Suppose you define the method and constructor with the same name as that
of the class name then JVM would differentiate between them by using return
type.
3. Whenever we create an object/instance of a class, the constructor will be
automatically called by the JVM (Java Virtual Machine).
If we don’t define any constructor inside the class, Java compiler automatically
creates a default constructor at compile-time and assigns default values for all
variables declared in the class.
The default values for variables are as follows:
a. Numeric variables are set to 0.
b. Strings are set to null.
c. Boolean variables are set to false.
4. Java constructor may or may not contain parameters. Parameters are local
variables to receive value (data) from outside into a constructor.
5. A constructor is automatically called and executed by JVM at the time of
object creation. JVM first allocates the memory for variables (objects) and
then executes the constructor to initialize instance variables.

6. It is called and executed only once per object. This means that when an
object of a class is created, constructor is called. When we create second
object then the constructor is again called during the second time.

How to call Constructor in Java

There are the following ways to call a constructor in java.


1. A a = new A(); // Here, A is name of class.
2. new A(); // It is calling A() constructor.
3. super();
4. this();
5. class.forName(“com.amol.A”).newInstance();
When we create an object of class by using new keyword, a constructor is
automatically called by JVM. After creating the object of the class, we cannot
call the constructor again.
The syntax to create an object of class is as follows:
Consider the following example.
School sc = new School(); // Here, default constructor is called.

Where,
School ➝ Name of the class.
sc ➝ Object reference variable which stores the address of the object in the stack
memory.
School() ➝ Constructor of class.
new ➝ It is a special keyword that allocates the memory to store objects whose type
is specified by a constructor. After allocation of memory, it calls constructor to
initialize objects, which are stored in the heap ( a region of memory for storing
objects).
When the constructor ends, a new keyword returns memory addresses to the
object so that it can be accessed from anywhere in the application.

Types of Constructors in Java

Basically, there are two types of constructors in java. They are as:
1. Default Constructor (No-argument constructor)
2. Parameterized Constructor (Argument constructor)
Difference between Constructor and Method in Java

Constructor vs Method

S Constructor Method
N

1. Constructor is a special type of method Method is used to expose the


that is used to initialize the state of an behaviour of an object.
object.

2. It has no return type even void also. It has both void and return
type.
3. If we don’t provide any constructor in Method is not provided by the
the class, Java Compiler provides a compiler in any case.
default constructor for that class.

4. Constructor name must be the same as Method name may or may


name of the class. not be the same name as the
class name.

5. The purpose of a constructor is to The purpose of a method is


create an object of a class. to execute the functionality of
the application.

6. They are not inherited by subclasses. They are inherited by


subclasses.

Key Points:
1. The task of a constructor in Java is to initialize instance variables of an
object.
2. A constructor of class is automatically executed by JVM when an object is
instantiated.
3. When an object of class is instantiated, constructor is called before any
methods.
4. If you declare your own constructor, you have to decide what values should
be given to instance variables.
5. this and super keyword must be the first line in the constructor.
6. Constructor overloading is possible but overriding is not possible.
7. It cannot be inherited in the subclass.
8. A constructor can also call another constructor of the same class using
‘this’ and for argument constructor use ‘this(para_list).
9. A Constructor is not a keyword in Java.
10. Java constructor is the third possibility to initialize instance variables in a
class.
1. Can a constructor be private in Java?
2. What is the use of private constructor?
3. How to access or class private constructor?
4. Can we call private constructor?

Visibility of Access Modifier in Java

The below table summarizes the visibility of various access modifiers in java.

Access location Publ Protect Defau Private Priva


ic ed lt protected te

Same class Yes Yes Yes Yes Yes

Subclass in same Yes Yes Yes Yes No


package
Other classes in same Yes Yes Yes No No
package

Subclasses in other Yes Yes No Yes No


package

Non-subclasses in other Yes No No No No


packages

Key of Access modifiers:


Private > Default > Protected > Public
More restrictive ----------------> Less restrictive.
Decreasing
Difference between Instance block and Constructor in
Java

1. Both instance block and constructor will be executed automatically for every
object creation, but instance block will be executed before a constructor.
2. A constructor can take arguments but instance block cannot take any
argument. Hence, we cannot replace the constructor concept with IIB.
3. If we want to perform any activity for every object creation, we have to
define that activity inside the instance block.

Can we access instance members from static area


directly?

Instance members (non-static members) can be accessed only from instance


area directly. But we cannot access it from the static area directly.
In other words, we cannot call instance member from the static member
because a static variable stores values into the memory before the object
creation whereas an instance variable stores into the memory after the object
creation.
So, when we access instance members by static members as they are not
present in the memory, it will give the compile-time error.

Can we access static variables from instance and static


methods?

Yes, static members (static variables) can be accessed from both instance
and static area (i.e. instance and static methods) directly using the class name
or without the class name. But outside the class, we can call only using class
name.

How to access static variable in Java from another


class?

We can access a static variable in Java by using class name from another
class.

How to change value of static variable?

We can change the value of the static variable in java by using a constructor
and static block but not inside a static method.

Advantage of Static variable in Java

Class variable makes program memory efficient. That is, it saves memory. All
static variables are stored in PermGen space of the heap memory.

Difference between Static variable and Instance variable


There are the following differences between static variable (class variable)
and instance variable.
1. A static variable is also known as class variable whereas, instance variable
is also known as non-static variable.
2. Class variable can be accessed inside a static block, instance block, static
method, instance method, and method of the inner class whereas, instance
variable can be accessed inside the instance block, instance method, and
method of the inner class.
3. Class variable is always resolved during compile time whereas, instance
variable is resolved during the runtime.
4. It is not serialized in Java whereas, instance variable is serialized in Java.

Key Points:
1. Static variable (also known as class variable) in Java is simply like another
variable but it is common to all instances of the class.
2. It can be accessed and modified by any other objects of class.
3. A static variable can be directly accessed by class name within static and
non-static methods of the class.
4. It can be used with public and final modifiers to make constant value.
Why Instance variable is not available to Static method?
When we declare a static method in Java, JVM first executes the static
method, and then it creates objects of the class. Since objects are not
available at the time of calling the static method.
Therefore, instance variables are also not available to a static method. Due to
which a static method cannot access an instance variable in the class.

Difference between Static method and Instance method


in Java

There are mainly five differences between static method and instance method.
They are as follows:
1. A static method is also known as class method whereas, the instance
method is also known as non-static method.
2. The only static variable can be accessed inside static method whereas,
static and instance variables both can be accessed inside the instance
method.
3. We do not need to create an object of the class for accessing static method
whereas, in the case of an instance method, we need to create an object for
access.
4. Class method cannot be overridden whereas, an instance method can be
overridden.
5. Memory is allocated only once at the time of class loading whereas, in the
case of the instance method, memory is allocated multiple times whenever the
method is calling.

Can We override Static method in Java in 3 Cases

No, we cannot override static method in Java because a static method is


resolved at compile time by java compiler whereas,

method overriding is resolved at runtime by JVM because objects are only


available at runtime.
We can declare static methods with the same signature in subclass, but they
are not considered as overriding. They are considered a method hiding.

Look at the difference between method overriding and method hiding in the
below figure.

This is one of the most tricky java questions where the interviewer will try to
confuse you. May be interviewer also does not know whether they can
override or overload static methods in Java. Therefore, you do not confuse
and give an exact answer.

Let’s understand from three different cases with example programs where we
cannot override static methods in Java.

Case 1:

Program source code 1:


package overriding;
public class AB
{
static void m1()
{
System.out.println("m1-AB");
}
}
public class ABC extends AB
{
protected void m1()
{
System.out.println("m1-ABC");
}
}
public class TestABC
{
public static void main(String[] args)
{
ABC obj = new ABC();
obj.m1();
}

Explanation:

In this example program, the m1() method is declared as static in the parent
class but not in child class. We are trying to override a static method with a
non-static method (instance method).

So, is it a valid case? No, it is not a valid case for overriding because static
method means class-level method whereas, instance method means object-
level method.

Hence, we cannot override a class-level method with an object-level method.


But if you are trying to override class-level method with instance method, you
will get a compile-time error: “m1() in ABC cannot override m1() in AB;
overridden method is static”.
This is because the compiler detects that you are trying to override a static
method with a non-static method that should be hidden and generates a
compiler error.

Case 2:

Programs source code 2:


package overriding;
public class AB
{
public void m1()
{
System.out.println("m1-AB");
}
}
public class ABC extends AB
{
public static void m1()
{
System.out.println("m1-ABC");
}
}
public class TestABC
{
public static void main(String[] args)
{
AB obj = new ABC();
obj.m1();
}

Explanation:

In this example, m1() method in parent class is an instance method but a


static method in child class.
In this case, java compiler thinks that you are trying to hide a method that
should be overridden and generates a compile-time error: “m1() in ABC
cannot override m1() in AB; overriding method is static”.

So, this case is also not valid for overriding. Therefore, we cannot override an
instance method with a static method.

Case 3:

Program source code 3:


package overriding;
public class AB
{
public static void m1()
{
System.out.println("m1-AB");
}
}
public class ABC extends AB
{
public static void m1()
{
System.out.println("m1-ABC");
}
}
public class TestABC
{
public static void main(String[] args)
{
AB obj1 = new AB();
obj1.m1();
ABC obj2 = new ABC();
obj2.m1();
AB obj3 = new ABC();
obj3.m1();
}

Output:
m1-AB
m1-ABC

m1-AB

Explanation:

In this example program, both parent class and child class methods are static.
We did not get any compile-time error. It seems overriding concept applicable
for static methods but it is not overriding, it is method hiding. How?

Let’s understand the output of the above program.

In method hiding, a method resolution is always resolved by the compiler


based on the reference type. Runtime object does not play any role in the
method hiding concept.

1. obj1.m1(); will call m1() method of class AB because the reference variable
obj1 is the type of AB. Therefore, the output is “m1-AB”.

2. obj2.m1(); will call m1() method of class ABC because the reference
variable obj2 is the type of ABC. Therefore, the output is “m1-ABC”.

3. obj3.m1(); will call m1() method of class AB because the reference variable
obj3 is the type of AB. Therefore, the output is “m1-AB”.

Suppose that it is method overriding then what will be the output?


In this case, the output will be “m1-ABC” because the reference variable obj3
is pointing to the object of class ABC.

We know that in overriding, a method resolution is always resolved by JVM


based on runtime object because objects are only available at runtime.

Key Points:

1. We cannot override a static method as non-static otherwise we will get a


compile-time error.

2. We cannot override a non-static method as static.

Why Static block is executed before Main method?

When we execute a particular class, JVM performs two actions at the runtime.
They are as:
1. JVM loads the corresponding dot class file (byte code) into memory.
2. During the dot class file loading into memory, static block is executed. After
loading the dot class file, JVM calls the main method to start execution.
Therefore, static block is executed before the main method.
In other words, we can also say that static block always gets executed first in
Java because it is stored in the memory at the time of class loading and
before the object creation.

How many times Dot class file is loaded into memory?

Dot class file is loaded into the memory only one time. So, only one time static
block will be executed. Instance block’s execution depends upon the object
creation.
If we create 10 objects, 10 times instance blocks will be executed but the
execution of static block depends upon the class loading. Since the class is
loaded only one time So, static block will be executed only one time.

Can we execute Static block without Main method


inside class?

It is possible to execute static block without a main method inside the class up
to Java 1.5 version but Java 1.6 version onwards, the main method is
mandatory to execute a static block inside the class.
During the dot class file loading, first static blocks are executed and then JVM
calls main method.

Advantage of Static block in Java


The advantages of static initialization block in Java are as follows:
1. Static initialization blocks are used to write logic that you want to execute
during the class loading.
2. They are used to initialize the static variables.

Difference between Static block and Instance block in


Java

The top five differences between instance block and static block in java are as
follows:
1. Static block is also known as a static initialization block whereas instance
block is also known as instance initialization block or non-static block.
2. They execute before the instance block whereas instance block executes
after the static blocks.
3. Only static variables can be accessed inside the static block whereas both
static and non-static variables can be accessed inside the instance block.
4. Static blocks execute when the class is loaded into the memory whereas
instance blocks execute only when instance of the class is created.
5. ‘this’ keyword cannot be used in the static block whereas this keyword can
be used in the instance block.

Key Points:
1. A static block in java can not be declared inside any method.
2. JVM executes a static block on the highest priority basis when the dot class
file is loaded into the memory.
3. If the keyword “static” is missed before block then the block is called non-
static block (instance block) that is executed when class is instantiated.
Key Points:
1. A constructor cannot be final.
2. A block cannot be final.
3. A local final variable must be initialized at the time of declaration.
4. We cannot change the value of a final variable after initialization.
5. A final method cannot be overridden.
6. A final class cannot be extended(inherited).
7. We can create the object for a final class but cannot extend it.
8. If the method parameters are declared as final, the value of these
parameters cannot be changed.

Difference between Nested class and Inner class in


Java

Nested class is a class that is defined inside another class. There are two
types of nested class: static and non-static. Non-static nested class is the
inner class.
Advantages of Inner class

There are basically five advantages of inner class in java. They are as follows:
1. Inner class provides a way to group the classes and interfaces in one place
that logically belongs together.
2. It can directly access all the variables and methods of the outer class
including private.
3. It is used to develop more readable and maintainable code.
4. It needs less code to write.
5. It increases encapsulation.
Restriction on Anonymous Inner class

An anonymous inner class also has the same restriction as to the local inner
class with respect to its members.
1. Anonymous inner class cannot be declared as public, private,
protected, or static.
2. It cannot access local variables of its enclosing scope that are not
declared as final or effectively final.
3. Inside anonymous inner classes, we cannot define any static
variables, methods, or static blocks except for static final constant.
4. We cannot create more than one object of the anonymous inner
class in Java.
5. Since an anonymous inner class has no name. Therefore, we
cannot declare a constructor for it within the class body.
Difference between Normal/Regular class and
Anonymous Inner class

The difference between a normal class and an anonymous inner class in java
is as follows:
1. A normal Java class can implement any number of interfaces
simultaneously but an anonymous inner class can implement only one
interface at a time.
2. A normal Java class can extend a class and can implement any number of
interfaces simultaneously but an anonymous inner class can extend a class or
can implement an interface but not both simultaneously.
3. In a normal Java class, we can define any number of constructors but in an
anonymous inner class, we cannot write any constructor explicitly (because
the name of the class and name of the constructor must be the same but
anonymous inner class not having any name).
Can we declare Main method within Static nested
class?

Yes, we can declare the main method inside a static nested class. A static
nested class can have both static and non-static members including the main
method.
1. Can you declare a class inside a class?
2. Can you declare a class inside an interface?
3. Can you declare an interface inside a class?
4. Can you declare an interface inside an interface?
Answer: If the interviewed person asks the above kind of questions then you
tell a simple answer like this. Anything inside anything is possible with respect
to class and interface. All four combinations are valid.

Use of Static Nested Class in Java

There are the following advantages of using a static nested class in Java.
They are as follows:
1. A static nested class can directly access the static members of its outer
class including private static members.
2. It acts as a direct member of its top-level class, not a member of the
package in which it is declared.
3. Without an existing outer class object, there may be a chance of an existing
static nested class. To access static members of the static nested class, there
is no need for an outer class object.

Difference between Normal inner class and Static


nested class in Java
The difference between normal inner class and static nested class is as
follows:
1. In the case of a normal or regular inner class, without an existing outer
class object, there is no chance of existing inner class object
whereas, in the case of a static nested class, without an existing outer class
object, there may be a chance of existing nested class object.
2. An inner class object is strongly associated with an outer class object
whereas, a static nested class is not strongly associated with an outer class
object.
3. In normal inner class, we cannot declare any static members but in the
static nested class, we can declare a static member including the main
method.
4. Since we cannot declare the main method in the normal inner class,
therefore, we cannot run inner class directly from the command prompt.
But we can declare the main method and can also run the static nested class
directly from the command prompt.
5. A normal inner class can access both static and non-static members of the
outer class directly but from the static nested class, we can access only static
members.

Key points:
1. A class declared inside another class is known as nested classes in java.
2. There are two types of nested classes available in Java: static and non-
static.
3. The member class declared with a static modifier is known as static nested
class.
4. The non-static member class is known as inner class or non-static nested
class.
5. A static nested class is not an inner class in java because it is considered
as top-level class.
6. It can be declared public, protected, package-level, or private to restrict its
accessibility.
7. An instance of a static nested class is created the same way as you create
an instance of a top-level class using the new keyword.

You might also like