DronaBlog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, September 3, 2018

Java Interview Questions and Answers - Part 4


Are you preparing for Java interview and looking for information for preparation? Are you also interested in knowing what kinds of questions about Object Oriented concepts are normally asked during Java interview? If so, then this article provides detailed questions and answers about Java, Object Oriented Concepts. This article also provides detailed information about Inheritance concepts. Good luck for your interview.

Q1: What is Object Oriented Programming?
Answer:

A programming style which is associated with the concepts like an object, a class, the inheritance, the polymorphism, an encapsulation and an abstraction is called as Object Oriented Programming.

Q2: What are the core concepts of Object Oriented Programming?
Answer: 

The core concepts of Object Oriented Programming are:

  1. Inheritance
  2. Encapsulation
  3. Abstraction
  4. Polymorphism

Q3: What is inheritance?
Answer:


  • Inheritance is nothing but inheriting properties (behaviour and state) of class into other class. 
  • The process by which one object acquires characteristics from one or more other objects is also termed as inheritance. e.g. children acquire characteristics from their parents.
  • The class from which properties are inherited is called parent class or base class or superclass. 
  • The class in which properties are inherited is called child or derived class or subclass. 
  • It helps to reuse the code and establish a relationship between different classes.
  • The common business logic can be moved from the derived class into the base class to improve maintainability of code.

Q4: What are types of inheritances?
Answer:

There are 4 types of inheritance
1. Single Level Inheritance
2. Multi Level Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance

Q5: Explain types of inheritances?
Answer:

1. Single Level Inheritance:
a. In this type of inheritance, one class inherits the properties of the another class.
b. Properties such as behaviour and state from a single parent class is inherited in child class.
b. It helps to add new feature in existing code as as the code re-usability.

Here, Class Shape is parent class and Class Triangle is child class which inherits the properties and behaviour of the parent class.4

Class Shape
{ ... }
Class Triangle extends Shape 
{ ... }

2. Multilevel Inheritance:
a. If class has more than one parent then it is called Multilevel Inheritance.
b. In the multilevel inheritance, a class is derived from the parent class which is also derived from another parent class.

Here, The class Square is derived from it's parent class Rectangle which is derived from it's parent Shape. The class Square has two parents - Rectangle and Shape respectively. Hence it is a multilevel inheritance.

Class Shape 
{ ... }
Class Rectangle extends Shape
{ ... }
Class Square extends Rectangle
{ ... }

3. Hierarchical Inheritance:
a. In the hierarchical inheritance the parent class has more than one child classes.
b. We can also state that if more than one child classes have the same parent class then it is a hierarchical inheritance.

Here, the super class Shape has two sub classes - Triangle and Rectangle, hence it is a hierarchical inheritance.

Class Shape 
{ ... }
Class Triangle extends Shape 
{ ... }
Class Rectangle extends Shape 
{ ... }

4. Hybrid Inheritance:
a. It is a combination of multiple inheritance and multilevel inheritance.
b. The multiple inheritance is not supported in Java as it leads to ambiguity.
c. Java supports multiple interfaces inheritance.


Q6: What is Implementation inheritance?
Answer:

a. Implementation inheritance is also know as class inheritance.
b. We can extend an functionality by reusing functionality in the super class by inheriting all or some of the operations already implemented.
c. In Java, we can only inherit from one superclass.
d. It helps in code reusability.
e. Improper use of class inheritance can cause problem in making future changes.
f. The subclass becomes tightly coupled with the superclass.
g. We have to make sure that the subclasses depend only on the behavior of the superclass, not on the actual implementation.

Q7: What is Interface inheritance?
Answer:

a. Interface inheritance is also know as type inheritance or as subtyping.
b. Interface inheritance reduces the coupling or implementation dependencies between systems.
c. It promotes the design concept of program to interfaces not to implementations.
d. We can implement any number of interfaces.
e. As this type of implementation will not influence specific subclass implementations, hence it is more flexible than implementation inheritance.

                                   

Friday, August 17, 2018

Java Interview Questions and Answers - Part 3


Are you preparing for Java interview and looking for material for preparation? Are you also interested in knowing what kinds of questions are normally asked during Java interview? If so, then this article provides detailed questions and answers about Java. Good luck for your interview.

Q1: What is marker interface in Java?
Answer:  The interface with no defined methods is called marker interface. Such interface acts as a marker which tells the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently.

For example, java.io.Serializable, java.lang.Cloneable etc. are marker interfaces 
  • Marker interface also called as ‘tag’ interface as they tag the derived classes into a specific category based on usage.
  • We can write custom marker interface. 

Q2: What is method in Java?
Answer:
  • A Java method in java is a set of statements that are grouped together to perform an operation
  • It can be called at any point in the program using the method's name.
  • The method is a subprogram which works on the data.
  • Method has return type, so it either return some value or it may return void. 

     For example, in the sample code below area() is method. 
    class Triangle 
        public int area(int param1, int param2) {
        return (1/2*param1*param2);
     }

Q3: What is method overloading and method overriding?
Answer:

  1. Method overloading means multiple methods in the same class with the same name but different method signatures. We can define the same operation in different ways for different data.

          For example -
       class Shape {
            public void calculateArea(int param) {…}
            public void calculateArea(int length, int width){}
        }
     
      2. Method overriding means two methods with same name and signatures, one in the parent class and the other one in the child class. We can define the same operation in different ways for different object types.

             For example - In the example below, method name 'area(int length)' is same. The signature of method in parent and child class is also same. Here, the child class Square overrides 'area' method from parent class - Shape.
       class Shape{
             public void area(int length) {…}
        }

       class Square extends Shape {
             public void area(int length) { …}
        }

Q4: Is Java 100% Object Oriented?
Answer: The Java technology is based on Object Oriented concepts. However, it does not follow 100% Object Oriented. Java uses eight primitive data types such as int, float, double , boolean, byte, char, long, short which are not objects.  Hence it is not fully Object Oriented.

Q5: What is an Object in Java?
Answer: Object is an entity which has state and behavior. State is presented through fields and behavior is presented through methods.  Person, Table, TV, Home etc . are examples of an object.

For example, assume person as an object.
It has state - weight, height, gender, eye color, hair color etc.
It has behavior - walk, speak, listen etc.


                                   



Thursday, August 16, 2018

Java Interview Questions and Answers - Part 2

This is the second article of the Java Interview Questions and Answers series. In the previous article we learned about basic questions related to classpath, Object Oriented Approach and the difference between C++ and Java languages. In this article we will learn more interesting questions which are asked during Java Interview Questions. If you are preparing for your Java interview then read this article to get more knowledge about Java technology.


Q1: What are the class loaders in Java? 

Answer: 

Do you know how the very first class gets loaded in JVM? The first class is loaded with the help of main() method in the Java class. Once first class is loaded, the subsequent classes are loaded by other classes. All JVMs include one class loader called the bootstrap class loader. The JVM also includes the user defined class loader which helps to load classes in a particular order.

  • Class loaders are hierarchical. 
  • These class loaders use a delegation model when loading a class in JVM. 
  • Child class loader requests its parent to load the class first before attempting to load it themselves. 
  • Once class is loaded in JVM, child class loader will not load it again. 
  • Classes loaded by the parent class loader will not have any visibility into classes loaded by its child. 
  • However, classes loaded by a child class loader have visibility in the parent class loader.

The types of class loader are mentioned below:
a) Bootstrap: Loads JDK internal classes, java.* packages. (rt.jar and i18n.jar)
b) Extensions: Loads jar files from JDK extensions directory (classes in the lib/ext directory of JRE)
c) System: Loads classes from system classpath (CLASSPATH environment variable or –classpath or –cp command line options)
  • Classes loaded by the Bootstrap class loader have no visibility into classes loaded by the Extensions and Systems class loaders or any other child class loader.
  • The classes loaded by System class loader have visibility into classes loaded by Extensions and Bootstrap class loaders, but they will not have visibility in classes loaded by Class loader 1 or Class loader 2.
  • If there are any sibling class loaders they cannot see classes loaded by each other. 

Q2: What is static class loader in Java?
Answer: 
  • Creating objects and instance using new keyword is known as static class loading
  • The retrieval of class definition and instantiation of the object is done at the compile time.
  • Classes are statically loaded with “new” operator in Java as

        class MyTestClass {
             public static void main(String args[]) {
             Shape shape = new Shape();
        }

If a class is referenced with “new” operator  but the runtime system cannot find the referenced class then NoClassDefFoundException exception is thrown.

Q3: What is dynamic class loader in Java?
Answer: 
  • Loading classes use Class.forName () method. 
  • Dynamic class loading is done when the name of the class is not known at compile time.  e.g. 

    Class oclass = Class.forName (String className); //It is static   method which returns a Class

In the example below, the dynamic loading will decide whether to load the class Shape or
the class Triangle at runtime based on  runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class.

   oclass.newInstance (); //creates an instance of a class
   Triangle otriangle = null ;
   String myClassName = "com.abc.Triangle" ; // can be read at  runtime
   Class shapeClass = Class.forName(myClassName) ;
   otriangle = (Triangle) shapeClass.newInstance();
   otriangle.getArea();

If no definition for the class with the specified name could be found then ClassNotFoundException exception will be thrown for methods mentioned below:
  • forName(…)- Class.
  • findSystemClass(…)- ClassLoader.
  • loadClass(…)  - ClassLoader

Q4: What is constructor in Java?
Answer: A constructor in Java is a block of code similar to a method which is used to initialize the object of a class.

  • It is called when an instance of an object is created.
  • It cannot be static, final, abstract, final and synchronised. 
  • It does not have return type.
  • It must have the same name as the class name.
  • It is called only once per creation of an object.

e.g.
     Pet.class
     public Pet() {} // constructor

Q5: What will happen if you do not provide a constructor to Java class?
Answer:

  • Explicit constructor is not required in the Java class. 
  • The Java compiler will create a default constructor in .class file with an empty argument, if we do not provide the constructor. 
  • The definition of default constructor looks like as "Country(){}". 
  • Java compiler does not create default constructor, if a class includes one or more explicit constructors like "public Country(int id)" or "Country(){}" etc.


Tuesday, August 14, 2018

Java Interview Questions and Answers - Part I

 Are you looking for which questions are asked during a Java interview? If so, then refer to this question and answer article on Java and supporting technologies. This article explains all Java related concepts in detail. This is the first article of the Java Interview Questions and Answers series.


Q1: What are the differences between Java and C++?
Answer:

Sr. No.
Java
C++
1
Java does not support pointers. Pointers are inherently tricky to use and troublesome.
C++ supports pointers.
2
Java does not support multiple inheritances because it causes more problems than it solves.
C++ supports multiple inheritances.
3
Java does not support destructors but adds a finalize() method. Finalize methods are called by the garbage collector prior to reclaiming the memory occupied by the object.
C++ supports destructors which are automatically invoked when the object is destroyed.
4
Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework.
C++ includes structures.
5
Java includes automatic garbage collection.
C++ requires explicit memory management.
6
Java has built in support for threads. In Java, there is a Thread class that you inherit to create a new thread and override the run() method.
C++ has no built in support for threads. C++ relies on non-standard third-party libraries for thread support.
7
Pointers, references, and pass-by-value are supported for all types (primitive or user-defined).
All types (primitive types and reference types) are always passed by value.


Q2: Explain the Java Platform.
Answer:
  • It is a software-only platform and it runs on top of other hardware-based platforms like UNIX, NT etc.
  • Java has a set of classes written in the Java language. Such classes are called the Java Application Programming Interface (Java API). It runs on the Java Virtual Machine.
  • Java Virtual Machine (JVM) is a software that is installed on the hardware platforms. JVM uses Byte codes as the machine language.

Q3 : What are the uses of Java packages? 
Answer:
Java package is a namespace. It helps to group a set of related classes and interfaces together. e.g. java.lang package is used to  group classes to the design of the Java programming language. Packages play a significant role in resolving conflicts in class names. 

For example, in the real time world we keep documents in one folder, images are kept in a separate folder and scripts or code are kept in a different folder. Packages keep classes in different packages for better organization of source code and also to resolve conflicts if class names are the same.

In order to create a package for your class use the statement below as the first statement - 
package com.abc.pqr;

Here, package is the keyword in Java and com.abc.pqr is the package name.

If you are going to import any other class then import the package in your class as,
import java.io.*;


Q4: What is Classpath in Java?
Answer: Classpath is a parameter in the Java Virtual Machine. It specifies the location of user-defined classes and packages. It can be set either on the command-line or through an environment variable.

Have you noticed the error below while running the  Java program?
Exception in thread "main" java.lang.NoClassDefFoundError: com/abc/pqr/MyWorld

If so, then you have not set the classpath in your system. To resolve this issue you can use one of the approaches below -

1. Set your project in the CLASSPATH environment variable of your system. e.g. "c:/TestProject"
2. Set the jar file of your project in the CLASSPATH environment variable of your system. This jar file should contain your .class file.to have a jar file e.g. we need to set the "c:/TestProject/HelloWorld.jar"" jar file in CLASSPATH and this .jar file has the MyWorld.class file in it. 
3. Run it with –cp or –classpath commands as shown below:
c:\>java –cp c:/TestProject com.abc.pqr.MyWorld
OR
c:\>java -classpath c:/TestProject/HelloWorld.jar com.abc.pqr.MyWorld


Q5: What are the advantages of the Object Oriented Approach?
Answer: Java is the Object Oriented Language and it comes with the benefits mentioned below due to its Object Oriented approach:
  1. We can achieve code re-usability with help of implementation inheritance and object composition.
  2. Everything in Java is an object and it maps to the real world. E.g vehicles, customers
  3. It helps to create modular architecture with the help of objects, systems, frameworks etc which are the building blocks of the big application.
  4. An Object Oriented Program forces designers to go through an extensive planning phase, which makes for better designs with less flaws.
  5. An Object Oriented Program is much easier to modify and maintain than a non-Object Oriented Program. 



Tuesday, July 17, 2018

How to Clear the Java Web Start (javaws) cache on a local client machine

Are you looking for an article on how to clear the Java Web Start cache? This articles provides various ways by which you can clear the Java Web Start Cache.

Why clear the Java Cache?
Most of the time, the Java update occurs automatically so the system updates to the higher Java version. For security reasons, it is recommended to always maintain the most current stable higher Java version. Sometimes the higher version of Java is installed to support other applications. The Java cache is created for better performance of your Java application. So the Java cache will be out of sync when the Java upgrade happens. Due to this, the application will behave inconsistently. To avoid such inconsistent behavior of an application, we need to clear the Java Cache.

How to clear the cache?
There are three ways by which we can clear Java cache :
1. Using Java Configure Mode
2. Using command line
3. Manually deleting file

  1. Using Java Configure Mode -

  • In this mode, if you are using windows system then go to Start -> Search function. Then type, Java. Several options will  popup. Select the Configure Java option from it.
  • Once you select, the Configure Java option and click on it, it will take us to the dialog box 'Java Control Panel'. In this dialog click on the 'Settings' tab.

  • Once we click on 'the Settings' button, it will take us to another dialog box - 'Temporary Files Settings'. In this dialog box, click on Delete Files to delete the Java cache. 


2. Using Command Line Mode -

  • Open your computer's DOS prompt by selecting the Start menu followed by the Run option. 
  • Enter 'command' followed by pressing the Enter key.
  • Type javaws at the DOS prompt followed by the Enter key to see the Java Web Start command-line options.
  • Type javaws -Xclearcache followed by the Enter key to clear Java Web Start Cache on your computer. 
  • After the cache has been cleared, the local drive prompt will appear on the DOS prompt.

3. Manually Deleting Files -

  • Delete the cache folder located in C:\Users\<user>\AppData\LocalLow\Sun\Java\Deployment on Windows 7.
  • For other Operating System versions, you might have to do the delete operation in the appropriate Sun Java folder.

Tuesday, July 3, 2018

How to handle NoSuchMethodException exception

Scenario : 
The exception - NoSuchMethodException occurs if the setter or the getter method does not present in classes created during the WSDL skeleton or the client generation.

public class ElectronicAddressRequest {
    protected List<ElectronicAddressSO> electronicAddress;

    public List<ElectronicAddressSO> getElectronicAddress() {
        if (electronicAddress == null) {
            electronicAddress = new ArrayList<ElectronicAddressSO>();
        }
        return this.electronicAddress;
    }


Here is what the ElectronicAddressSO class looks like below :

public class ElectronicAddressSO {

    protected String electronicAddress;
    protected String electronicAddressType;

    public String getElectronicAddress() {
        return electronicAddress;
    }

     public void setElectronicAddress(String value) {
        this.electronicAddress = value;
    }

     public String getElectronicAddressType() {
        return electronicAddressType;
    }

     public void setElectronicAddressType(String value) {
        this.electronicAddressType = value;
    }

}

In the above code, the setter method is not created for the ElectronicAddressRequest if you use the wsdl2j tool to create the skeleton.

Error  :

When you try to run the application you will get the error below.

weblogic.wsee.jaxws.framework.policy.advertisementimpl.AdvertisementHelperImpl registerExtension
WARNING: Registering oracle.j2ee.ws.wsdl.extensions.addressing.AddressingExtensionRegistry extension failed; java.lang.NoSuchMethodException: oracle.j2ee.ws.wsdl.extensions.addressing.AddressingExtensionRegistry.registerSerializersAndTypes(com.ibm.wsdl.extensions.PopulatedExtensionRegistry)
Mar 11, 2015 12:22:12 PM weblogic.wsee.jaxws.spi.WLSServiceDelegate addWsdlDefinitionFeature
SEVERE: Failed to create WsdlDefinitionFeature for wsdl location: http://rmv-eap-spr-d11.ddc.dot.state.ma.us:57453/MARMV_MainFrame_Provider/LicenseUpdateService?wsdl, error: com.sun.xml.ws.wsdl.parser.InaccessibleWSDLException, message: 2 counts of InaccessibleWSDLException.


Solution :
In order to handle this error, add the method below in the ElectronicAddressRequest class :


public void setElectronicAddress(ElectronicAddressSO oElectronicAddressSO) {
        if (null != electronicAddress) {
            electronicAddress.add(oElectronicAddressSO);
        } else {
            List<ElectronicAddressSO> listContactInformation = new ArrayList<ElectronicAddressSO>();
            listContactInformation.add(oElectronicAddressSO);
            this.electronicAddress = listContactInformation;
        }
    }

What is CRM system?

  In the digital age, where customer-centricity reigns supreme, businesses are increasingly turning to advanced technologies to manage and n...