DronaBlog

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

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...