Top 100 Core Java Interview Questions

  • By Onkar Nagarkar
  • April 28, 2023
  • JAVA Programming
Core Java Interview Questions

Top 100 Core Java Interview Questions

Core Java is a powerful programming language that serves as the foundation for many modern software applications. It’s widely used in a variety of industries, including finance, healthcare, and e-commerce. In this article, you will  find the Top 100 Core Java Interview Questions

If you’re interested in developing your skills in Core Java, you’ve come to the right place. Our Core Java training in Pune program is designed to help you master the language and build real-world applications from scratch.

Our program covers all the essential topics, including variables, data types, control structures, arrays, classes, objects, inheritance, polymorphism, exception handling, multithreading, and much more. You’ll also learn about popular frameworks and libraries, such as Spring and Hibernate, that are commonly used in Java development.

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

Q Who is the Father of Java?

James Gosling

————————————————————————

Q List out some features of Java

 

1) Java is platform independent

   –> It is mainly because of Byte code and JVM

   –> A compiled code in a language like C is in binary and thus Platform dependent. 

   –> But, Java does not compile the source  code into binary code, 

       It converts it into byte code, which platform independent.

   –> Thus Java is Platform independent.

 

2) Java is secure  

   The main reason, java is secure is because of JVM.

   As processor cannot understand byte code, the harmful instruction will not be executed.

   Only through JVM can processor execute a byte code.

   And JVM acts a sheild/body guard preventing all the harmful instructions.   

 

3) Java is Robust 

   The language Java, does not have pointers concept.

   Because of which, it eliminates the bugs/errors caused by memory leaks/pointers

   Java has strong error checking –>  it has the concept of Exception handling.

   Exception handling, prevents the runtime errors caused during execution of program/software.

 

4) Java is Architecture neutral

   The word architecture talks about the Operating System’s architecture.  

   A java program is capable of running on any OS Architecture(windows/linux/IOs)

 

5) Java is an interpreted language

   Java is partially interpreted and partially compiled

   Java Compiler converts: Java –> Byte code

   Java interpreter(JVM): converts Byte code –> binary 

 

6) High Performance

   Since, Java is compiled into byte code, which is optimized to be converted into binary

   and run faster on a processor, Java is a High Performance language.

   Java has a JIT(Just In time) compiler, which further increases the performance of the program.

   JIT compiler is used at runtime by JVM to convert frequently called/used functions written in byte code to binary code.

 

7) Multithreaded 

   A program can be divided into individual independent tasks, which can be simultaneously 

   executed and run at the same time, resulting in faster execution.

 

—————————————————————————————————————————–

 

Q Why does java not implement the concept of pointers?

  Since pointers concept is a memory level concept, and handling memory needs a skilled programmer.

  Most of the errors caused in a software is due to memory leaks.

  Java did not want any errors caused by memory leaks, thus java decided to not include the 

  concept of pointers.

 

————————————————————————————————

 

Q What are the 2 major types of Programming methodologies

 There are 2 types of programming methodologies/paradigm

  1. Procedural  –> EX: C
  2. Object Oriented Programming Ex: Java, Python…

 

  1. Procedural : When the instructions are to executed in a procedure, the type of

              programming used is Procedural.

              Application: when component level(Electronic), embedded, such programming is used.

 

  1. When you treat the entities in a program as objects which has some properties and 

   behavior(methods) the this type is called object oriented programming.

   To create an object, you first create a class.

   

   A class can be thought of as a design/blueprint of an object.

   That is if you want to create an object, you must have the design(class) of that 

   object.

 

————————————————————————————————     

Q What is the difference between a class in java and a structure in C

  

  Structure: 

  structure is used to create a user defined data type.

  Structure as the names suggests is a structure of the newly created data type. 

  It means it is the design of the new data type.

  A structure can have different types of variables declared in it.

 

  class:

  A class is a design/blueprint of an object.

  A class is also a user defined data type.

  A class is different from a structure because it can have properties/variable + methods associated 

                                                                                  with the object.

  The reason we call it as an object, is because it is not just a variable that stores data,

  It is an entity that has data as well as methods to use the data.

  So it is like a real life object. 

 

————————————————————————————————

         

Q What are some data types in Java and its sizes?

  numeric:  

    byte –> 1 byte

    short –> 2 bytes

    int –> 4 bytes 

    long –> 8 bytes

  

floating point             

   float –> 4 byte

   double –> 8 bytes

 

character

   char –> 2 bytes

 

boolean

   boolean –> …

 

————————————————————————————————

 

Q Is String a primitive/default/fundamental data type?

  No

  String is a class in java, and that is why it starts with a capital S.

  whereas all the primitive data types are not classes and do not start with a capital letter. 

————————————————————————————————

Q  Why size of character in C is 1 byte whereas in java it is 2 bytes?

   In language like C, the character set implements ASCII character encoding standard.

   whereas in Java, character set implements UNICODE character encoding standard.

   

   The UNICODE standard, provided support for most of the languages spoken in the world

   and that is why to store characters of many different languages 1 byte was not sufficient.

   1 byte –> 256 combinations

   So, size 2 bytes for unicode character was chosen as,

   2 bytes –> 65536 combinations

   which is sufficient to represent and hold characters(alphabets) of any language in the world. 

 

————————————————————————————————

 

Q Variable rules in java

 

  1. A variable in java can only have

   (A-Z), (a-z), (0-9), _ , $

  1. A variable name cannot start with a number.  
  2. Blank spaces cannot be used in variable names.
  3. Java keywords cannot be used as variable names.
  4. Variable names are case-sensitive.

 

Do properties/variables in class have default values? If yes what are they?

Default values of instance variables:

 

  1. byte/short/int/long –> 0
  2. float/double –> 0.0
  3. char –> prints nothing(null character \u000)
  4. boolean –> false
  5. String –> null
  6. any object if not initialized –> null

 

Note: Local variables do not get any default values. 

——————————————————————————————————————————-

Discuss the syntax and meaning of main method in Java?

 

JVM calls the main method  

public static void main(String[] args) 

 

public –> because it can be accessed from anywhere

static –> It is static because, you don’t need any object to call main method 

void –> main method does not return anything to JVM

main() –> name of the method, where main logic to create objects and call methods

String[] args–> args is the name of the String[] passed as an argument to main

                 String[] –> array of strings                                                                  

 

–> you can change the order of public and static keywords

–> you can change the name of the parameter args to any name

–> name of the method–> main() –> must not be changed

 

—————————————————————————————————————————–

 

Q What are Access Modifiers

 

  1. private: access limited to class

     A method or a variable can be declared as private.

     Declaring a variable/method as private means, it can be accessed by members(methods) only within the class. 

 

  1. public: access to all

     A method, variable or a class can be declared as public.

     Declaring a variable/method/class as public means, it can be accesses from anywhere.

 

  1. default: access limited to the package

    A method, variable or a class can be declared as default.

    Declaring a variable/method/class as default means, it can be accesses from anywhere within a package.(Not accessible outside of package)

 

    Note: Only applicable modifiers for class are public and default

 

————————————————————————————————

Q Why the only applicable modifiers for class are public and default?

  1. private: access limited to class
  2. public: access to all
  3. default: access limited to the package

 

    since private access means, all the members within a class can access the member marked as private.

    Declaring a class as private does not make sense.

    why? because the members that can access a class are either the classes present inside the same package for which default

    is the applicable modifier or classes present outside the package for which public can be used as a modifier.

   

    If the class itself is declared as private, the private modifier will have no impact as a class cannot be private to itself.

 

————————————————————————————————

Q What is inheritance?

    inheritance in common words means to inherit parent behavior.

    inheritance in java requires 2 classes, Parent class and a child class where the relation between 

    the classes is, child class inherits the methods and properties of the parent class using the 

    keyword extends.

    Ex: Student extends Human

        Sports_Car extends Car 

 

    The concept of inheritance applies when the class that you want to create is an enhanced version

    of an already existing class.

    Or

    When 2 or more classes have some common behavior, then instead of writing the common methods

    in every class, you can create a parent class which will have the common methods, and all the 

    child classes can extend this class to avoid repetition of code.

————————————————————————–     

Q What is Polymorphism?

    The word polymorphism is a combination of 2 words  

    Poly: means many

    morph: face

    Polymorphism means: One with many faces

 

    So in java Polymorphism can be seen in the following ways

  1. Method overloading:  which is a compile time polymorphism

       In method overloading, method with the same name can have multiple definitions based on the

       on the following 3 factors

       Factor 1: overloading based on different data type of the parameters.

       Factor 2: overloading based on different number of parameters.

       Factor 3: overloading based on different sequence of parameters.

 

       For example: 

       sum(int, int)

       sum(float, float)

       sum(int, float)

       sum(float, int)

       sum(int, int, int)

       

  1. Method overriding:  which is run time polymorphism

  

—————————————————————————-     

Q What is Encapsulation?

    The word encapsulation means to encapsulate i.e. wrap something in a capsule.

 

    Generic definition: 

    In java Encapusulation means wrapping data and methods together into a single entity called as class.

    The class here is a capsule which binds the properties and methods together. 

 

    Encapsulation is 70% similar to the concept of abstraction.

    

    What is abstraction?

    Hiding irrelevant information and showing relevant information to the user is called as abstraction.

    Ex: TV at our home is the best example for abstraction.

 

     

    All the components which make the TV function are hidden behind the big screen.

    Only the functionalities which are relevant to the user

    like volume, brightness, channel is given or shown to the user. 

    Here the abstraction is, all the irrelevant things are hidden in the casing and all the relevant 

    things are shown in terms of the buttons on the remote.   

 

    Abstraction is done mainly for 2 reasons

  1. To achive relevance 

         Abstraction is hiding the irrelevant and showing the relevant

         Encapsulation, the way through which you achive abstraction is called as encapsulation.

     Example :

     Showing volume, channel feature to the user and hiding the rest is abstraction

     And to achieve abstraction –> covering the components in casing and putting a screen in front of it, and giving access to

     a remote which only has the user required features like volume, brightness, channel control 

     is called as encapsulation.

 

  1. To achieve security

     Not showing/giving access of sensitve information to the user, prevents the user from casuing any harm.

     If the information is sensitive, the access must not be given to the user,

     i.e. hiding the sensitive information and showing only the relevant information..

     The above is nothing but abstraction.

 

    Now In java abstraction and encapsulation is achived in the following way

    The abstraction in java refers, showing only the methods which are relevant to the user and hiding 

    the methods which are irrelevant.

   

    The above can be achived in 2 ways

  1. To show the methods to the user, define the method as public.

       To hide the irrelvant methods, define the method as private.

  

  1. In a class define only those methods and properties which are relevant to the user.

       Don’t add any method which is not relevant. 

       And that is why, a class is said to encapsulate Properties and methods.

————————————————————————————– 

 Q What is the meaning and Job of JVM? How does JVM make Java Platform Independent?

   JVM : Java Virtual Machine 

   Job of JVM: JVM is responsible run a java file which is in the form of a byte code.

   JVM is how Java is platform independent

   In languages like C, A C file is converted into OS specific binary file, thus it is platform(OS) dependent.

   Whereas in Java, A java file is first converted into a byte code which is platform(OS) in-dependent.

—————————————————————————————————–

Q What is JDK, JRE, JVM, JIT compiler?

  JDK: Java Development Kit

  Whatever tools which are required to develop a java based software are all included in this

  JDK includes: Devlopment tools, Java compiler(javac.exe), JVM(java.exe), JRE   

  

  JRE: Java Runtime Environment   

  The runtime, Environment tools required to run a java program are included in JRE

  

  JRE includes: Library files, JVM, JIT compiler

  

  JIT compiler: Just in Time compiler

  JIT compiler is a part of JVM which helps in faster Execution of a Java program.

  JVM has to convert each and every line of byte code to binary code before executing it.

  If a function is called repetitively, then JVM has to convert the definition of the same funtion every time to execute it.

  JIT compiler converts the repetitive called function at once after a certain threshold(Limit) and stores it in a small part

  mermory inside JVM.

  Doing this, next time when the same function is called again, JVM does not have to waste its time again on converting it 

  to binary, as it already has the binary code stored in its memory area.  

——————————————————————————————————————-

Q What do you mean by instance and static variables.

  instance vairables: 

      Also called as Object level variables

      The variables whose value is unique to every object are called as instance varibles. 

      Example: name, age, phoneNo, salary,..

      Every student object will have its own name, age,.., thus every object will have its own copy of the variable.

      Since instance variables like name and age are a part of a student object, It does not make sense to access 

      the variables without the creation of the student object.

      

      Conclusion: Thus, to access an instance, you must create an object

                  And on this object, you cann access the variables using the dot operator.

                  Ex: Student s1 = new Student();

                      s1.name;   

                      s1.age;

 

   static variables: 

       Also called as class level variables.

       The variables whose value is same for every object and thus shared among all are called as static variables 

       Meaning all the students studying in same school called DPS, will have the value of school variable as DPS only 

       Example: school, city, planet, companyName, …

       Only one copy of the static variable is created which is outside of any object and is shared among all objects

       to save memory as all objects will have the same value for that particular variable.

       Thus a static variable is not an Object dependent variable. Its value is same irrespective of any object.

       Since static variables are not object dependent, you don’t need to create an object to access a static variable. 

       

       You can access a static variable in following 2 ways.

  1. Using the object name.            –>  s1.school;
  2. Using the class name(Recommended) –>  Student.school;

 

instance methods: 

       Methods that internally use instance variables directly in its definition and methods which are object dependent

       should be declared as instance.

       To declare a method as instance you don’t need to mention anything. by default every method is an instance method.

       To access an instance method, you must have an instance(Object), on which you can call this method.

       For ex: if you do not have a fan, you cannot call any Fan specific method like switchOn, change-speed

       So, to call an instance method you must have an object.

 

Static methods:

     Methods which internally do not use instance varibales directly, and methods which are not dependent on any object

     are called as static methods.

     Static methods are not object specific.

     To declare a method as static, you must add the static keyword to the method.

     Thus you do not need to create an object in order to call a static method.

     You can access a static method in following 2 ways.

  1. Using the object name.            –>  s1.m1();
  2. Using the class name(Recommended) –>  Student.m1();

 

————————————————————————-

Q public static void main(String[] args) { }

  public: main function is public because it can be accessed from anywhere.

  static: Because to call main, you do not need an object. 

  void: because main does not return anything to JVM

  main(): Name of the method

  String[]:  Array of strings

  args: an array variable which can hold an array of strings

————————————————————————-

Q Can you change the order of public static to static public

 ans: YES

 Since public and static are keywords that specify a method is public and static, the order is not important.

————————————————————————————————-

Q What are some Access Specifiers in Java

  A class can only have public and default as access specifiers

  A varible can have all of the 4 specifiers

  A method can have all of the 4 specifiers

  1. public: Can be accessed from anywhere
  2. private: Can be accessed only within a class
  3. default: Can be accessed only withing a package
  4. protected: …..

  

  A class can only have public and default as access specifiers

  A varible can have all of the 4 specifiers

  A method can have all of the 4 specifiers

——————————————————————————————————

Q What are the advantages of Packages in Java?  

  Creating a package is similar to creating folders/categories

  The reason you create folders is to organize your documents 

  for example, if you have a folder called as English movies in which there are categories like horror, comedy, fiction ..

  you will group all the horror movies inside the horror folder, all the comedy movies inside the comedy folder

 

  similarly, all the relevant classes while creating a software in java are packaged together under 1 folder which 

  is called as a package in java

  Benifit of doing so results in

  1. Better organization of code.
  2. Better readability
  3. Better accessiblity
  4. Better maintainability
  5. Easy of modifying code –> addition of code, updation of code

———————————————————————-

 

 Q What is a constructor? What is a default constructor?

 

   A constructor is a special kind of method used to initialize Object variables in java.

   A constructor is called implicity when you create an object using the following command

   Student s = new Student(“Raj”, 25);

   

   Here, Student(“Raj”, 25); is a constructor call and the definition that is invoked is

   

   Student(String name, int roll) 

    {

      this.name = name;

      this.roll = roll;

    }

   

  A Constructor does not have any return type.

  Name of the constructor must be same as the name of the class it is defined in.

  If your java class, does not have any constructor in it, the compiler adds a default constructor.

  default constructor looks like this

  Student() {

  }

 

  Default constructor is an empty constructor and the job of a Default constructor is to initialize Object variables with 

  default values

  So, Student s = new Student();

  here the default constructor gets called and initializes the variables as follows

  name = null;

  age = 0;

——————————————————–

Q How many types of constructors are used in Java?

  Default constructor/No-Arg constructor :

  A constructor which has no parameters, is called as default/No-Arg Constructor.

  This constructor will initialize the object/instance variables with default values.

  If your java class, does not have any constructor in it, the compiler adds a default constructor.

  default constructor looks like this

  Student() {

  }

 

  If you already have a constructor in your class, then compiler will not add the default constructor in this case.

 

  Parameterised constructor

  A constructor which has 1 or more parameters is called a parameterised constructor.

  This type of constructor is used to initialze object variables with user given values.

  Student(String name, int roll) 

    {

      this.name = name;

      this.roll = roll;

    }

—————————————————————————————————————- 

Q Can you overload a constructor?

  Yes

 

  Constructor overloading means, the name of the constructors will be same, but the parameters can differ.

  Constructor overloading is done, because at times there can be cases where you want to initialize only a specific set 

  of properties and not all.

  

  Student(String name, int roll) 

    {

      this.name = name;

      this.roll = roll;

    }

  Student(String name, int roll, int age) 

    {

      this.name = name;

      this.roll = roll;

      this.age  = age;

    }

 

—————————————————————————————————————- 

Q Does constructor return any value?

 

  To understand what a constructor returns, first we need to understand what a function returns.

  

   int sum(int n1, int n2)

     {

        int ans = n1 + n2;

        return ans;

     }

 

  –> int result = sum(5,7); // Here sum(5,7) returns the addition which gets stored in the result variable

  

  Similarly, new Student(“Raj”, 25) creates an object in heap which is returned to the reference variable s 

 

  –> Student s = new Student(“Raj”, 25);

 

—————————————————————————————————————————–

 

Q Is constructor inherited?

  No, Every class has its own constructor and as we know a constructor’s name is always same as the class name.

  Thus a child class cannot have a constructor with parent class name.

 

—————————————————————————————————————- 

Q What is method Overriding?

  When in inheritance, if one is not satisfied with the implementation of the parent class, or wants to modify a method of 

  parent class, then the same method with the same method signature can be created inside the child class with the

  newer implementation. 

  This new method with the same signature is said to override the method of parent class.

  This is called as method Overriding in java.

 

  For example, if SmartTv extends Tv, and it is not satisfied with the display() method 

   Tv class display –> display()

                         {

                            syso(“LCD display”)

                         }

   SmartTv class can have it’s own display method with a new implementation as 

   SmartTv class display –>  display()

                               {

                                syso(“LED display”)

                               }   

   

 

  The SmartTv class’s display() method overrides, the same display() method of parent class.

  So if now you create an object of class SmartTv, display() method of SmartTv will get called instead display() of Tv 

 

———————————————————————————————————————-

Q Can you hold a child class object with a parent class reference variable?

  Yes.

  We can hold a child class object with a parent class reference variable.

                 

                     Parent p = new Child();

  

  In this case, since the refence variable is of class Parent.

  The methods are called on reference variable

  For ex. if there is a class called Car

          Car c1 = new Car();

  You call the methods on the reference c1 as c1.accelerate(), c1.brake(), …

 

  Similarly in case of, Parent p = new Child();

  If methods are to be called on a reference variable, then the class to which the reference belongs to must have the 

  those methods.

  

  So, If my child class is SmartTv and my Parent class is Tv

  and Tv t1 = new SmartTv();

  only methods of class Tv can be accessed even though, the object is of class SmartTv.

  Treat the reference variable of class Tv as a remote and the Telivision as an actual object of SmartTv.

  Even if the SmartTv is loaded with features like, Wifi, blutooth, record ..etc,

  but the remote has only the basic buttons of volume, channel, etc.

  The remote can only access the basic features available in class Tv but cannot access the 

  features of the fully Loaded class SmartTv. 

———————————————————————————

Q What is dynamic Binding?

In inheritance when you override a method of parent class in child class, the method which belongs to the object gets

executed at runtime. 

 

For ex . If you have a display() in class Tv

         display() {

            syso(“LCD”);

         } 

         AND

         If you have a display() in class SmartTv

         display() {

            syso(“LED”);

         } 

 

         Tv tv1 = new SmartTv();

         Here, the reference Variable(remote) : class Tv

               the actual Object              : class SmartTv

 

         tv1.display();

 

         First the compiler checks, if there is a method called as display in the class to which tv1 belongs to.

         Since tv1 belongs to class Tv, and class Tv has a method called display, it generates no error.

 

         At runtime, when display() is called, since the actual object has LED display, the overridden display method of class

         SmartTv gets executed.

 

         Since the binding of the method, meaning which method should get called is decided at runtime, 

         It is called as dynamic binding.  

——————————————————————————————————– 

Q Rules for method Overriding?

 

1) Overriding concept can only be applied in case of inheritance. Only a child class method can override a super class method.

2) The overriding method must have the same name and parameters.

3) The return type of the must must also be the same.

4) The access level of the parent class method cannot be decreased in the child class.

   For ex: if parent class method has access specifier as public, you cannot have access specifier as 

   default, protected or private in the child class overriding method.

5) You cannot override a final method

6) You cannot override a private method as a parent class private method will not be visible 

   in the child class.

7) You cannot override a static method as a static is object independent(does not depend/ is specific to any particular object)

 

Ex: 

Parent class: int sum(int a, int b) {

      }

 

Child class: int sum(int a, int b) {

      }

 

Note: The method name and the paramter list should exactly be same for a valid overriding 

 

——————————————————————————————————– 

Q What is Method Overloading?

 

If a class has multiple methods having the same name but different parameters the it is known as Method Overloading.

You want to overload a method, when the job of the method is same, but the parameters are different.

 

Ex:

    int sum(int a, int b) {

       …

    }

   

    int sum(int a, int b, int c) {

       … 

    }

 

    int sum(int a , float b) { 

       ….

    }

 

    int sum(float a , int b) { 

       ….

    }

——————————————————————————————————– 

Q Rules for Method Overloading.

 

  1. Method name should be same, but the list of parameters should be different in the following ways
  2. a) number of arguments/parameter is different.
  3. b) type of parameter is different
  4. c) sequence of parameters is different.

 

  1. Chaging the return type and keeping the method name and parameters same will not count as method overloading.

   Reason: The compiler should be able to differentiate which method to call. 

           The information with which a method is called is: the method name and arguments. 

           You don’t specify the return type of the method to be called.

           For ex: sum(5,7)

           If you had two sum methods:

                                    int sum(int a, int b) {

                                       …

                                    }

                                    float sum(int a, int b){

                                       …

                                    }

          

                    calling sum as sum(5,7), The compiler will not be able to decide which method to call. 

                    Thus the above is invalid. 

 

——————————————————————————————————– 

Q What will happen in method overloading if you change the other method’s return type and keep the name and parameters same.

ans: It will not be valid and will not be called method overloading as answered in the above question.

 

——————————————————————————————————– 

Q Can you inherit a constructor? Can you override a constructor?

 

You cannot inherit a constructor in the subclass(child class), because a constructor is a special method 

which is designed to only create the objects of the class it is present in.

Ex: A Animal class constructor cannot be inherited by Dog class, because animal class constructor’s job is to create

objects of class Animal, not Dog. Thus it does not make sense to have animal constructor in class Dog.

 

——————————————————————————————————– 

Q Can you overload the main method?

  Yes you can overload he main method, but java can only call the standard version of main which is 

 

  public static void main(String[] args)

 

——————————————————————————————————– 

Q What do you mean by abstraction?

Hiding the irrelevant information and showing the relevant information is called as abstraction.

 

Real World Examples : wrist watch, TV, mobile, AC, Car, 

——————————————————————————————————– 

Q What is an abstract class? 

  An abstract class is a class where one or more methods in the class are declared as abstract.

——————————————————————————————————– 

Q What is an abstract method?

  A method which has no body is called as an abstract method.

  The reason it is called as abstract is because, the word abstract means hiding the details and showing only the relevant part.

  The same applies for a abstract method, where you hide the details of a method and show the method signature.

  An abstract method must be declared using the keyword abstract.

 

  Ex: abstract void eat()

——————————————————————————————————–  

Q Rules for an Abstract class.

  1. If one or more methods in a class are abstract, the class must be declared as abstract.
  2. An abstract cannot have body, and it ends with a semicolon.
  3. An abstract class must be extended to implement the abstract methods(no body).
  4. The class extending the abstract class must implement all the abstract methods.
  5. If the extending class, does not implement some of the abstract methods, then this class should also be declared as 

     abstract.

  1. An abstract class cannot be instantiated, meaning you cannot create an object of abstract class.

     Reason: since, an abstract class has abstract methods which do not have any body, creating an object this class

     and calling the methods would have no impact as the method has no body.

     Thus it does not make sense, and it would be inappropriate to create an object on which methods cannot be called(executed).

  1. You can create a reference variable of an abstract class.

     A reference of an abstract can hold any of its implementing child classes objects.

    

     Ex: Animal a = new Dog();

         

     

     The difference would be, since you call the methods on an object using a reference varible like a.eat()…,

     you can only access those properties and methods which are available in the reference variable’s class.

 

  1. An abstract class can both, regular methods(with body) and abstract methods(without body).
  2. An abstract can have a constructor even though you cannot create an object of an abstract class

    Reason: An abstract class can have properties. A constructor is used to initialize properties. 

            Even though you cannot invoke a constructor while creating an object of abstract class, 

            but you can call the abstract class’s constructor from the child class’s constructor by using super();

 

————————————————————————————————————————–

Q When should you use an abstract class? 

  An abstract class can be treated as a category class, where you can define the guidlines of a category by using

  the abstract methods.

  For example: class Ainimal is category,  class SUV, Sedan is category…

————————————————————————————————————————– 

Q What is an interface in Java?  

  Interface is a pure abstract class.

  Interface –> between faces

  For Ex: User Interface(UI), is an interactive screen, which acts as an interface between a user and the company.

 

  In an interface all the methods are by-default public and abstract.

  variables in an interface are always public, static and final. 

  you cannot have a constructor in an interface

             

——————————————————————-

Q What are the types of Constructor?

 

–> Default Constructor/ No parameter 

    A constructor with no parameter, which initializes the properties

    with default values.

    Compiler adds a default constructor, if there is no constructor, 

    java will add a default constructor.

 

–> Parameterised constructor (the constructor which has parameters)

    Initializes the properties user given values.

 

–> Even though, we do not mention any return type to a constructor, A

    constructor returns an object.

 

–> A constructor can only be invoked(called), at the time of object

    creation that too implicitly(automically, internally).

    You cannot call a constructor explicitly(alag se nahi kar sakte).

 

———————————————————————

Q What is an abstract method in Java?

 

abstract method

 –> A method is called as abstract, if the method has no body/definition/implemention.

 –> A abstract method acts a rule, meaning any class that extends this class, must implement all the abstract methods.

 –> To define a method as abstract following is the syntax

         abstract void m1();

 

Abstract class

 –> If a class has 1 or more methods as abstract, then the class is declared as abstract.

 –> You cannot create objects of an abstract class, because an abstract class has methods with no definition.

 –> An abstract class can have both –> regular methods as well as abstract methods.  

 –> Multiple inheritance is not allowed in classes, meaning a class can only extend 1 class at a time.

 

Interface

 

 –> An interface acts as a rule book in java, as it has all the methods as abstract. 

 –> An interface is a pure abstract class, meaning all the methods are abstract. 

     

     Rules:

   1.All the methods in an interface are by default public and abstract.

     meaning, even if you do not add the public and abstract modifiers to a method,

     the java compiler will add it in the backend.

     Ex:  

       writing    public abstract void m1() is same as 

       writing    void m1()

   

  1. A variable in an interface is always public, static and final even if you don’t

      mention it explicity(alag se).

 

–> an interface can never have a concrete/regular method with a body.

–> You cannot create an object of an interface but you can create a reference variable

–> You can hold an object with interace reference variable. 

–> Multiple inheritance is allowed in case of interfaces.

–> A class can implement any number of interfaces.

–> A class implements an interface.

–> The implementing class, must define all the methods of the interface

–> A class never extends an interface, it will always implement an interface. 

–> An interface is generic, which means it is not class/software specific

    Ex: A payment gateway interface is a generic interface which can be implemented by

        any software like food delivery, e-commerse, ticket booking, IRCTC etc.  

—————————————————————————————————————————-

Q How can you achieve abstraction in Java?

 

Part 1: 

 

Abstraction: Hiding the irrelevant data and showing the relevant data.

Real world examples: TV-remote, ATM, Lift

 

How can you achieve abstraction at a very basic level 

  1. Define only those methods in a class which are relevant.
  2. Define the relevant methods as public, irrelevant methods as private.

 

2c What is Encapsulation

    The word encapsulation means to encapsulate i.e. wrap something in a capsule.

 

    Generic definition: 

    In java Encapusulation means wrapping data and methods together into a single entity called as class.

    The class here is a capsule which binds the properties and methods together. 

 

    Encapsulation is 70% similar to the concept of abstraction.

    

    What is abstraction?

    Hiding irrelevant information and showing relevant information to the user is called as abstraction.

    Ex: TV at our home is the best example for abstraction.

 

     

    All the components which make the TV function are hidden behind the big screen.

    Only the functionalities which are relevant to the user

    like volume, brightness, channel is given or shown to the user. 

    Here the abstraction is, all the irrelevant things are hidden in the casing and all the relevant 

    things are shown in terms of the buttons on the remote.   

 

    Abstraction is done mainly for 2 reasons

  1. To achive relevance 

         Abstraction is hiding the irrelevant and showing the relevant

         Encapsulation, the way through which you achive abstraction is called as encapsulation.

     Example :

     Showing volume, channel feature to the user and hiding the rest is abstraction

     And to achieve abstraction –> covering the components in casing and putting a screen in front of it, and giving access to

     a remote which only has the user required features like volume, brightness, channel control 

     is called as encapsulation.

 

  1. To achieve security

     Not showing/giving access of sensitve information to the user, prevents the user from casuing any harm.

     If the information is sensitive, the access must not be given to the user,

     i.e. hiding the sensitive information and showing only the relevant information..

     The above is nothing but abstraction.

 

    Now In java abstraction and encapsulation is achived in the following way

    The abstraction in java refers, showing only the methods which are relevant to the user and hiding 

    the methods which are irrelevant.

   

    The above can be achived in 2 ways

  1. To show the methods to the user, define the method as public.

       To hide the irrelvant methods, define the method as private.

  

  1. In a class define only those methods and properties which are relevant to the user.

       Don’t add any method which is not relevant. 

       And that is why, a class is said to encapsulate Properties and methods.

 

 

  part2  –> Abstract class

             Interface

 

—————————————————————————————————————————-

Q differentiate between Concrete class vs Abstract class?

 

concrete class: 

  1. all methods have body.
  2. can create object of this class.
  3. It is not mandatory to extend a concrete class

 

Abstract class

  1. abstract class can have abstract(no body) and concrete(with body) methods
  2. cannot create object of this class
  3. We must extend an abstract class to implement the abstract methods.
  4. The class must be declared as abstract. 

—————————————————————————————————————————-

Q Can abstract modifier applicable for variables?

Ans: No.

—————————————————————————————————————————-

Q Can an abstract method be declared with private modifier?

 

Ans: No, it cannot be private because the abstract method must be implemented in the child class. 

If we declare it as private, we cannot implement it from outside the class.

—————————————————————————————————————————-

Q When to use Abstract class in Java?

 

  1. If you want to treat a method as rule, that every class must implement.
  2. If some classes have some common methods but different implementation, then you cannot have

   one method in the parent class with one definition

   In this case you declare the method in the parent class as abstract, so that all the classes

   extending this class can implement the method according their own specific implementation.

   Example: eat method of class Animal.

—————————————————————————————————————————-

Q Is abstract class a pure abstraction in Java?

No, because it can have both, abstract as well as concrete methods.

—————————————————————————————————————————-

Q  Is it possible that an abstract class can have without any abstract method?

    Yes, you can declare a class as abstract, and it may not have any abstract method.

    but even if one method is abstract in a class, then the class must be abstract.

—————————————————————————————————————————-

Q Can an abstract class have constructor?

Ans: YES

 

Job of a constructor is to initialze variables.

An abstract class can have properties and thus it can have a constructor.

 

  If you cannot create objects of abstract class, then how can the constructor be called.

  As we know, a constructor is only called when an object is created.

 

  We cannot direclty call the construtor, but since the child class extends the abstract class.’

  Properties of abstract class are inherited by child class.

  The child classes constructor can internally call abstract class’s constructor to initialize the

  abstract class properties by using the keyword super();

—————————————————————————————————————————-

Q Can you have multiple inheritances in classes?

  No you cannot, because of the diamond problem.

—————————————————————————————————————————-

Q Can an abstract class have multiple inheritances?

  No, because it is also a class

—————————————————————————————————————————- 

Q Can the interface have multiple inheritance

  Yes

—————————————————————————————————————————-

Q What can you do, if the child class does not implement all the methods of the abstract Parent class.

  If you do not override all the methods of an abstract class, the compiler will generate an error.

  To avoid the error you can either

  1. Implement the rest of the abstract methods.

   OR

  1. Declare the child class as abstract

 

——————————————————————————–

 

Q what is an interface?

  Interface is pure abstract class.

  Interface acts a rule book / Contract

—————————————————————————————————————————-

 

Q What happens if a class has implemented an interface but has not provided implementation for that method defined in Interface?

Ans: The class has to be declared with an abstract modifier. This will be enforced by the Java compiler

—————————————————————————————————————————-

Q Can you declare a variable as final without initializing it?

   Ex: final int a;  –> Is this Valid

   No, because the word final means –> the value cannot be changed.

   If you do not provide any value, it does make sense to add final keyword. 

   valid ans –> final int a = 10; 

—————————————————————————————————————————-

Why an Interface method cannot be declared as final in Java?

  1. An abstract method which has no body, does not make sense to declare final.
  2. A final method can never be changer, overriden in the child class.

 

 Final keyword can be applied to class, variable and method. 

—————————————————————————————————————————-

Q Why an interface cannot have a constructor?

  ans: No

  In an interface, the variables are always static, which means not related to object.

  A construtor is used to initialize instance variable–> variables of an object

 

  Thus it does not make sense to have a constructor in an interface.

—————————————————————————————————————————-

Q Why an Interface can extend more than one Interface but a Class can’t extend more than one Class?

Ans: because multiple inheritance is allowed in interfaces but not in classes


Top 100 Core Java Interview Questions

Q Why should you use an interface in java?

 –> An interface acts as rulebook or a contract.

 –> Example: JPA –> Java Persistance API

  JPA is an interface which is designed for java programmers to save or modify the data in the database.

  The databases can be of different companies like, Oracle, MySQL, PostgreSQL.

 

  The JPA rule book defines the rules to save or modify any oject in the database.

  The database companies must follow and implement the abstract methods of the JPA interface

  methods like 

  create()

  read()

  delete()

  update()

 

  The interface creates a set of standard methods for a java programmer.

  The benifit is, it does not matter which database is being used, the java programmer will always use

  the set of standard methods defined in JPA.

  Because of the interface, the programmer does not need to follow the database rules of each different 

  company

 

–>  By creating an interface, the child classess implementing this interface can have their own specific implementation.

  Ex: If Animal is an interface which has a method called eat()

      The child classes, Snake, Dog and crocodile each can implement the eat() according to thier way.

—————————————————————————————————————————-

Q Can we define a variable in an interface? What type it should be?

ans Yes, the variable is always public, static and final   

—————————————————————————————————————————-

Q Can we re-assign a value to a variable of interface?

ans No, we cannot reassign as interface variables are always final.

—————————————————————————————

 

Exception Handling

 

Exception: Any unwanted event that occurs during a normal execution of a program then it is called 

           as an exception. 

           An exception stops the execution of a program abnormally.

        

Exception Handling: To handle such exception that can occure during the program execution, is called as 

                    Exception handling.

                    To provide an alternative solution/way, so that the program does not stop abnormally.

      

The Root class of Exception Hirarachy is class Throwable

class Throwable has 2 child classes

  1. Exception
  2. Error

 

  1. Exception

 

An Exception is an unwanted event that occurs during the flow of execution.

An Exception always occurs at run time and stops the program abnormally

Most of the times an exception is caused due to a program. 

An exception can be handled by a programmer   

Examples of some Exceptions

  1. ArithmaticException
  2. NullPointerException
  3. ArrayIndexOutOfBoundsException
  4. IOException
  5. SQLException …

 

  1. Error 

 

   An error also occurs at runtime and stops the program abnormally.

   But an error is caused due to lack of computer resources.

   

   Examples of some Errors

  1. StackOverFLowError
  2. VirtualMachineError
  3. OutOfMemoryError

 

————————————————————————————

Q what are the types of Exception?

  There are 2 types of Exception

  1. Checked Exception
  2. Uncheked Exception

 

  What are checked Exceptions?

  Exceptions which are checked by the compiler are checked Exceptions

 

  The common Exceptions in a program that should be handled by a programmer 

  are checked Exceptions.

 

  If you write a statement in a java Program that can generate an exception(checked) 

  and you have no handling code then java compiler will give an error, saying

  Unhandled Exception and the compiler will not let you compile the program, unless and 

  until you handle the exception either by try-catch or throws keyword.

 

  PrintWriter pw = new PrintWriter(“hihihihih.txt”);

  pw.write(“Hello”);

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

The above statements can generate an Exception which is FileNotFoundException.

 

The statements are perfectly fine, but there is a chance, if the abc.txt file is not found,

then, how will the program complete it’s execution. 

It is for this reason, that if an exception does occur, 

then the program should have an alternative path(Handling code), to continue

the rest of the execution smoothly.  

 

  NOTE: No Matter what, An Exception always occurs at Runtime.

 

  Ex :  IOException

        SQLException

        ServletException

        InterruptedException …

 

 

  What are unchecked Exceptions?

 

  Exceptions which not checked by the compiler(or go unchecked) are unchecked Exceptions.

  Ex:  

 

  These exceptions are caused by a program’s or a programmers mistake.

  These exceptions should be corrected, because handling a ArithmaticException/NullPointerException is very rare. 

 

  1. All RuntimeException child classes are unchecked

     ArithmaticException

     NullpointerException

     ClassCastException

     ArrayIndexOutOfBoundsException

  

  1. All Error and its child classes are unchecked

     StackOverFlowError

     OutOfMemoryError 

 

————————————————————————————————-

 Q How is an Exception Object Created?

  

   An Exception Object is created at the line where the exception occurs at runtime.

   An Exception Object includes information like  

   Name of the Exception

   Decription of the Exception

   Location/stack Trace of the Exception

 

   JVM creates an Exception Object with this information, and the type depends upon which exception has occured.

   JVM terminates the program abnormally when an exception occurs.

  

   It is the responsibility the caller of that method to handle the exception.

   If the caller does not handle the exception, the the caller is also terminated abnormally.

   And this process goes on until it reaches main.

   main methods is also terminated abnormally if it does not handle the exception.

   After main, the JVM handles this Exception Object to the default Exception handler

   The default Exception handler’s job is to just print the exception object’s information onto the console.

               

————————————————————————————————-

Q What are 2 types of Exceptions?

  Pre-defined Exception: Exceptions are part of the Java Language.

  For ex: IOException, SQLException, ArithmeticException

 

  User-Defined/custom Exception: Exceptions which are designed by the programmer/User is called as  User-Defined/custom Exception 

  For ex: InsuffiecientBalanceException, IncorrectPassWordException 

 

————————————————————————————————-

Q What is the advantage of using exception handling in Java?

  1. Using Exception Handling, even if an exception occurs, our program can execute smoothly/normally.
  2. The software created using Java will be a Robust(strong, less prone to errors) software, if you use Exceptionn handling

 

————————————————————————————————-

Q What does JVM do when an exception occurs in a program?

   The line at which an exception occurs, JVM will create an Exception Object of that type 

   and will either throw the object to a catch block or print the exception on the screen and will stop 

   the program.

————————————————————————————————-   

Q Should you handle Checked Exception? And Why should you do it?

   You must handle a checked Exception, because compiler will not let you compile unless and until you have handling code. 

 ————————————————————————————————-   

Q  Do checked exceptions occur at compile time?  

   No they do not. 

   All exceptions occur at Runtime only.

   Checked are just checked at compile time. The compiler checks if you have a handling code for that exception. 

————————————————————————————————-   

Q Are compile-time errors exceptions?

  No. Compile Time Error means, grammatical mistakes in a program like, semicolon missing, brace missing, spelling mistake…

  Compile time has no relation with any exception, because exceptions always occurs at runtime.

————————————————————————————————- 

Q Does Java compiler check Runtime exceptions at compilation?

 No, RuntimeException are Uncheked Exceptions.

 It means, they are not checked by the compiler

—————————————————————————————————————————-

Q Is it neccessary to handle RuntimeException?

  Since RuntimeException is unchecked, it is not checked by the compiler and thus you don’t need to provide any handling code.  

—————————————————————————————————————————-

Q If your program can generate a RuntimeException(AE, NPE or CCE), will the compiler ask you for the handling code?

  No because RuntimeException is unchecked.

————————————————————————————————- 

Q What are the keywords to handle an exception in Java?

  1. try
  2. catch
  3. finally
  4. throws
  5. throw

————————————————————————————————- 

Q What happens when an exception is thrown by the main method?

JVM handovers the Exception object to the default Exception handler.

Default Exception Handler stops the program and prints the Exception information on the screen/console.

Rest of the program will not get executed.

 

————————————————————————————————- 

  1. What is try block in Java?

Ans: A try is a block of code or statements that might throw an exception. 

     An exception generated code (risky code) must be placed within a try block.

————————————————————————————————- 

  1. What are the three possible forms of try block?
  2. try-catch
  3. try-catch-finally
  4. try-finally

————————————————————————————————- 

Q Can we write statements between try block and catch block?

 

Ans: A catch block must be followed by try block. 

     We cannot write a statement between the end of try block and the beginning of catch block.

————————————————————————————————- 

Q What is a nested try block in Java?

 

Ans: A try block within another try block is called nested try block.

————————————————————————————————- 

Q What is unreachable catch block error in Java?

ans: If you have a parent class catch block first, and child class catch block below it, then since the parent class catch block like Exception e

     can handle any Exception, the below child class Catch block like ArithmeticException will never get a chance.

     Then the below child class catch block is said to be unreachable. 

 

————————————————————————————————- 

Q What is a finally block in Java?

Finally block will be executed regardless of whether or not an exception occurs, meaning even if the exceptions or not, finally block will get

executed.

A finally block is used to close all the resources opened in try block, so that even if an exception occurs and there is no catch block, resources are not wasted

For example, if you open a database connection in java inside try block and an SQLException occurs and you do not have a catch block, 

the finally block will still get executed and the database connection will be closed(will not be wasted).

Top 100 Core Java Interview Questions on Multithreading

Q What is the difference between final, finally and finalize?

final: 

      final is a keyword in java used : class : if a class is final, you cannot extend that class.

                                  varible: if a variable is final, the value cannot be changed.

                                  method: if a method is final, then you cannot override that method.

 

finally: 

        finally is block in java which is used in Exception handling as follows

        try-finally

        try-catch-finally

 

        A finally block is used to close all the resources opened in try block, so that even if an exception occurs and there is no catch block, resources are not wasted

        For example, if you open a database connection in java inside try block and an SQLException occurs and you do not have a catch block, 

        the finally block will still get executed and the database connection will be closed(will not be wasted).

 

finalize: finalize is a method in java, which is used to close all the resources related to an object. 

          It is called before destroying an object, so that resources like db connection is not wasted.

————————————————————————————————- ————————————————————————————————- 

Q What is throw in java?

  throw is keyword which is used to generate an exception in java.

  throw can be used to throw user defined or pre-defined Exceptions in java.

  It is recommended to use throw keyword to generate user-defined Exceptions.

  For Ex: 

        if(withdrawAmount<balance) {

           throw new InsufficientBalanceException();

        }

————————————————————————————————- 

Q How do we throw an user defined exception in Java?

  If you want to generate/throw a user Defined Exception,

  since every exception in java is class which extends, Exception.

  you must first create a class with your user Defined Exception like InsufficientBalanceException which extends Exception.

  

  class InsufficientBalanceException extends Exception {

 

  }

 

————————————————————————————————- 

Q Explain the throws clause in Java. 

 

 throws keyword:

                throws keyword in java is used to bypass the compiler, just convince compiler to run the code.

                If a program has a piece of code, that can generate a checked Exception, then you handle it with’

                either try-catch or throws.

                

                using throws keyword, does not prevent abnormal stopping of the program. 

                meeaning, if an exception does occur, then the program will terminate abnormally 

                throws keyword is used with a method as follows

                

                void m1() throws Exception 

 

————————————————————————————————————————————————————————————————– 

Q What is multi-tasking and multi-Threading?

 

Multi-Tasking –> When different applications/software run simultenously on a processor/computer, then it is called as Multi-tasking.

                  Ex: Chorme is running, paint is running, eclipse is running, mp3 player is running, all these applications are running 

                      simulataneously.

 

Multi-Threading –> When a single application/Program is divided into independent parts and each part is treated as a seperate process/task, 

                    then this concept is called as multi threading.

 

Thread  —> 1 Flow of execution

Multi-Threading –> multiple flow of execution, where each flow is seperate part of a program.

————————————————————————————————————————————————————————————————– 

Q What are the benefits of using Multithreading?

 

–>If an exception occurs in a single thread, it will not affect other threads as threads are independent.  

   if the entire program is executed by main thread, and an exception occurs in some part of the program , the entire program will come to a stop.

   if we use multi-threading, different parts of the program will be executed by different threads. If an exception occurs in some part of the program

    , only that part(thread) will stop executing and the rest will continue their execution. 

 

–> Muliti-Threading saves time and improves performance  

    If a program is divided into multiple parts, and each part is executed simultaneosly by different threads, then the program will complete

    its execution in a very less period of time.

 

–> In Multi-Thread resources are shared, thus saving memory

 

————————————————————————————————————————————————————————————————– 

Q What are the two ways of implementing thread in Java?  

 

  1. Extending the Thread class 

   –> class MyThread extends Thread 

   –> define the job of a Thread inside –> public void run() { …} 

 

   To execute –> MyThread t1 = new MyThread();

                  t1.start();

 

  1. Implementing the Runnable Interface

   –> class MyRunnable implements Runnable

   –> define the job of a Thread inside –> public void run() { …} 

 

To execute –> MyRunnable r = new MyRunnable();

               Thread t1 = new Thread(r);

               t1.start();

 

————————————————————————————————————————————————————————————————– 

Q What’s the difference between thread and process?

 

process: Execution of a program.

thread: Execution of a part of a program.

 

————————————————————————————————————————————————————————————————– 

Q What is Synchronization?

 

The concept of Synchronization is a solution to the Data inconsistency problem.

 

Data inconsistency problem: When 2 threads simultaneously execute a method on the same object, then there maybe a chance of data ininconsistency.

Ex: The bookTicket() method when simultaneously executed by two threads, will create a problem if the seat number is same.

 

To avoid such problem, the method must be declared as synchronized.

Synchronization allows only one thread at a time to execute the method, thus preventing data ininconsistency.

 

————————————————————————————————————————————————————————————————– 

Q LifeCycle of a Thread?

 

TS: Thread Schedular(job is to manage the threads)

 

     Born state                ————->   Ready/Runnable state  —————>  Running state  ———> Dead state

(MyThread t1 = new MyThread)    t1.start();                           if TS allocates                 after a thread

                             Registers the Thread with TS              the processor              completes its execution

 

————————————————————————————————————————————————————————————————– 

Q Context Switching 

  When there are multiple threads on a single processor, then the processor switches from one thread to another to execute all threads.

  Advantage: Every thread gets a chance

————————————————————————————————————————————————————————————————– 

Q What is the join() method in java?

  When an execution of a thread say t1 is dependent on the result of some other thread say t2, then t1 will wait for t2 to 

  complete its execution. 

  Thus t1 thread will call t2.join(), so that after t2 completes its execution, t1 will join the process.

  When t1 calls t2.join(), t1 thread enters into waiting state util t2 completes its execution.

  

  join() is present in: class Thread  

  

  There are 3 overloaded join methods in the class Thread

  join();

  join(milli);

  join(milli, nano); 

  

————————————————————————————————————————————————————————————————– 

Q What is the sleep() method?

  When one thread wants to pause its execution for a specific amount of time, then that thread can call Thread.sleep() method.

  You can call sleep method as follows —> Thread.sleep()  

  sleep() –> class Thread

 

  There are 2 overloaded join methods in the class Thread

  sleep(milli);

  sleep(milli, nano);

 

  If you use the sleep() method by calling Thread.sleep(), 

  complier will generate an error saying unhandled exception of type InterruptedException

  So, you must handle the InterruptedException either try-catch or throws keyword.

————————————————————————————————————————————————————————————————– 

Q Is it possible to start a thread twice? 

  it means, can you call start() on a thread twice?

 

  No, you can only start a thread once.

  once a Thread starts, it will complete its life cycle and enter into dead state

  

  If you try calling start() method twice on the same thread, you will get a runtime exception:  

  “java.lang.IllegalThreadStateException”

 

————————————————————————————————————————————————————————————————– 

Q Can we call the run() method instead of start()?

  No, you cannot call run instead of start(), because start() method is an important method which registers the thread with TS.

  run() cannot register a thread.

 

  start() method is not any ordinary method.

  start() method is present in Thread class and you can call it as: t1.start()

  start() —> 1. To Register the thread with Thread Schedular

  1. To call the run() method

 

  

 

  run() method is method where the job of a newly created thread is defined 

  run() method is present in the Runnable interface

  run() —> 1. Job of a thread

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

————————————————————————————————————————————————————————————————– 

Q What are Daemon Threads ?

  Daemon threads are low priority threads that work in the backgrond of a program execution to give support and services

  to the main threads. 

 

  As a user, you can mark a thread as a daemon by using:       public void setDaemon(boolean status)  –> status–> true/false

  You can check if a thread is daemon thread or not by using:  public boolean isDaemon()

 

————————————————————————————————————————————————————————————————–     

Q Can we make the user thread as daemon thread if we start the thread?

 

  No, if you do so, it will throw IllegalThreadStateException. 

  herefore, we can only create a daemon thread before starting the thread.

 

————————————————————————————————————————————————————————————————–     

Q What is the interrupt() method?

 

  interrupt() method is a method present in ——> class Thread

 

  The interrupt() method can be used to interrupt()(disturb) a thread which is in a sleeping state. 

  It will cause the the thread to come out of the sleeping state.

————————————————————————————————————————————————————————————————–     

Q What is a block

  A block is an anonymos(of no name) piece of code enclosed in the curly braces { }

 

  A block can be of two types : 1. instance block 

  1. static block\

 

  1. Instance block

   –> instance block gets executed automatically when an object/instance of that class is created. 

 

public class Test {

  {

    System.out.println(“Instance block”);

  }

 

  public static void main(String[] args) {

  }

 

}

 

  1. static block

   A static block is executed when the class gets loaded onto the RAM.

   you don’t need an object to be created for the static block to get executed

 

public class Test {

static

  {

    System.out.println(“static block”);

  }

 

   public static void main(String[] args) {

   }

 

}

 

——————————————————————

Q What is Collection : group of elements/Objects

 

Collection(I) is an interface.

Collection interface is the root interface of the Collection Hirarchy.

Collection Hirarchy includes interfaces and classes that implment the core data structures.

 

Collection Interface methods:

 

  1. add(Element);             ——————> adds specified element to the list 
  2. addAll(collection);       ——————> adds collection of elements to the list 
  3. remove(Element);          ——————> removes the specified element from the list 
  4. removeAll(collection);    ——————> removes all the specified elements from the list 
  5. clear();                  ——————> clears the list
  6. contains(Element);        ——————> checks if the specified element is present in the list 
  7. containsAll(collection);  ——————> checks if all the specified elements are present in the list 
  8. retainAll();              ——————> keeps the specified element and removes all the other elements from the list
  9. size();                   ——————> returns the size of the collection(number of elements)
  10. isEmpty();               ——————> checks if the list is empty

 

————————————————————————————————————————————

Q What is List(I): is an interface that extends Collection(I).

Implementing class of the List(I) interfaceL: ArrayList(C), LinkedList(C), Vector(C), Stack(C)

 

As the name suggests, List interface is a parent interface to all the classes that have an indexed data structure i.e., 

where data is ordered in a sequence.

The insertion order of the elements added is preserved.

Duplicates are allowed.

 

Methods of List(I) interface: 

 

  1. add(int index, elememt e)
  2. addAll(int index, collection c)
  3. remove(int index)
  4. get(int index)
  5. indexOf(element e)
  6. lastIndexOf(element e)
  7. set(int index, element e)
  8. subList(int fromIndex, int toIndex)

 

————————————————————————————————————————————

Q What is ArrayList(C): is a class that implements List(I)

ArrayList also implements: Serializable(I), Cloneable(I), RandomAccess(I)

 

–> The underlying data structure of ArrayList is Array(i.e. ArrayList is based on Array only).

–> ArrayList is growable in size, whereas Array is fixed in size

–> ArrayList can store Heterogenous elements(of mixed datatypes int, float, Student, Employee), whereas Array can only store homogenous elements (similar data type elements)

–> The default size/capacity of an ArrayList is 10.  –> ArrayList al = new ArrayList() creates an Arraylist with default size 10

–> If the ArrayList gets full, then the size of new ArrayList is as follows 

                                                     new size = (size*3/2) + 1;  // (10*3/2) + 1 = 16

 

–> Multithreading is allowed on an ArrayList object to acheive to high performance. 

    Hence ArrayList is not Thread Safe.

–> since ArrayList supports multithreading, performance is high.

 

————————————————————————————————————————————

Q What is Vector(C): is a class that implements List(I)

Vector also implements: Serializable(I), Cloneable(I), RandomAccess(I)

Vector: is also a resizable array 

–> The underlying data structure of Vector is Array(i.e. Vector is based on Array only)

–> Vector is growable in size.

–> Vector can store Heterogenous elements.

–> The default size of Vector is 10

–> If the Vector gets full, then the size of the new Vector is doubled

                                              new size = size*2;  // 10*2 = 20

 

–> Vector does not support multithreading as Vector is synchronized in nature.(only one thread allowed at a time)

    Thus Vector is Thread safe

–> Since vector is synchronised, the performance is low.

Do watch our Java Video: Click Here

Author:-

Onkar Nagarkar

Call the Trainer and Book your free demo class for Java now!!!

© Copyright 2020 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*