Pages

April 06, 2016

#Java: Part 6-Core Java Interview Questions and Answers (Wrapper classes, Static variables, methods and imports)

> >  Part 5-Core Java Interview Questions and Answers (Clone and Immutability)

What are Wrapper classes?
A wrapper class wraps (encloses) around a data type and gives it an object appearance. They include methods to unwrap the object and give back the data type. e.g
int intCount = 100;
Integer wrapperIntCount = new Integer(intCount); //this is called Boxing
int intCountBack = wrapperIntCount.intValue(); //thats unBoxing

There are mainly two uses with wrapper classes:
1) To convert simple data types into objects, i.e to give object form to a data type.
2) To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

All wrapper classes have typeValue() method. This method returns the value of the object as its primitive type.

The valueOf() method is available in all wrapper classes except Character.

The 8 primitive types and its wrapper classes are:
byte : - Byte
int : - Integer
short : - Short
long  : - Long
float : - Float
double : - Double
char  : - Character
boolean : - Boolean

Why we need Wrapper classes?
Java is an object-oriented language and can view everything as an object. The primitive data types (like int) are not objects, they do not belong to any class,they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language.

For example, up-to JDK1.4, the data structures accept only objects to store. A data type need to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

What are Static variables, methods, class and block?
Static variables are class variables i.e., there will be only one copy for each class and not one copy for each object of the class and these variables will be accessed without instantiating the class. Static Variables make program memory efficient.

Static methods are class methods because they belongs to the class rather than object of a class. They can be accessed without creating an instance of the class. Static methods cannot access instance variables, they can access only static variables.

Static classes: If you declare a top-level class as a static class, then Java will throw a compilation error. Only the inner classes that are the member classes can be declared as static.

If we declare member classes as static, we can use it as a top-level class outside the context of top-level class. One catch here is "The static keyword does not do to a class declaration what it does to a variable or a method declaration." - what it means is say for example you have a static variable, then to access that static variable you will use the notation

<>.<>
but when you want to use the static inner class, you need to instantiate like
<>.<> newClass = new <>.<>();

Static blocks
 are also called Static initialization blocks is a normal block of code enclosed in braces{ }, and preceded by the static keyword. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes.

If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.

If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.


What are the advantages of static blocks?

  • If you’re loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives.
  • If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded.
  • Security related issues or logging related tasks

What are the limitations for static blocks?

  • There is a limitation of JVM that a static initializer block should not exceed 64K.
  • You cannot throw Checked Exceptions.
  • You cannot use this keyword since there is no instance.
  • You shouldn’t try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.

Can we execute a program without main() method?
Yes, in previous version of JDK before 1.7, we can use static block to execute a program. But in JDK7 and above, we will get 'Main method not found in class, please define the main method as:', when we execute the class.

What is static import in Java 5?
Static import is introduced in Java 5 along with other features like Generics, Enum, Autoboxing and Unboxing and variable argument methods.

The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.

For example without static import you will access static constant MAX_VALUE of Integer class as Integer.MAX_VALUE but by using static import you can import Integer.MAX_VALUE and refer it as MAX_VALUE. Similar to regular import statements, static import also allows wildcard * to import all static members of a class. e.g:

import static java.lang.Integer.MIN_VALUE;
import static java.lang.System.out;
import static java.lang.Math.*;

public class StaticImportTest {
public static void main(String args[]) {
//using out instead of System.out
out.println("Minimum value of int variable in Java without static import : " + Integer.MIN_VALUE);

//instead of double var1= Math.sqrt(5.0);
double var1= sqrt(5.0);
}
  • Static import statements are written as "import static" in code and not "static import".
  • If you import two static fields with same name explicitly e.g. Integer.MAX_VALUE and Long.MAX_VALUE then Java will throw compile time error. But if other static modifier is not imported explicitly e.g. you have imported java.lang.Long.*, MAX_VALUE will refer to Integer.MAX_VALUE.
  • Static import doesn't improve readability as expected, as many Java programmer prefer Integer.MAX_VALUE which is clear that which MAX_VALUE are you referring.
  • You can apply static import statement not only on static fields but also on static methods in Java.
  • If you are going to use static variables/methods a lot then it’s fine to use static imports.
  • Static Imports makes the code confusing and less readable so if you are going to use static members very few times in your code then probably you should avoid using it.  
ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

No comments:

Post a Comment