Search This Blog

Thursday, September 3, 2020

Java frequently asked questions

 Java frequently asked questions

1. Why we can'r use this keyword inside static context?

Note: Every java have mainly 2 context a. static context b. non static context(place/area)

static context -- Free accessible area.

Ex: reception,

non static context -- Restricted area, we need to take permission.

Ex: Class room, id card required as permission.

2. Why abstract can't be final and abstract can't be static?

Note: final abstract is illegal combination modifier.

Ex: class Parent{

final abstract void method1(); --> illegal combination modifier.

static abstract void method2();  -->  illegal combination modifier.

static --> Common functionality of object. Ex: IFSC code

non-static--> specific to object. : Account number.

abstract-- > specific.

3. Why class can' be private & protected(within the hierarchy)?

Note: Class is representation of object. Plan is nothing but class or model.

If class is defined as private then the complete object is not visible to the communication world.

hierarchy --> Parent child relation.

4. When we use Runnable interface to create Thread?

Note: In java every class is implicitly inherit Object class, to get the Object behaviour.

In IS-A- Relation (parent child relation) if you want to apply Thread behaviour only to child class 

 You can con extend from the thread Class because Child class is already extending Parent class

 and one more retention is not possible as java does't support multiple Inheritance concept.

Hence We have only one option that is implement Runnable Interface.

5. What is Inheritance?

Inheritance includes:

1. Accessing Existing object functionality.

2. Adding new feature.

3. Updating existing object functionality.

Ex: Java latest version in market , Latest version of Android Mobile.

Def: Define an Object with the help of Existing object.

6. Checked vs Unchecked Exception?

Exception: Runtime error.

Unchecked Exception means Your java application is not connected to any outside resource.About your application only you should take care of them whether you handled or not compiler involvement is not there. But incaseof Checked Exception your application is connected to outside resource, you should care about outside resource if you don't care about outside resource  then compiler involvement is there in your application Please go and handle this resource.  

7. Why  static execute before main()?

static block provides the basic information at time of Class loading, Without basic information you cvan not start communicating. Hence Without block we can not use methods.

8. Why main() is public and static?

main() is common starting point for all the standalone application   

9. Why we can't override constructor?

Defining the method inside child class with the same name and same signature from Parent class.

Updating Existing functionality in the extended class.

Note: generally constructor is used for initialization.

10. When to use Fully Qualified name instead of import?

import is used to connect the classes between the application.

Whenever we want to access two classes with the same name from two different packages , we can not use import statement.

package advantage is defining more than one  class with the same name identity, to avoid the collegian

between the classes. Once the Classes create in two different places with same name, accessing again becomes problem, With he import statement we can not access because import statement can not understand from where it has to load i.e which class will load into JVM can not understand Hence we should go for Fully Qualified name.

11. Where to use String to primitive Data type conversion?


12. What is abstract class ? Why a class     becomes abstract?

Note: We have two types of class General class(concrete class), abstract class.

class --> Complete representation of Object.[100 % it has to define]

abstract class--> partial representation of Object.

i.e, abstract class is a class which is not fully defined or not 10% defined.

A class is nothing but 100% defined.

13. What is Boxing?

Converting primitive data into Object type data is known as Boxing.

Note: we have two things to convert.

A. pri-defined method

Ee: valueOf() convert primitive data to Object type.  valueOf() is a static method, Hence we need to call method using Class name.

B. Constructor.

Note: constructor always returns Object only.

14. Where do we use try with multiple catch blocks?

To handle different types of exception occured  in different types of statements.

While performing the task we may face different types of exception.

Ex: Atm withdrow  process.

15.   How to access static members in java application? 

static members--> It can be static variable or static method 

There are three way to access members

1. using class

2. using this keyword

3. Object reference

Note:1. From static context we can use static member using class name and object reference but not using this keyword.

Note: 2. from non-static context we can access static member(variable, method) using class name, this keyword and object reference.

16. What are limitation of default constructor??

If you are not wring default constructor in java source program, compiler will supply automatically constructor  with zero argument/no argument and empty body called default constructor.

Limitations......

16 What is default constructor?

Constructor is a special java method and having same name as Class name, and no return type for it.

If manually we don't provide constructor in that case compiler will supply a no arg constructor.

17. Why we can not collect object address onto integer variable instead of class type?

  what is user defined data type in C,C++?

 Structures is used to declare/ store different types of data into a single variable is called user defined data type.

Ex: struct Employee{

int eno,

char ename[20],

float esal;

};

Not: integer variables holds data , pointer variable holds address, but both are in the form of integer.


18. How JVM instantiate Parent class in child object creation?

Note: super() is used to invoke Parent class constructor from the child class, and is should be first statement.

Example:

class Parent{

Parent(){

sop("Parent's instantiation");

}

class Child extende Parent{

Child()

{

super(); --> Must be 1st statement 

sop("child's instantiation);

}

psvm(){

new Child();

}

}

19. can we define main method inside abstract class?

abstract class is the class which is not having full definition or partial definition  of object. 

abstract class can have two types of methods

a. abstract method

b. concrete method- A method having difination.

 Note: if any class is having abstract method the class also should be defined as abstract.

Yes, abstract  class can have main method and JVM invokes the main method automatically, bacause main() is a static method, Hence static functionality of abstract class we can access directly.

Example:


public abstract class mainMethodInsideabstract {


void m1() {


}


abstract void m2();

public static void main(String[] args) {

System.out.println("abstract class main method");

}

}


   

20. can we overload main()?

Yes.

Example:


public class MainMethodOverloading {


void main() {


}


static void main(int value) {

        System.out.println("ststic main method");

}


public static void main(String[] args) {

System.out.println("stsnderd main methoid");

MainMethodOverloading overloading = new MainMethodOverloading();

overloading.main();

                 overloading.main(1333);

MainMethodOverloading.main(100);

}

}


21. How can we instantiate Class, abstract Class and interface??

Basic funda: Once the class 100 percent defined then only you an create object.

We can create object for an Class either by using new keyword, or by using child class also.
We can not create object for an abstract Class by using new keyword b because class in not having 100 percent defined, but we can create through  object from child class.

We can not create object for an Interface either by using new keyword, or by using child class also.

22. Difference between this()  and super() ?
 
this:
1. used to access current class constructor.
2. Use only inside another constructor  of same class.
3. call to this() must be the first statement inside constructor.

super():
1. used to access Parent class constructor.
2. Use only under child class constructor.
3. call to this() must be the first statement inside constructor.

============== 26 lecture ==============
23. Types of Inheritance?
Types of inheritance in Java




24. How we can create object inside static block?
   
scenario -- 1 
 

public class ObjCreationinideststic_block {

static {
ObjCreationinideststic_block obj = new ObjCreationinideststic_block();
System.out.println(obj);
}

public static void main(String[] args) {
System.out.println("Main method"+obj); // compile time error
}
}

scenario- 2.


public class Test {
static Test ref = null;
static {
Test.ref = new Test();
System.out.println(ref);
}

public static void main(String[] args) {
System.out.println("Main method --> " + Test.ref);
}

}
 
25. Block vs method??
        Block--------------------------------------- Method
  1. Block of instructions.                    1. Block of instructions.
 2. No identity.                                     2. Having identity.
 3. No input.                                         3. Input is present
 4. No output.                                       4. output is present.
 5. we can not access block                  5. we must call explicitly using it's name.
      explicitly.

Note:  we can not access any block  because blocks don't have identity.
Note: blocks in java executes implicitly either static or non- static block

26. static variable vs non-static variable(instance variable)???
     
--     Instance variables are declared in a class, but outside a method, constructor or any block.
-- Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
-- Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
-- Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
== 
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.

== Static variables are created when the program starts and destroyed when the program stops.
== 
Static variables can be accessed by calling with the class name ClassName.VariableName.

== 
There would only be one copy of each class variable per class, regardless of how many objects are created from it.


27. How to initialise  an Object??



28. POJO vs Bean?
  
POJO rules:
a. Class must be public.
b. properties(variable) must be private.
c. default constructor is mandatory.
d. must have public setter and getter methods for all properties.

NOTE: POJO class will not serialize.(will not implement serializable interface)
and Bean class can be serialized because Bean class must implements serializable interface.

29. Can a final class extends abstract class??

 Partial representation of Object-- abstract class.
Ans--> YES
 conditions allowed
--->> it has to override all the specifications of abstract class in final class because one more extension is not possible.

30. What is Exception orrun-time error?

   31. What is syntactical error? or compile time error?
  
 
Compile-timeRuntime
The compile-time errors are the errors which are produced at the compile-time, and they are detected by the compiler.The runtime errors are the errors which are not generated by the compiler and produce an unpredictable result at the execution time.
In this case, the compiler prevents the code from execution if it detects an error in the program.In this case, the compiler does not detect the error, so it cannot prevent the code from the execution.
It contains the syntax and semantic errors such as missing semicolon at the end of the statement.It contains the errors such as division by zero, determining the square root of a negative number.


EX: 1. can not find symbol.
2.  Invalid method declearation 
3. this can not be addressed from static context.

32. Can we place instance variable(non static variable) inside interface?
  
     Ans --- Not allowed.
         When non static variable gets memory allocation , in the process of object creation but we can not          create object for interface
     Reason:   no constructor  definition. we can not define constructor inside interface.
       
Remember this: In java without constructor no one can create object.

All the variable declared inside interface is by default compiler will add public static final.

 33. What is logical error?
 
    Produce unexpected output. 
Ex:  
 class test{
    psvm(){
     
  int x=5, y= 2;
    float z= x/y;  // o/p= 2.2 which is wrong
       float z=(float) x/y;  // o/p -- 2.5 is correct
   
}
}

34. Class / abstract class / interface???

Class -- complete definition of object.[Only concrete methods]
abstract class -- Partial definition of Object.[concrete methods & abstract methods are allowed]
interface-- Complete declaration of Object but no definition.[Only abstract methods are allowed i.e 0 % definition i.e only abstract methods will be present]

35. How to implement multiple inheritance using interfaces?
 An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.

A program that demonstrates multiple inheritance by interface in Java is given as follows:

Example

 Live Demo

interface AnimalEat {
   void eat();
}
interface AnimalTravel {
   void travel();
}
class Animal implements AnimalEat, AnimalTravel {
   public void eat() {
      System.out.println("Animal is eating");
   }
   public void travel() {
      System.out.println("Animal is travelling");
   }
}
public class Demo {
   public static void main(String args[]) {
      Animal a = new Animal();
      a.eat();
      a.travel();
   }
}

Output

Animal is eating
Animal is travelling

Now let us understand the above program.

The interface AnimalEat and AnimalTravel have one abstract method each i.e. eat() and travel(). The class Animal implements the interfaces AnimalEat and AnimalTravel. A code snippet which demonstrates this is as follows:

interface AnimalEat {
   void eat();
}
interface AnimalTravel {
   void travel();
}
class Animal implements AnimalEat, AnimalTravel {
   public void eat() {
      System.out.println("Animal is eating");
   }
   public void travel() {
      System.out.println("Animal is travelling");
   }
}

In the method main() in class Demo, an object a of class Animal is created. Then the methods eat() and travel() are called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      Animal a = new Animal();
      a.eat();
      a.travel();
   }
}

  36. Can we define main() inside interface?
 
 An interface is a complete declaration  of an Object and have  only abstract methods.

Ans--> Till JDK 1.7 --> main method inside interface is not allowed  either static or non static.
         from JDK 1.8 --> they have introduced definition of one or n no of static method is allowed but non-static method we can not define.

37. What is default Exception handler?
 
Whenever an exception Object is rased that we have to handle  and if we are not handling than that object will be transferred to to JVM  and JVM and JWM again pass it to the Default Exception Handler and DEH will take care and it will handle.

38. When we  call super method explicitly?

In the process of child Object creation, if you want to provide initial value to to parent class we use super() or we call super()  from the Chile class constructor.  
   
 39 What is POJO class and it's rules ?
  
  Pojo -Plain old java Object.
 Rules are:
 1. Class must be public.
2. Properties/ variables must be private.
3. Must have public default constructor.
4. Can have args constructor, it's optional.
5. Every property should have getter and setter Methods.

40 What is Immutable Class ?

Immutable --> Once object has been created to a particular class the state can not be changed.
 
Rules are: 
1. Class is public.
2. Properties are private and final.
3. Must initialize all the properties through  Constructor.
4. Setter methods are not allowed.
5. Only public getter methods allowed.

41. What is getter and setter method??


42. When we use Fully Qualified Name?

Note: The main advantage of package is to avoid  collesion between class name.

If you want to access two classes with the same name but from two different packages insted of import statement we should go for Fully Qualified Name.
   
43. When we can assess members  of different     access modifiers?

 
44. Can a java Source file contains more than one Public class?

 Not allowed.

We can not define more than one  class in a single source file.
If 100 public class are there 100 should be present in java.

45. How can we handle child type exception using it's parent class reference variable ??
    
Just because of Runtime polymorphism concept or runtime binding.

runtime binding -- After creating object of the child class you can collect the address into it's parent type or grand parent type or any other type in the hirararchy.

46. Why we can't handle Child type Exception after handling Parent type ?

 Note: One try block can handle n no of catch block in java.
You can not handle same exception more than one type .


47. Will JVM creates Separate Objects for Parent in Child Object Creation ?
  

48. why we can't handle Error in Java ?


49 . Why we can't handle same exception more than one time?

 
50. How to create Thread ?

   A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called.

The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread and it is the last thread to finish execution.

A program that demonstrates this is given as follows:


51. What are the default identities of Thread ?

Threading refers to the practice of executing programming processes concurrently to improve application performance. While it's not that common to work with threads directly in business applications, they're used all the time in Java frameworks.

As an example, frameworks that process a large volume of information, like Spring Batch, use threads to manage data. Manipulating threads or CPU processes concurrently improves performance, resulting in faster, more efficient programs.

  

Find your first thread: Java's main() method

Even if you've never worked directly with Java threads, you've worked indirectly with them because Java's main() method contains a main Thread. Anytime you've executed the main() method, you've also executed the main Thread. 



52.  Multitasking vs Multi-threading ?

    -- Maximum use of a CPU or performing n no of tasks using n no of prosesses spaces.
  ---   Multi-threading -- processing n no of tasks(thread) using only one process.
    
53. need of Multitasking?
  Multitasking -- performing more than one task concurrently with the help of Control unit , time slicing concepts and context switching concept.

Adv:
 1. Optimum(maximum) utilisation of CPU.
 

54. What is multi-tasking  ?

 
55. What is Runnable state in Thread life-cycle ?
 
    Runnable state -- Waiting in the queue to be started.
 

56. What is the Super class of all the class in java ? Why ???

 Ans --> java.lang.Object -- it's default package Hence we can access  directly into every java application.

 Note: Every java class supports single inheritance concept  by extending the functionality of Object class.
 
57. When we cast object address into interface type reference variable??

Note: interface is a standard set of specification,  this is object upcasting.
  Example:

    interface Lenovo 
      {
   processor();
   motherBoard();
   diaplay();
 }

class pankajComputers implements Lenovo {

 .................
..................
....................
       pankajComputers  pankajcom= new pankajComputers(); // wrong 
 
       Lenovo leovocom= new pankajComputers(); 

}


58. Why run() can not throws Interrupted exception ?

 59. Why we can't call run() explicitily ??

    start()  is a pre-defined method it is available in a Thread class  and internally start() perform following logic

1. To allocate thread space.
2. fetch run() logic.
3. Execute in the allocated space.


59. What is Deamon thread??

Deamon thread  --> provide  service to the non-Deamon thread.

 non-Deamon thread  executes front-end logic.
 Deamon thread  -- service thread.



  
60. How to find current thread details ??

  Ans--> currentThread(); method.

 Ex: Thread t=  Thread.currentThread();
                   t.getName();
                   t.getPriority();

61. How to set identity to the thread?

  
62. Diff between sleep() and join() ???

Whenever one thread depends on another thread completion then insted of going for sleep() we should go for join().

63. What is finalize() ??
    
  finalize() is available in Object class with access modifier protected with empty body and we can override finalize() in every class of java application.
 finalize() contains closing statements i.e before destructing of objects GC Thread should release all the resources connected with the object.

64. What is final modifier in java?

 final is a modifier or key-word we can apply final modifier to following:

a. class   
b. methods.
c. variable.
 
finalize keyword will restrict the updation permission.

if class is final we can not extennds it.

if method is final we can not override it.
if variable is final we can not modify the value.



65. When JVM starts GC Thread ??

Ans---> JVM starts the GC Thread only when it's required, when memory is running low Hence to decrease the stress on the processor and to increase the performance of App JVM starts GC thread.

66. what is garbage collection ??

GC is a demon thread(back-end thread) or service thread i.e it will provide the service to all the non-demon threads(the thread which are running in the application).

 GC delets unused space in heap memory and re-collect the heaps space to create the new objects.

NOTE: JVM will create the GC and JVM only starts the GC threads and stop as well when required. Hence as a programmer we no need to take car og GC.

67. Can we change the behaviour of a main thread from non-daemon(executes front-end logic) to demon??
 
As soon as thread is created it will be non daemon thread including main thread .
We can convert non-daemon thread to daemon using a methid setdeamon().

68. How to create Daemon thread??


Ans--> We can convert non-daemon thread to daemon thread using  non-static method present in Thread class and it's take arg as bolean.

true-- non-daemon to daemon .
false means non-daemon behaviour only i.e by-deafault it's non-daemon

69. Can we over-ride static method in ??

 Ans-- you can not update static methods to maintain common functionality , if you want to update plz update in parent class only.

70. what is use of throw keyword??

throw keyword is used to throw an Exception object externally.

71. Why finalize() is protected in Object class??


72.  What is the use of System class GC method?? // Syste.gc(); 

System class is a Predefined available in lang package have GC method it will simply run garbage collector thread.
    
73. Can we access static  variable directly??

Note: static variable we can access using Classname.variable name, if there is no local variable with same name in that case we can directly call variable name.
 
 Hence when there is same name variable is present in local and static in that case it won't allow.


74.  Why we need to set path to JDK??

 
75. Can we apply modifier to local variable??

No, modifiers and access modifiers is not applicabe to local vabiable.

76.  How to generate Random integer ??

Random class is present in util package having 2 methods are present to generate random number

1. nextInt();  --> 4 bytes --> -2 power 31 to -2 power 31 -1
2. nextInt(int upperlimit); --> generate randon value b/w 0 to upper value.


76. What is Serialization ??

Serialization is the concept of converting Object states into persistance(permanent) state using ObjectOutstream class.
Note: Which class object you want  to serialize the class must implements Serializable interface.
Once the data is serialize we must deserialize it to see it. 
  

77.  What is transient modifier ??

 Ans ---> If you declare any variable with transient modifier , that variable will not be converted into persiatance state.

78. What is De-Serialization??

Converting serializable file into Object or reacquiring the object information from the serializable file using ObjectInputStream class and read().

79. How to create userdefined immutable class ??

 Rules:

1. class. MUST BE PUBLIC AND FINAL.
2. All the properties are private and final.
3. Provide initilization only through constructor at the time of object creation
4. only getter() are allowed.
5. setter() are not allowed.
     
79. What is immutable object in java ??

 
80. What is Process of Serialization in HAS-A-Relation ??



81. Can we call static method directly??

82. What is Local variable and limitations of Local variable ?

Decleration of variable inside the block.
We can access local variable within the block or Method.

83. What is Limitations of Local Inner     class ??

Defining a class inside a class method or block or constructor is called local inner class.

1. we can not access local inner class outside of that block. 
2. We can not apply access modifier to Local access modifier.
3. Local inner class can be static.

84. What is inner class/ nested class ??

 Define a class inside another class is known as inner classs.

Adv:
1. Setting dependencies to Objects.


85. Why we can't write serialized data into .txt file??

 
86. What is Anonymous inner class?

Define a class with no identity inside method only --- > Anonymous class.

Mostly Anonymous class used to provide the defenation to interfaces.


87.  How to pass an interface object as a parameter??


88. How to instantiate non-static inner class??

89. What is Local inner class?

Writing a class inside the block, method or constructor is called as inner class.

 Adv
1. Avoid collision between the class names.

90. What is Array??



91. How to access Array elements?


92. Diff between static and dynamic memory allocation??

static memory size is fixed
Ex: primitive data type, Arrays, ......
Dynamic memory --- memory size ia not ficed.
Ex: Collaction......


93. Array vs Collection??


1. static in size                                        1. dynamic in size
2. can store only homogenous data        2.Holds heterognous.
3. Holds primitive and objects               3. Holds only Objects, can't store primitive data in collaction  


94. Hahset  vs Linkedhashset vs treeset ??

HS                                                LSS                                TS
1.2                                                1.4                            sorted set
No insertion order        maintain insertion order        assending oder

Not allowed duplicate in all three.

95. Arraylist vs Vector??

1. implements List interface                               1. mplements List interface  
2. Ordered                                                           2. Ordered
3. Duplicate allowed                                           3. Ordered

4. jdk 1.2                                                                4. jdk 1.0
5. dy def Not synchronized-not thread safe          5. by def synchronized


96. When we will go foe LinkedList insted of Araylist ??

1. Element stored in congequative    1. 
2. insertion & deletion is faster        2.   insertion & deletion is slower
3. Fat accessing of element               3. 

97. Applets vs Swing??
  
1 run by html                                                                        1. pure java  -- javax.swing run by jvm
2. OS dependent                                                                   2. independent to OS

98. HashMap vs Linkedhashmap vs TreeMap ??

doesn't maintain insertion order
linkedHashmap Maintain insertion order
Maintain sorted order of keys in Treemap.

99. How elements stored into hashtable ??


proocessing is faster when compare with LinkedList.


No comments:

Post a Comment