0% found this document useful (0 votes)
10 views

Java

Uploaded by

Viknesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java

Uploaded by

Viknesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1.

Differences between JDK, JRE and JVM

The Java Development Kit (JDK) is a software development environment used for developing
and running Java applications and applets. It includes JRE and development tools.
JDK = JRE + Development Tools
JDK has JRE, an interpreter/loader (Java), a compiler (javac), an archiver (jar) and other tools
needed for Java Development.
The Java Runtime Environment (JRE) provides the minimum requirements for
executing/running (not develop) a Java application. It includes JVM, core library classes and
supporting files. JRE is a container and JVM is the content. JRE physically exists. JVM virtually
exists.
JRE = JVM + core library classes
The Java Virtual Machine is responsible for executing a java program line by line, hence it’s also
called as interpreter. It loads, verifies and executes the code.
2.

Comparison Index C++ Java


Platform Platform Dependent Platform Independent
Goto Supports goto statement Doesn’t support goto
Multiple Inheritance Supports Multiple Doesn’t support Multiple
Inheritance Inheritance
Operator Overloading Supports Doesn’t support
Pointers C++ supports pointer. Can Java supports pointer
write programs using internally. Can’t write pointer
pointers program in Java
Compiler and Interpreter Supports compiler only Uses compiler and
Interpreter
Thread Doesn’t have built in support Has built in support for
thread
Call by value and reference Supports both Supports only call by value
Garbage collection We need to free the memory Java has in built Garbage
pointers manually collector

3. Why Java doesn’t have goto statement?


It is present in the keyword list, but it is marked as unused. The main reason behind not to use
the GOTO statement is we can replace it with much more efficient keywords like BREAK and
CONTINUE which provides more efficient language processing. Moreover, multilevel Break and
Continue removes almost every possible reason to use GOTO.
4. What is instance variable in Java?

A variable which is created inside the class but outside the method, is known as instance
variable. Instance variable doesn't get memory at compile time. It gets memory at run time
when object(instance) is created. That is why, it is known as instance variable.

5. Why main method is declared static?

Since main method is like an entry point, JVM doesn’t want to create an instance of main
method every time while running the program. To avoid that we are declaring that as static.

6. Can main method be overloaded?

Yes, but JVM will look for the method declared with public static void main (String args[])
7. Can main method be declared ‘final’?
Yes, main method can be declared final, synchronized, strictfp modifier in the signature.
8. Can main method be declared private, protected?
No, we can’t. It reduces the visibility of main method and it’s not allowed.
9. Why Java doesn’t support Multiple Inheritance?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java. Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class. This will result in compile time error.
10. Why Java doesn’t support call by reference?
Java is strictly call by value. Say for example, a variable is created, we assign a value to it. Now if
we pass that value to a method and try to change the value in the method. Now java will
modify the value inside the method, java will try to create a copy of that variable while passing
it as a variable. The original value of the variable is left unmodified. This is not the case with call
by reference, if we pass an object as reference and try to access and modify the same variable,
then the original value of the variable is changed.
11. Difference between Compiler and Interpreter

Compiler Interpreter
It scans the whole code and translates the It scans the code line by line and translates to
whole program into machine readable form machine readable form.
The compilation/scanning time is high and The scanning time faster for single line. But
execution time is less. the execution time is high
The compiler saves an executable file after Interpreter doesn’t save any file.
successful compilation. But the interpreter needs to translate the
The executable file can be reused in the source code every time.
future if there are no changes in the source
code. No need for compilation in the future.
Needs extra memory to save the executable Interpreter doesn’t require such extra
file memory

12. What is Inheritance? Advantages of Inheritance


Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Concept of creating new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of parent class, and you can add
new methods and fields also.
Advantages of Inheritance

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.

13. Types of Inheritance


 Single
 Multilevel
 Hierarchical
 Hybrid

14. Method Overloading. Ways in which you can achieve Method Overloading. Advantages
of Method Overloading.
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Advantages of Method Overloading


 Increases the readability of the program.

15. Method Overriding. Advantages of Method Overriding


16. What is Polymorphism? Advantages of Polymorphism
17. What is Compile time and Runtime Polymorphism?
Compile time or static polymorphism is achieved through Method Overloading. In the
below example, the decision to call the add method is determined by the parameter during
the compile time.
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}
Dynamic Polymorphism is achieved through Method Overriding. Here, the child class will be
overriding a method in parent class. In this example we have child class object assigned to
the parent class reference so in order to determine which method would be called, the type
of the object would be determined at run-time. It is the type of object that determines
which version of the method would be called (not the type of reference).
class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class XYZ extends ABC{

public void myMethod(){


System.out.println("Overriding Method");
}
public static void main(String args[]){
ABC obj = new XYZ();
obj.myMethod();
}
}

18. What is strictfp modifier?


19. Why String is Immutable in Java?
The value of String cannot be changed, by design it is immutable. Say for example, if we
have a String s1 = “Hello” and if we try to modify it to uppercase letters by calling
s1.upperCase() and try to print s1. The value still has “Hello” unchanged. Which means
we cannot modify the value of s1.

String Literals
String s1 = “Hello”; // cached in string pool
String s2 = “Hello”; // now s2 will also point to the same string obj in string pool

s1 == s2 is true
Strings are stored in a special memory called String Pool. Say we have another String s2
= “Hello”. Previously, String s1 value is cached in the String pool. Now JVM will go and
check the String pool whether “Hello” is already present. Since its already there s2 will
also point to the same object in the string pool.
Creating String by calling the constructor
String s3 = new String(“Hello”); // this string is not interned
s1 == s3 is false
JVM does not search the string pool for “Hello” and assign the reference to the object
s1. So s3 is totally pointing to a new object in the heap. It won’t create in the string
pool.
To make JVM search the string for “Hello” we need to call intern() after creating a string
using constructor. Now it will return true.

String s3 = new String(“Hello”).intern(); // now its interned


s1 == s3 is true

20. Difference between final, finally and Finalize


Final is used for restricting the user. If a variable is declared as final, then we cannot change
the value of the variable. It will be considered as a constant.
 A final variable that have no value it is called blank final variable. It can be initialized in
the constructor only. (If not, it will result in a compile time error).
 A blank final variable can be static. It can be initialized in the static block only.
 We cannot inherit/extend a class that is declared as final.
 We can inherit a final method from the super class. But we cannot override it.

class Bike {
final void run () {System.out.println("running...");}
}

class Honda2 extends Bike {


public static void main (String args[]){
new Honda2().run();
}
}
o/p: running…
 A constructor cannot be declared final.

Finally block is used after the try and catch in exception handling. It is used to execute
important code such as closing connection, stream etc., This block is always whether the
exception is handled or not.

Finalize method is used to perform clean up processing just before the object is garbage
collected. Garbage Collector always calls just before the deletion/destroying the object
which is eligible for Garbage Collection. It is present in the object class (which is the super
class of all Java classes)
21. Difference between throw and throws

No Throw Throws
.
1. Java throw keyword is used to explicitly Java throws keyword is used to
throw an exception. declare an exception.

2. Throw is used within the method. Throws is used with the method
signature.
3. Cannot throw multiple exceptions at the can declare multiple exceptions e.g.
same time. public void method()throws
IOException, SQLException.

22. What is Encapsulation? How can you achieve encapsulation? Advantages of


Encapsulation in java is a process of wrapping code and data together into a single unit.
We can create a fully encapsulated class in java by making all the data members of
the class private.

By providing only setter or getter method, you can make the class read-only or
write-only.

23. What is Interface? Advantages of having Interface


Using interface we can achieve 100% abstraction. Abstraction is a process of hiding
the implementation details and showing only functionality to the user.

24. What is Abstract class. Advantages of Abstract class


25. Difference between Abstract class and Interface

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract classcan extend another An interface can extend another Java


Java class and implement multiple Java interface only.
interfaces.

7) An abstract classcan be extended An interface class can be implemented


using keyword ?extends?. using keyword ?implements?.

8) A Java abstract class acan have class Members of a Java interface are public by
members like private, protected, etc. default.

26. What is covariant return type?


27. What is the use of this keyword?
28. What is the use of super keyword?
The super keyword in java is a reference variable which is used to refer immediate
parent class object. Used to invoke parent class variable, method and constructor
29. What is Static and Dynamic Binding?
30. What is the use of instanceof operator?
31. What is the difference between .equals and == in java?
The == operator compares references of string objects and not values.
The .equals() compares the values of the string.

32. What is wrapper class? What is the use of it?


Wrapper classes are used for
33. Difference between Deep copy and shallow copy
34. Difference between Comparable and Comparator
35. Difference between Serializable and De-serializable

36. What is Arraylist?


 Java ArrayList class uses a dynamic array for storing the elements.
 It can contain duplicate elements.
 ArrayList maintains insertion order.
 ArrayList class is non-synchronized.
 Manipulation is slow because a lot of shifting needs to be occurred if any element is
removed from the array list.
 Allows random access because array works at the index basis.

37. What is LinkedList?

o Java LinkedList class uses doubly linked list to store the elements.

o Java LinkedList class can contain duplicate elements.

o Java LinkedList class maintains insertion order.

o Java LinkedList class is non synchronized.

o In Java LinkedList class, manipulation is fast because no shifting needs to be


occurred.
o Java LinkedList class can be used as list, stack or queue.

38. Difference between process and Thread


39. What is String Constant pool?
40. What is StringTokenizer class?
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple
way to break string.

public class Simple{


public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
o/p: my
name
is
khan

41. Difference between Primitive type and Derived Type


42. How to create an immutable class in Java
 Class must be declared as final (So that child classes can’t be created)
 Data members in the class must be declared as final (So that we can’t change the value
of it after object creation)
 A parameterized constructor
 Getter method for all the variables in it
 No setters (To not have option to change the value of the instance variable)

43. How do you convert String to int and int to String in Java?

44. Difference between String concat and ‘+’ operator


45. Advantages of inner class. Difference between inner class/nested class
Java inner class or nested class is a class which is declared inside the class or interface.
We can access all the members of outer class including private methods and variables.

Advantages of Inner class


 it can access all the members (data members and methods) of outer class including
private.
 Nested classes are used to develop more readable and maintainable code
 Code Optimization: It requires less code to write.

46. Types of Nested class


47. What is a transient variable in Java?
48. What is type casting?
49. Constructors. Types of Constructors. Advantages of using Constructors

50. Difference between Heap and Stack Memory


51. What is Synchronization?
52. Can we execute a program without main method?
53. Can we use this() and super() both in a constructor?
54. Can constructor have return type?
55. Why can’t we override a constructor?
56. Why can’t we use ‘this’ inside static context?

57. Can we override and overload static method in java?


 We can overload static methods in Java. But both the method should have static
keyword in the method definition. If one method doesn’t have the static keyword,
then it will result in ‘compile time’ error.
 Overriding is not possible for static methods. Even though, we declare the methods
as ‘static’ in both the parent and child class, when the method is called, instead of
calling the static method in the derived class it will call the static method in the
parent class. (Check the ‘OverrideStaticMethods’ class in Practice project)
 Declaring static methods in both parent and child class doesn’t cause any compile
time or runtime error. But overriding cannot be achieved.
58. Why static block executes before main method?
59. Can we create an object inside static block?
60. Difference between static and non-static nested class
 Nested static class doesn’t need reference of Outer class, but Non-static nested class
or Inner class requires Outer class reference.
 Inner class (or non-static nested class) can access both static and non-static
members of Outer class. A static class cannot access non-static members of the
Outer class. It can access only static members of Outer class.

61. What is a Singleton pattern?


Singleton pattern is that we can have only one object at a time for a class.
After first time, if we try to instantiate the Singleton class, the new variable also
points to the first instance created.
To design a Singleton class, we need to
o Make the constructor private
o Write a static method that has return type object of this singleton class

Difference in normal and singleton class in terms of instantiation is that, For normal
class we use constructor, whereas for singleton class we use getInstance() method.

class Singleton

{
// static variable single_instance of type Singleton
private static Singleton single_instance = null;

// variable of type String


public String s;

// private constructor restricted to this class itself


private Singleton()
{
s = "Hello I am a string part of Singleton class";
}

// static method to create instance of Singleton class


public static Singleton getInstance()
{
if (single_instance == null)
single_instance = new Singleton();

return single_instance;
}
}
class Main
{
public static void main(String args[])
{
// instantiating Singleton class with variable x
Singleton x = Singleton.getInstance();

// instantiating Singleton class with variable y


Singleton y = Singleton.getInstance();

// instantiating Singleton class with variable z


Singleton z = Singleton.getInstance();

// changing variable of instance x


x.s = (x.s).toUpperCase();

System.out.println("String from x is " + x.s);


System.out.println("String from y is " + y.s);
System.out.println("String from z is " + z.s);
System.out.println("\n");

// changing variable of instance z


z.s = (z.s).toLowerCase();

System.out.println("String from x is " + x.s);


System.out.println("String from y is " + y.s);
System.out.println("String from z is " + z.s);
}
}

62. What is Factory design pattern?


In Factory pattern, we will be creating an object without exposing the creation logic to client
and refer to the newly created object using a common interface.
We will be having a factory class which gives the instance of the relevant class we want.
Equals() and Hashcode()
In java equals() method is used to compare equality of two Objects. The equality can be
compared in two ways:
 Shallow comparison: It simply checks if two Object references (say x and y) refer to the same
Object. i.e. It checks if x == y. Since Object class has no data members that define its state, it is
also known as shallow comparison.

 Deep Comparison: Suppose a class provides its own implementation of equals() method in
order to compare the Objects of that class w.r.t state of the Objects. That means data members (i.e.
fields) of Objects are to be compared with one another. Such Comparison based on data members
is known as deep comparison.

It returns the hashcode value as an Integer. Hashcode value is mostly used in hashing
based collections like HashMap, HashSet, HashTable….etc. This method must be
overridden in every class which overrides equals() method.
 If two Objects are equal, according to the equals(Object) method, then hashCode() method
must produce the same Integer on each of the two Objects.
 If two Objects are unequal, according to the the equals(Object) method, It is not
necessary the Integer value produced by hashCode() method on each of the two
Objects will be distinct.
SOAP REST
Simple Object Access Protocol depends REST supports both XML and JSON formats
primarily on XML to provide messaging for communication
services.
SOAP uses different protocol for REST is an architecture which uses HTTP
communication like HTTP, SMTP, FTP actions and methods for communication
SOAP is a heavy weight protocol REST messages are smaller in size, since it
predominantly uses JSON than XML. So it’s a
lightweight component.

You might also like