Java Theory
Java Theory
Class
1. Class is a set of object which shares common characteristics/
behavior and common properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint
or prototype from which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of
methods.
-> A class in java can contain:
• data member
• method
• constructor
• nested class and
• interface
Object
It is a basic unit of Object-Oriented Programming and represents real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by methods of an object. It also reflects the response of an object
with other objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
Ordering It follows the LIFO order. It does not follow any order
because it is a dynamic
memory allocation and
does not have any fixed
pattern for allocation and
deallocation of memory
blocks.
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
These variables are created when the block is entered, or the function is called
and destroyed after exiting from the block or when the call returns from the
function.
The scope of these variables exists only within the block in which the variables
are declared, i.e., we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined
scope.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of
any method, constructor, or block.
As instance variables are declared in a class, these variables are created when
an object of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier, then the default access specifier will be
used.
Initialization of an instance variable is not mandatory. Its default value is 0.
Instance variables can be accessed only by creating objects.
3. Static Variables
Static variables are also known as class variables.
These variables are declared similarly as instance variables. The difference is
that static variables are declared using the static keyword within a class outside
of any method, constructor or block.
Unlike instance variables, we can only have one copy of a static variable per
class, irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed
automatically when execution ends.
Initialization of a static variable is not mandatory. Its default value is 0.
If we access a static variable like an instance variable (through an object), the
compiler will show a warning message, which won’t halt the program. The
compiler will replace the object name with the class name automatically.
If we access a static variable without the class name, the compiler will
automatically append the class name.
Differences between the Instance variables and the
Static variables
Now let us discuss the differences between the Instance variables and the Static
variables:
Each object will have its own copy of an instance variable, whereas we can only have
one copy of a static variable per class, irrespective of how many objects we create.
Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of the instance variable. In the case of a static
variable, changes will be reflected in other objects as static variables are common to
all objects of a class.
We can access instance variables through object references, and static variables can
be accessed directly using the class name .
Now, The space in the heap Memory is created but the question is how to access that
space?.
Then, We create a Pointing element or simply called Reference variable which simply points
out the Object(the created space in a Heap Memory).
Constructors in Java
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.
The default constructor is used to provide the default values to the object
like 0, null, etc., depending on the type.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class The method name may or may not
name. be same as the class name.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance
of a class.
o A static method can access static data member and can change the value
of it.
single,
multilevel and
hierarchical.
In Java, Method Overloading is not possible by changing the return type of the
method only.
Interfaces in Java
Serializable,
Cloneable
and Remote interface. All these interfaces are empty interfaces
Platform Independent
Java is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language.
1) What is Java?
Java is the high-level, object-oriented, robust, secure programming
language, platform-independent, high performance, Multithreaded, and
portable programming language. It was developed by James Gosling in
June 1991. It can also be known as the platform as it provides its own JRE
and API.
Class - A logical entity that defines the blueprint from which an object
can be created or instantiated.
In HashMap, null values are allowed for key and values, whereas in
ConcurrentHashMap null value is not allowed for key and value,
otherwise we will get Run-time exception
saying NullPointerException.
An abstract class can have a method The interface has only abstract methods.
body (non-abstract methods).
An abstract class can have the The interface cannot have the constructor.
constructor.
An abstract class can have static The interface cannot have static methods.
methods.
You can extend one abstract class. You can implement multiple interfaces.
The abstract class can provide the The Interface can't provide the
implementation of the interface. implementation of the abstract class.
An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}
o By providing only the setter or getter method, you can make the class
read-only or write-only. In other words, you can skip the getter or setter
methods.
o It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the logic
inside the setter method. You can write the logic not to store the negative
numbers in the setter methods.
o It is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.
o The encapsulate class is easy to test. So, it is better for unit testing.
o The standard IDE's are providing the facility to generate the getters and
setters. So, it is easy and fast to create an encapsulated class in Java.
Functional Interface
A functional interface is an interface with only one abstract method. This
means that the interface implementation will only represent one
behavior. Examples of a functional interface in Java are:
java.lang.Runnable
java.util.Comparator
java.util.concurrent.Callable
java.io.FileFilter
An important point to remember is that the functional interface can have
a number of default methods but only one abstract method.
An interface with exactly one abstract method is called Functional
Interface. @FunctionalInterface annotation is added so that we can mark an interface as
functional interface. It is not mandatory to use it, but it’s best practice to use it with functional
interfaces to avoid addition of extra methods accidentally. If the interface is annotated
with @FunctionalInterface annotation and we try to have more than one abstract
method, it throws compiler error. The major benefit of java 8 functional interfaces is that we
can use lambda expressions to instantiate them and avoid using bulky anonymous class
implementation. Java 8 Collections API has been rewritten and new Stream API is
introduced that uses a lot of functional interfaces. Java 8 has defined a lot of functional
interfaces in java.util.function package. Some of the useful java 8 functional
interfaces are Consumer, Supplier, Function and Predicate. You can find more detail
about them in Java 8 Stream Example. java.lang.Runnable is a great example of
functional interface with single abstract method run(). Below code snippet provides some
guidance for functional interfaces:
HTTPS
HTTPS is an abbreviation of Hypertext Transfer Protocol Secure. It is a secure extension
or version of HTTP. This protocol is mainly used for providing security to the data sent
between a website and the web browser. It is widely used on the internet and used for secure
communications. This protocol uses the 443 port number for communicating the data.
This protocol is also called HTTP over SSL because the HTTPS communication protocols
are encrypted using the SSL (Secure Socket Layer).
Those websites which need login credentials should use the HTTPS protocol for sending the
data.
3. The data which is transferred in HTTP is plain 3. The data which is transferred in HTTPS is
text. encrypted, i.e., ciphertext.
4. By default, this protocol operates on port 4. By default, this protocol operates on port
number 80. number 443.
5. The URL (Uniform Resource Locator) of HTTP 5. The URL (Uniform Resource Locator) of HTTPS
start with http:// start with https://
8. The speed of HTTP is fast as compared to 8. The speed of HTTPS is slow as compared to
HTTPS. HTTP.
10. Examples of HTTP websites are Educational 10. Examples of HTTPS websites are shopping
Sites, Internet Forums, etc. websites, banking websites, etc.
Advantages of HTTPS
Following are the advantages or benefits of a Hypertext Transfer Protocol Secure (HTTPS):
Disadvantages of HTTPS
The big disadvantage of HTTPS is that users need to purchase the SSL certificate.
The speed of accessing the website is slow because there are various complexities in
communication.
Users need to update all their internal links.
OOPS Concept
Q2 What is an interface?
No, it is not possible to override the static method in Java. The reason is
a. The static method belongs to the class level, not the object level. In
method overriding, it is the object that decides which method is to be
called.
b. Also, for class-level methods i.e static methods, the type reference
decides which method is called not the object being referred. It concludes
the method called is determined at compile time.
If a child class defines a static method with the same signature as a static
method in the parent class, then the method in the child class hides the
method in the parent class.
Q5 What is the Dynamic method dispatch in Java?
Exception Handling
Q6 What is the difference between Checked and Unchecked
Exception in Java?
No, there is one scenario where the finally block does not execute. When
you run System.exit(0) in the try or catch block, then finally block does not
execute.
Collection
Q10 What is the difference between Array and ArrayList? Which is
better?
The detailed answer to the difference between Array and ArrayList can be
found here.
The detailed answer to the difference between LinkedList and ArrayList can
be found here.
This is one of the most important questions that every java developer must
know. Find the detailed answer to How HashMap works internally in
Java here.
The detailed answer to the difference between fail-fast and fail-safe can be
found here.
You can find all the differences between the wait and sleep method here.
String
Q21 What is the difference between String, StringBuilder, and
StringBuffer in Java?
Serialization
Q24 What is the marker interface? Name some marker interfaces in
Java?
String: String is an immutable class, which means that once a String object is
created, its value cannot be changed. This makes String objects thread-safe and ideal for
situations where the value of the string will not change frequently. You can use String
objects for storing constant strings, such as error messages, application labels, and other
similar data.
Methods, on the other hand, are used to perform specific actions or operations on an
object. They may or may not change the object's state.
So while constructors are used to set up an object's initial state, methods are used to
interact with that state, modify it, or retrieve information about it.
In short, constructors are used to initialize the object's state, while methods are used
to perform actions on that state. Both constructors and methods have important
roles to play in object-oriented programming.
In Java, the equals() method and hashCode() method are two important methods that are
used to implement object equality and are related to each other.
The equals() method is used to determine whether two objects are equal in value. By default, the
equals() method compares the memory addresses of the two objects to determine equality,
which means that two objects that have the same values but are in different memory locations will
not be considered equal. However, developers can override the equals() method in their classes
to compare the values of the objects instead of the memory addresses.
The hashCode() method is used to generate a hash code value for an object. A hash code is a
numeric value that represents the contents of an object. It is used by data structures such as Hash
Sets and Hash Maps to quickly identify if an object is already present in the collection or not. The
hashCode() method returns an integer value that is used as the hash code for the object.
The equals() and hashCode() methods are related to each other because if two objects are
equal according to the equals() method, their hash codes must be equal too. This is because if
two objects have the same values, they should produce the same hash code. Therefore, if the
equals() method is overridden, the hashCode() method should also be overridden to ensure
that equal objects produce the same hash code.
VM Memory Structure
JVM creates various run time data areas in a heap. These areas are used
during the program execution. The memory areas are destroyed when JVM
exits, whereas the data areas are destroyed when the thread exits.
Method Area
Method Area is a part of the heap memory which is shared among all the
threads. It creates when the JVM starts up. It is used to store class
structure, superclass name, interface name, and constructors. The JVM
stores the following kinds of information in the method area:
Heap Area
Heap stores the actual objects. It creates when the JVM starts up. The user can
control the heap if needed. It can be of fixed or dynamic size. When you use a
new keyword, the JVM creates an instance for the object in a heap. While the
reference of that object stores in the stack. There exists only one heap for each
running JVM process. When heap becomes full, the garbage is collected.
Stack Area
Stack Area generates when a thread creates. It can be of either fixed or
dynamic size. The stack memory is allocated per thread. It is used to store
data and partial results. It contains references to heap objects. It also
holds the value itself rather than a reference to an object from the heap.
The variables which are stored in the stack have certain visibility, called
scope.
PC Registers
Each thread has a Program Counter (PC) register associated with it. PC
register stores the return address or a native pointer. It also contains the
address of the JVM instructions currently being executed.
o Serial GC: It uses the mark and sweeps approach for young and old
generations, which is minor and major GC.
o Parallel GC: It is similar to serial GC except that, it spawns N (the number
of CPU cores in the system) threads for young generation garbage
collection.
o Parallel Old GC: It is similar to parallel GC, except that it uses multiple
threads for both generations.
o Concurrent Mark Sweep (CMS) Collector: It does the garbage
collection for the old generation. You can limit the number of threads in
CMS collector using XX:ParalleCMSThreads=JVM option. It is also
known as Concurrent Low Pause Collector.
o G1 Garbage Collector: It introduced in Java 7. Its objective is to replace
the CMS collector. It is a parallel, concurrent, and CMS collector. There is
no young and old generation space. It divides the heap into several equal
sized heaps. It first collects the regions with lesser live data.
Miscellaneous
Q27 What is the difference between final, finally, and finalize in Java?
The difference between final, finally and finalize is answered in detail here.
Q28 What are the different ways to call the garbage collector in Java?
If a variable is marked as volatile then this variable is read from the main
memory instead of cache memory.
Coding