Java Interview Questions - Core Faq - 1

Is there any need to import java.lang package?

No, you don't need to import java.lang.*; All classes in the java.lang package are imported by default and it includes the core Java language classes.

Is JDK required on each machine to run a Java program?

No, JDK (Java Development Kit) isn't required on each machine to run a Java program. Only JRE is required, it is an implementation of the Java Virtual machine (JVM), which actually executes Java programs. JDK is development Kit of Java and is required for development only. It is a bundle of software components that is used to develop Java based applications.

What is a package?

Packages are used to organizes a set of related classes and interfaces . Programs are organized as sets of packages. Each package has its own set of names for types, which helps to prevent name conflicts . Package constructs can be mapped to a file system.
System.Security.Cryptography.AsymmetricAlgorithm ssa;

can be replaced:

import System.Security.Crypography; class xxx { ... AsymmetricAlgorithm aa; ..... }

Package cannot be nested. One source file can only have one package statement.

How can I convert my Java program to an .exe file?

Yes, there are many options available to make a Java program to a .exe file like Executable Jar File , JSmooth, JexePack, LaunchAnywhere etc. But there is a simple way, to make a .bat file with the following code:
start javaw -jar YourJarFile.jar
then convert the bat to an exe using any .bat to .exe converter.

How many types of memory areas are allocated by JVM?

There are five type of memory allocated by JVM

  1. Class(Method) Area
  2. Heap
  3. Stack
  4. Program Counter Register
  5. Native Method Stack

Java is Pass by Value or Pass by Reference?

Java is always pass-by-value , not reference. Java does manipulate objects by reference, and all object variables are references . So Objects, Arrays, Primitive Types etc. – these are all passed by value in Java.
  1. Pass by Value: When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.
  2. Pass by Reference: When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable.
  3. <

List primitive Java types?

Primitive types are the most basic data types available within the Java language . It is predefined by the language and is named by a reserved keyword . The eight primitive data types supported by the Java programming language are: boolean, char, byte, short, int, long, float and double.
  1. boolean, the type whose values are either true or false
  2. char, the character type whose values are 16-bit Unicode characters

the integer types:

  1. byte
  2. short
  3. int
  4. long

the floating-point types:

  1. float
  2. double

Is null a keyword?

No, null is not a keyword . The null is a literal similar to true and false in java, but it is a character string that is treated specially by the compiler if the compiler encounters it in a java source file . It treated as a reserved word in java language.

Are true and false keywords?

No, true, false, and null are not Java keywords , they are literals. Literals are something which are actual values not the variable names. If you try to use them as variables you will get compile error saying - invalid VariableDeclaratorId. They treated as reserved words in java language and you cannot use them as identifiers in your programs.

What is a JAR file?

A JAR file is actually just a ZIP file, typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one compressed file for distribution. The jar tool provides many switches, some of them are as follows:
  1. -c creates new archive file.
  2. -v generates verbose output.
  3. -m includes manifest information from the given mf file.
  4. -f specifies the archive file name.
  5. -x extracts files from the archive file.

How to run a JAR file through command prompt?

java -jar <jar-file-name>.jar
In case, if you don't have a manifest in your jar file the above method will not work.

Try this command if you don't have a manifest:

java -cp my.jar full.package.name.ClassName

How to get the path of a running JAR file?

String jarPath = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(jarPath, "UTF-8");

Default value of data types in java

There are two data types available in Java -

  1. Primitive Data Types
  2. Reference/Object Data Types
Primitive datatypes are predefined by the language and named by a keyword. There are eight primitive datatypes supported by Java. Following are the default value of DtataTypes.
byte:0 short:0 int:0 long:0L float:0.0f double:0.0d char:'u0000' boolean:false

What is type casting?

Type Casting really means that, taking an Object of one particular type and "turning it int" another Object type. This process is called casting a variable. Example
Object obj = "str"; String str = (String)obj;
In the above case, the object being stored in 'obj' is actually a string , and therefore we can cast to a string without any problems. There are two ways casting could go wrong. Firstly, if you are casting between two types in completely different inheritance hierarchies then the compiler will fail and stop you: Example
String obj = "str"; Integer str = (Integer)obj;

In the above casting compilation will fail.

Secondly, if they are in the same hierarchy but still an invalid cast then a ClassCastException will be thrown at runtime. Example
Number num = new Integer(5); Double n = (Double)num;
In the above case ClassCastException will thrown. More about.... Type Casting in Java

What is Upcasting ?

Up-casting is casting to a supertype, while Downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException . Generally, upcasting is not necessary. Casting a subtype object into a supertype is called upcast . In Java, we need not add an explicit cast and you can assign the object directly. Compiler will understand and cast the value to supertype. By doing this, we are lifting an object to a generic level . If we prefer, we can add an explicit cast and no issues. Example
public class AnimalFeeding { public void feed(Animal animal) { animal.startFeeding(); animal.stopFeeding(); } }
Here, the feed() method can accept any object which is subtype of Animal. So objects of type Dog and Cat will be upcasted to Animal when they are passed into this feed() method:
Dog dog = new Dog(); Cat cat = new Cat(); AnimalFeeding feeding = new AnimalFeeding(); feeding.feed(dog); feeding.feed(cat);
More about.... Type Casting in Java

What is Downcasting?

Downcasting is casting to a subtype , while Up-casting is casting to a supertype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException . By doing Downcasting, we are telling the compiler that the value stored in the base object is of a super type . Then we are asking the runtime to assign the value. Because of downcast we get access to methods of the subtype on that object. When performing downcasting, that you’re well aware of the type of object you’ll be casting. Example
Animal animal = new Dog(); Dog castedDog = (Dog) animal;
Here, we cast the Animal type to the Dog type. As Dog is subclass of Animal, this casting is called downcasting . Downcasting can fail if the actual object type is not the target object type . Example
Animal animal = new Cat(); Dog dog = (Dog) animal;
The above code will throw a ClassCastException because the actual object type is Cat. And a Cat is not a Dog so we cannot cast it to a Dog. More about.... Type Casting in Java

Can a double value be cast to a byte?

No, Java will not implicitly narrow a primitive value . You cannot cast from a double to byte because the byte has a range smaller than the double and it does not contain decimals like a double does. You can explicitly cast it to a Byte via a boxing conversion. This guards against accidental loss of precision.
Byte r = (byte) x;
When you cast the double to a byte (lowercase) explicitly; then Java will implicitly box the byte into a Byte .

Why not use Double or Float to represent currency?

Because floats and doubles cannot accurately represent the base 10 multiples we use for money, so it is impossible to represent 0.1 (or any other negative power of ten). This issue is not only in Java, it's for any programming language that uses native floating-point types , as it stems from how computers handle floating-point numbers by default. Example

Suppose you have $1.03 and you spend 42c. Calculate how much money remaining you?

System.out.println(1.03 - .42);

It prints 0.6100000000000001.

The solution to this problem is to use BigDecimal , int or long for monetary calculations.

What is the default value of Boolean?

  1. The default value for a boolean (primitive) is false.
  2. The default value for a Boolean (object) is null.

What is default value of a local variables?

The local variables are not initialized to any default values.

Normally, local variables are declared to do some calculation. So its the developer's decision to set the value of the variable and it should not take any default value. If the developer, by mistake, did not initialize a local variable and it take default value, the java compiler throws error. So in case of local variables, the compiler will ask the developer to initialize with some value before they access the variable to avoid the usage of undefined values.

What are the advantage of a Java enum?

  1. Set of Constant declaration
  2. Restrict input parameter in method
  3. Can be usable in switch-case
  4. Type safety and value safety
More about.... Enum in Java

Can Enum extend any class in Java?

No, Enum types are final by design. An enum cannot extends another class because an enum already extends Enum < T > . That class provides all the enum functionality. All enums implicitly extend java.lang.Enum . Because a class can only extend one parent and the Java language does not support multiple inheritance of state, therefore an enum cannot extend anything else. More about.... Enum in Java

What is the importance of main method in Java?

The main() method is the starting point of an application. When a program starts running, it has to start execution from somewhere. That somewhere is called main. Without it, there is no place to start running a Java program. Every Java application must contain a main method whose signature looks like this:
public static void main(String[] args){ }

How the main Method Gets Call

When the Java interpreter executes an application, it starts by calling the class's main() method. The main method then calls all the other methods required to run your application. If you try to invoke the Java interpreter on a class that does not have a main method, the interpreter refuses to compile your program and displays an error message similar to this:
In class NoMain: void main(String argv[]) is not defined

Why is the main() method declared static?

The main method is static because it keeps things simpler. Since the main method is static JVM (Java virtual Machine) can call it without creating any instance of a class which contains the main method. The main() method must be declared public, static, and void. It must accept a single argument that is an array of strings. This method can be declared as either:
public static void main(String[] args)

or

public static void main(String... args)

Can we execute a program without main() method?

No. Prior to Java 7 , you can compile and execute without main() method By using static block. Example
public class TestClass { static { System.out.println("Message"); System.exit(0); } }
The System.exit(0) lets the program exit before the Java Virtual Machine is looking for the main() method, otherwise the following error will be thrown:
Exception in thread "main" java.lang.NoSuchMethodError: main

Should a main() method be compulsorily declared in all java classes?

No, the main method is the default entry point for a programme. That doesn't mean that, every java class should contain main method. It is driver program which handles all other java files . It is important to note that all classes of java should be connected with main() method directly or indirectly.

Does the order of public and static declaration matter in main()?

The method names comes last (main), the return type the second to last (void), and then after that it's your choice.

Example
public class TestClass { static public void main(String[] args) { System.out.println("Hello"); } }

Can main() method in Java can return any data?

No. The main method's return type must be void, because the java language specification enforces it. You can't change the return type of main() . Once the main is finished the program is dead, so you don't have any benefit from that.

How we can execute any code even before main method in Java?

Up to Java 6 it was possible to do this using the Static Initialization Block.

Sequence is as follows:

  1. jvm loads class
  2. executes static blocks
  3. looks for main method and invokes it

So, if there's code in a static block, it will be executed.

Example
public class TestClass { static { System.out.println("Hello before main"); } public static void main(String[] args) { System.out.println("Inside Main"); } }
Output
Hello before main Inside Main
From Java 7 , however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:
Main class should contain method: public static void main (String[] args).

Can I override a static methods in Java?

No. In Java, Overriding simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it. Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviours for the same methods defined in the superclass (and overridden in the subclasses). So, static methods also cannot be overridden, because static methods are a part of the Class itself, and not a part of any object(instance) of that class. A static method is not associated with any instance of a class so the concept is not applicable. Overloading : Yes, static methods can be overloaded just like any other method.

What are the restriction imposed on a static method or a static block of code?

A static method do not have direct access to the non-static members. It needs an instance of the class in order to get access to the non-static variable .

A static block cannot return any value from static block and keywords "this", "super" cannot be used.

Can we call a non-static method from inside a static method?

Yes, you can call a non-static method from a static method is to have an instance of the class containing the non-static method.

Can you override a private or static method in Java?

No, you cannot override private method. A private method cannot be overridden because it is not accessible to the derived class.

What is dot(.) operator in Java?

The Dot operator will give access to visible methods and variables of an Object, and static variables and methods of a Class.

What is the % operator?

The modulus operator , % returns the remainder of a division operation. For instance 5 % 2 is 1 because 5 divided by 2 leaves a remainder of 1. It can be applied to floating-point types as well as integer types. (This differs from C/C++, in which the % can only be applied to integer types.)
public class TestClass { public static void main(String[] args) { int i = 5; int j = 2; int k = i % j; System.out.println("i%j is " + k); } }
Output
1

Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely . Syntax
for(;;){}
From the following example, you can see without condition and increment for loop will run indefinitely Example
public class infiLoop { public static void main(String[] args) { for (;;) { System.out.println(i); } } }

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

  1. Unicode requires 16 bits
  2. ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits.
  3. UTF-8 represents characters using 8, 16, and 18 bit patterns.
  4. UTF-16 uses 16-bit and larger bit patterns.

Which non-Unicode letter characters may be used as the first character of an identifier?

The non-Unicode letter characters $ and _ may appear as the first character of an identifier