0% found this document useful (0 votes)
3 views19 pages

JAVA

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

JAVA

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

http://www.instanceofjava.com/p/interview-questions.

html

JAVA
Thread: Implementing runnable interface or extending the Thread Class

Exception Handling:

An exception is an abnormal condition which occurs at the time of program execution.

Errors are abnormal conditions that happen in case of severe failures, these are not handled
by the Java programs.

The main advantage of exception handling is to maintain the normal flow of the application.
In Java, all exception and errors types are classes and sub classes that implements Throwable
interface

Checked Exception can be identified at compile time. The classes which directly
inherit Throwable class except RuntimeException and Error are known as checked exceptions For
Example : ClassNotFoundException, SQLException and RemoteException etc.

Unchecked exception not identified at compile time but they occurred at runtime. All Exceptions
which are sub class of RuntimeException are called as Unchecked Exception. For
Example: NullPointerException, ArithmaticException and ArrayOutOfBoundException etc.
Throw VS Throws:

Throwing a single exception and JVM will handle it


void myMethod() {
//Throwing single exception using throw
throw new ArithmeticException("An integer should not be divided by
zero!!");
}
..
Throws:

The calling method will handle the exception

//Declaring multiple exceptions using throws


void myMethod() throws ArithmeticException, NullPointerException{
//Statements where exception might occur
}

OOPS Concept :

https://facingissuesonit.com/2019/09/21/java-oops-concepts/
Details explanation link: https://facingissuesonit.com/2019/09/21/java-oops-concepts/

Object
A physical or logical entity that has state and behavior are known as an object. For
Example Pen, Paper, computer, watch fan, etc.
An Object is an instance of a class. It contains an address and takes some space in heap
memory. Communication between objects happens without knowing the detail of each other only
condition is the type of message accepted and the type of response returned should be
compatible.
For Example, A car is an object because it has states like color, make, model, engine, etc. as
well as behaviors like speed, accelerator, music, etc.

Class
The collection of objects is called a class. Class is the blueprint of an object from which object
created. Class doesn’t consume space.

For Example, Person is class and “Saurabh Gupta” is the object of that class.

Inheritance
Inheritance is a process where child class acquired all the properties and behaviors of the
parent class. Inheritance is used when one object is based on another object. Here parent class
also called a superclass and child class called as a subclass.
For Example, Person is Parent class and Employee is a subclass of Person. which acquired
all the properties and behavior of Person class.

Advantage of inheritance
 Code Reusability
 Runtime Polymorphism

Points about Inheritance


 extends the keyword used to implement inheritance.
 Java doesn’t support multiple inheritances. It’s possible by implementing multiple
interfaces.
 Inheritance has an “IS-A” relationship.

Polymorphism
Polymorphism (more-form) means the ability to take more than one form. It’s used when one
task needs to perform in different ways.

For Example, areas of shape are having different formulae for each same like rectangle,
square, circle, etc.
Polymorphism can be achieved in two ways:

1. Runtime Polymorphism (Method Overriding)


2. Compile-time Polymorphism (Method Overloading)

Abstraction
Abstraction is a concept to show only essential detail

i.e hide internal detail and show functionality in simple terms. To achieve abstraction in Java, use
abstract class or interface.

Example: In ATM we don’t know how internally work. In Car don’t know about the internal
mechanism.
Abstraction can be achieved by two ways:
 Abstract Class (0% to 100%)
 Interface (100%)

Encapsulation
Binding (or wrapping) of data and function in a single unit is called encapsulation. The
encapsulation technique is used to achieve abstraction in oops.

In Java, A class is an example of encapsulation where abstraction level depends on access


modifiers(private, protected and public) uses for fields and methods. A class is considered as
fully encapsulated if all data members are private.

Collection is an interface while Collections is a utility


class.

The size() method is available for collections, length works with arrays in Java.
System.out.println():
System is a class in java.lang package and out is ref variable of printstream class and
println is a method here
The protected access modifier provides access within the package and
outside the package through inheritance only

 variables in interface are final, public and static.


Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default public abstract (only method
signature, no body).
interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

class Bicycle implements Vehicle{

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}

Stack and Heap Memory:


1. Heap contains Objects (may also contain reference variables)
2. Stack contains methods, local variables and reference variables
Java Heap space is used by java runtime to allocate memory to
Objects and JRE classes. Whenever we create an object, it’s always
created in the Heap space.
Garbage Collection runs on the heap memory to free the memory
used by objects that don’t have any reference. Any object created in
the heap space has global access and can be referenced from
anywhere of the application.

Stack memory is always referenced in LIFO (Last-In-First-Out) order.


Whenever a method is invoked, a new block is created in the stack
memory for the method to hold local primitive values and reference
to other objects in the method.
As soon as the method ends, the block becomes unused and
becomes available for the next method.
Stack memory size is very less compared to Heap memory.
https://www.journaldev.com/4098/java-heap-space-vs-stack-memory

package com.journaldev.test;

public class Memory {

public static void main(String[] args) { // Line 1


int i=1; // Line 2
Object obj = new Object(); // Line 3
Memory mem = new Memory(); // Line 4
mem.foo(obj); // Line 5
} // Line 9

private void foo(Object param) { // Line 6


String str = param.toString(); //// Line 7
System.out.println(str);
} // Line 8

}
 As soon as we run the program, it loads all the Runtime classes into
the Heap space. When the main() method is found at line 1, Java
Runtime creates stack memory to be used by main() method thread.
 We are creating primitive local variable at line 2, so it’s created and
stored in the stack memory of main() method.
 Since we are creating an Object in the 3rd line, it’s created in heap
memory and stack memory contains the reference for it. A similar
process occurs when we create Memory object in the 4th line.
 Now when we call the foo() method in the 5th line, a block in the top
of the stack is created to be used by the foo() method. Since Java is
pass-by-value, a new reference to Object is created in the foo()
stack block in the 6th line.
 A string is created in the 7th line, it goes in the String Pool in the
heap space and a reference is created in the foo() stack space for it.
 foo() method is terminated in the 8th line, at this time memory block
allocated for foo() in stack becomes free.
 In line 9, main() method terminates and the stack memory created
for main() method is destroyed. Also, the program ends at this line,
hence Java Runtime frees all the memory and ends the execution of
the program.
Difference between Java Heap Space and
Stack Memory
Based on the above explanations, we can easily conclude the
following differences between Heap and Stack memory.

1. Heap memory is used by all the parts of the application whereas


stack memory is used only by one thread of execution.
2. Whenever an object is created, it’s always stored in the Heap space
and stack memory contains the reference to it. Stack memory only
contains local primitive variables and reference variables to objects
in heap space.
3. Objects stored in the heap are globally accessible whereas stack
memory can’t be accessed by other threads.
4. Memory management in stack is done in LIFO manner whereas it’s
more complex in Heap memory because it’s used globally. Heap
memory is divided into Young-Generation, Old-Generation etc, more
details at Java Garbage Collection.
5. Stack memory is short-lived whereas heap memory lives from the
start till the end of application execution.
6. We can use -Xms and -Xmx JVM option to define the startup size
and maximum size of heap memory. We can use -Xss to define the
stack memory size.
7. When stack memory is full, Java runtime
throws java.lang.StackOverFlowError whereas if heap memory is
full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
8. Stack memory size is very less when compared to Heap memory.
Because of simplicity in memory allocation (LIFO), stack memory is
very fast when compared to heap memory.

Constructor:
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:
This():

Usages of this

https://www.flowerbrackets.com/this-keyword-in-java/

Super():
Uses of super keyword

1. To call methods of the superclass that is overridden in the subclass.

2. To access attributes (fields) of the superclass if both superclass and subclass have attributes with the

same name.

3. To explicitly call superclass no-arg (default) or parameterized constructor from the subclass constructor.

Exceptions and errors both are subclasses of Throwable class. The error indicates a
problem that mainly occurs due to the lack of system resources and our application
should not catch these types of problems. Some of the examples of errors are system
crash error and out of memory error. Errors mostly occur at runtime that's they belong to
an unchecked type.
Exceptions are the problems which can occur at runtime and compile time. It mainly
occurs in the code written by the developers. Exceptions are divided into two
categories such as checked exceptions and unchecked exceptions.

Sr. No. Key Error Exception

1 Type Classified as an unchecked Classified as checked and


type unchecked

2 Package It belongs to java.lang.error It belongs to java.lang.Exception

3 Recoverable/ It is irrecoverable It is recoverable


Irrecoverable

4 It can't be occur at compile It can occur at run time compile time


time both

5 Example OutOfMemoryError ,IOError NullPointerException ,


SqlException

Example of Error
public class ErrorExample {
public static void main(String[] args){
recursiveMethod(10)
}
public static void recursiveMethod(int i){
while(i!=0){
i=i+1;
recursiveMethod(i);
}
}
}

Output
Exception in thread "main" java.lang.StackOverflowError
at ErrorExample.ErrorExample(Main.java:42)
Example of Exception
public class ExceptionExample {
public static void main(String[] args){
int x = 100;
int y = 0;
int z = x / y;
}
}

Output
java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:7)

In the StringTokenizer class, the delimiters can be provided at the time of


creation or one by one to the tokens.

You might also like