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.
can be replaced:
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:
How many types of memory areas are allocated by JVM?
There are five type of memory allocated by JVM
- Class(Method) Area
- Program Counter Register
- 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.
- 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.
- 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. <
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.
- boolean, the type whose values are either true or false
- char, the character type whose values are 16-bit Unicode characters
the integer types:
the floating-point types:
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:
- -c creates new archive file.
- -v generates verbose output.
- -m includes manifest information from the given mf file.
- -f specifies the archive file name.
- -x extracts files from the archive file.
How to run a JAR file through command prompt?
Try this command if you don't have a manifest:
How to get the path of a running JAR file?
Default value of data types in java
There are two data types available in Java -
- Primitive Data Types
- Reference/Object Data Types
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
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
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
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
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.
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?
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?
- The default value for a boolean (primitive) is false.
- 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?
- Set of Constant declaration
- Restrict input parameter in method
- Can be usable in switch-case
- Type safety and value safety
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:
How the main Method Gets CallWhen 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:
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:
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
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
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:
- jvm loads class
- executes static blocks
- looks for main method and invokes it
So, if there's code in a static block, it will be executed.Example
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.)
Can a for statement loop indefinitely?Yes, a for statement can loop indefinitely . Syntax
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
- Unicode requires 16 bits
- ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits.
- UTF-8 represents characters using 8, 16, and 18 bit patterns.
- 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
- Java Interview Questions-Core Faq - 2
- Java Interview Questions-Core Faq - 3
- Important features of Java
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- What is NullPointerException in Java
- Difference between Stack and Heap memory in Java
- How to set the maximum memory usage for JVM?
- What is numeric promotion?
- Why do we need Generic Types in Java?
- What does it mean to be static in Java?
- What are final variables in Java?
- How Do Annotations Work in Java?
- How do I use the ternary operator in Java?
- What is instanceof keyword in Java?
- How ClassLoader Works in Java?
- What are fail-safe and fail-fast Iterators in Java
- What are method references?
- "Cannot Find Symbol" compile error
- Difference between system.gc() and runtime.gc()
- How to convert TimeStamp to Date in Java?
- Does garbage collection guarantee that a program will not run out of memory?
- How setting an Object to null help Garbage Collection?
- How do objects become eligible for garbage collection?
- How to calculate date difference in Java
- Difference between Path and Classpath
- Is Java "pass-by-reference" or "pass-by-value"?
- Difference between static and nonstatic methods java
- Why Java does not support pointers?
- What is package in Java?
- What are wrapper classes?
- What is singleton class in Java?
- Difference between Java Local Variable, Instance Variable and a Class Variable?
- Can a top level class be private or protected in java
- Are Polymorphism , Overloading and Overriding similar concepts?
- How to Use Locks in Java
- Why Multiple Inheritance is Not Supported in Java
- Why Java is not a pure Object Oriented language?
- Why can't a Java class be declared as static?
- Difference between Abstract class and Interface in Java
- Why do I need to override the equals and hashCode methods in Java?
- Why does Java not support operator overloading?
- What’s meant by anonymous class in Java?
- Static Vs Dynamic class loading in Java
- Why am I getting a NoClassDefFoundError in Java?
- How to generate random integers within a specific range in Java
- What's the meaning of System.out.println in Java?
- What is the purpose of Runtime and System class?
- What is finally block in Java?
- What is difference between final, finally and finalize?
- What is try-with-resources in java?
- What is a stacktrace?
- What is the meaning of immutable in terms of String?
- What are different ways to create a string object in Java?
- Difference between String and StringBuffer/StringBuilder in Java
- What is the difference between creating String as new() and literal?
- How do I convert String to Date object in Java?
- How do I create a Java string from the contents of a file?
- What actually causes a StackOverflow error in Java?
- Why is char preferred over String for storage of password in Java
- What is I/O Filter and how do I use it in Java?
- Serialization and Deserialization in Java
- Understanding transient variables in Java
- What is Externalizable in Java?
- What is the purpose of serialization/deserialization in Java?
- What is the Difference between byte stream and Character streams
- How to append text to an existing file in Java
- Read/convert an InputStream to a String in Java
- What is the difference between Reader and InputStream in Java
- Introduction to Java threads
- What is synchronization Java?
- Static synchronization Vs non static synchronization in Java
- Java Thread Deadlock Tutorial
- What is Daemon thread in Java
- Difference between implements Runnable and extends Thread in Java
- What is the volatile keyword in Java
- What are the basic interfaces of Java Collections Framework
- What are the differences between ArrayList and Vector in Java
- What is the difference between ArrayList and LinkedList?
- What is the difference between List and Set in Java
- Difference between HashSet and HashMap in Java
- Difference between HashMap and Hashtable in Java?
- How does the hashCode() method of java works?
- Difference between capacity() and size() of Vector in Java
- What is a Java ClassNotFoundException?
- How to fix java.lang.UnsupportedClassVersionError