Q:What do you know about Java? A:Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Q: What is java and why it came into existence? A:Java is a programming language provided with application developement and deployment environment. It came into existence because of following objectives/features: 1) To over come problem in C++ like pointer, 2) MultiThreading 3) Platform Independent 4) Automatic garbage collection 5) Improved security and many more. Q:What is JVM and is it platform independent? A:Every Java program is first compiled into an intermediate language called Java bytecode. The JVM is used primarily for 2 things: the first is to translate the bytecode into the machine language for a particular computer, and the second thing is to actually execute the corresponding machine-language instructions as well. The JVM and bytecode combined give Java its status as a portable language - this is because Java bytecode can be transferred from one machine to another. Since the JVM must translate the bytecode into machine language, and since the machine language depends on the operating system being used, it is clear that the JVM is platform (operating system) dependent. Q:What is the difference between JVM and JRE? A:Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn't contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed. Q:What if the main method is declared as private? A:The program compiles properly but at runtime it will give "Main method not public." message. Q:What if the static modifier is removed from the signature of the main method? A:Program compiles. But at runtime throws an error "NoSuchMethodError". Q:Can static methods be overridden? A:We can declare static methods with same signature in subclass, but it is not considered overriding as there won't be any run-time polymorphism. Hence the answer is 'No'. If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class. Q:What if I write static public void instead of public static void? A:Program compiles and runs properly. Q:What gives Java its 'write once and run anywhere' nature? A:Java code is not compiled to machine code or linked to any libraries. Java code is compiled into java bytecode, which is an almost-machine code. Then, that byte code is fed to a Java Virtual Machine. It's this program that turns the Java program into commands for the computer. Since the Java Virtual Machine does this translation, the same byte code will run on any platform that has a working JVM. Q:What is difference between path and classpath variables? A:PATH: It is set for providing path for all Java tools like java, javac, javap, javah, jar, appletviewer. In Java to run any program we use java tool and for compile Java code use javac tool. All these tools are available in bin folder so we set path upto bin folder. CLASSPATH: It is set for providing path of all Java classes which is used in our application. All classes are available in lib/rt.jar so we set classpath upto lib/rt.jar. Q:Why main method is static? A:Because object is not required to call static method if it is non-static method,jvm creates object first then call main() method that will lead to the problem of extra memory allocation. Q:How can one prove that the array is not null but empty using one line of code? A:Print arr.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print arr.length. Q:Can we execute a program without main() method? A:Yes, one of the way is static block. Q:What if I do not provide the String array as the argument to the method? A:Program compiles but throws a runtime error "NoSuchMethodError". Q:Can an application have multiple classes having main method? A:Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict among the multiple classes having main method. Q:Can I have multiple main methods in the same class? A:As long as method parameters (number (or) type) are different, yes they can. It is called overloading. Overloaded methods are differentiated by the number and the type of the arguments passed into the method. public static void main(String[] args) only main method with single String[] as param will be considered as entry point for the program. Q:Java-passed by value or by reference? A:Java is always pass-by-value. Unfortunately, they decided to call pointers references, thus confusing newbies. Because those references are passed by value. It goes like this: public static void main( String[] args ){ Dog aDog = new Dog("Max"); foo(aDog); if (aDog.getName().equals("Max")) { //true System.out.println( "Pass by value." ); } else if (aDog.getName().equals("Fifi")) { System.out.println( "Pass by reference." ); } } Next Example: public static void foo(Dog d) { d.getName().equals("Max"); // true d = new Dog("Fifi"); d.getName().equals("Fifi"); // true } In this example aDog.getName() will still return "Max". The value aDog within main is not overwritten in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo. Likewise: Dog aDog = new Dog("Max"); foo(aDog); aDog.getName().equals("Fifi"); // true public void foo(Dog d) { d.getName().equals("Max"); // true d.setName("Fifi"); } In the above example, FiFi is the dog's name after call to foo(aDog) as in Java the values are passed-by-value i.e. a copy of an object is made and passed to a function. On returning from the function, the copy is again copied back to the original passed object. So, the value set in the function is copied back. Q:What is OOP concept? A:Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Object: Any entity that has state and behavior is known as an object. For example: chair Class: Collection of objects is called class. It is a logical entity. Inheritance: When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism. Polymorphism: When one task is performed by different ways i.e. known as polymorphism.In java, we use method overloading and method overriding to achieve polymorphism. Abstraction: Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.In java, we use abstract class and interface to achieve abstraction. Encapsulation: Binding code and data together into a single unit is known as encapsulation. For example: capsule.A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. Q:What is finally and finalize in java? A:finally block is used with try-catch to put the code that you want to get executed always, even if any exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block. finalize() is a special method in Object class that we can override in our classes. This method get’s called by garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when object is garbage collected. Q:What kind of variables a class can consist of? A:A class consist of Local variable, instance variables and class variables. Variables defined inside methods, constructors or blocks are called local variables. Instance variables are variables within a class but outside any method. These are variables declared with in a class, outside any method, with the static keyword. Q:Do I need to import java.lang package any time? Why ? A:No. It is by default loaded internally by the JVM. Q:Can I import same package/class twice? Will the JVM load the package twice at runtime? A:One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class. Q:What is overloading and overriding in java? A:When we have more than one method with same name in a single class but the arguments are different, then it is called as method overloading. Overriding concept comes in picture with inheritance when we have two methods with same signature, one in parent class and another in child class. We can use @Override annotation in the child class overridden method to make sure if parent class method is changed, so as child class. Overriding Example: class CarClass { public int speedLimit() { return 100; } } class Ford extends CarClass { public int speedLimit() { return 150; } public static void main(String args[]) { CarClass obj = new Ford(); int num= obj.speedLimit(); System.out.println("Speed Limit is: "+num); } } Output: Speed Limit is: 150 Overloading Example: class Sum { int add(int n1, int n2) { return n1+n2; } int add(int n1, int n2, int n3) { return n1+n2+n3; } public static void main(String args[]) { Sum obj = new Sum(); System.out.println("Sum of two numbers: "+obj.add(20, 21)); System.out.println("Sum of three numbers: "+obj.add(20, 21, 22)); } } Output: Sum of two numbers: 41 Sum of three numbers: 63 Q:What is the difference between abstract class and interface? A:1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can have static methods, main method and constructor. Interface can't have static methods, main method or constructor. 5) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. Abstract Class Example: public abstract class Shape{ public abstract void draw(); } Interface Example: public interface Shape{ void draw(); } Q:What are different types of inner classes? A:Nested top-level classes, Member classes, Local classes, Anonymous classes. Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety. Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class. Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable. Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor. Q:What is static import? A:If we import a class with static then we can directly use all the static variable and method from that imported class without class name. Q:Can an abstract class have a static method? A:Yes an abstract class have a static method and it can be accessed by any other class(even not a concrete class). Q:Can there be an abstract class with no abstract methods in it? A:Yes, there can be an abstract class without abstract methods. Q:Can an abstract class have a constructor? A:Yes, an abstract class can have a constructor. Consider this: abstract class Product { int multiplyBy; public Product( int multiplyBy ) { this.multiplyBy = multiplyBy; } public int mutiply(int val) { return multiplyBy * val; } } class TimesTwo extends Product { public TimesTwo() { super(2); } } class TimesWhat extends Product { public TimesWhat(int what) { super(what); } } The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value. Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class. Q:Why static methods cannot access non static variables or methods? A:A static method cannot access non static variables or methods because static methods doesn't need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will not be initialized since the object is not created and this could result in an error. Q:What is Marker interface? A:A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well known marker interfaces are Serializable and Cloneable. Q:Difference between String, StringBuffer and StringBuilder? A:String is immutable and final in java, so whenever we do String manipulation, it creates a new String. StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder. StringBuilder performance is fast than StringBuffer because of no overhead of synchronization. Q:Can an anonymous class be declared as implementing an interface and extending a class? A:An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. Q:Can this keyword be assigned null value? A:No Q:Can we use String with switch case? A:Yes in Java 7 we can have switch case statements with string. Q:How does Java allocate stack and heap memory? A:Each time an object is created in Java it goes into the part of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack. When a method is invoked and stack pointer is decremented when a method call is completed. In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code. Q:Can we use String with switch case? A:One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements. Q:What are the steps involved in Java Application Execution ? A:1. Creating java source file 2. Compiling Java Source Files into *.class file which is actually Byte Code. Use of javac command. 3. Loading class file into Java Run Time (JRE) using class loader 4. Use Bytecode verifier to check for byte code specification 5. Use Just In time Code Generator or Interpreter for byte code execution. Q:What is JIT compiler? A:A JIT compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently. This is in contrast to a traditional compiler that compiles all the code to machine language before the program is first run. To paraphrase, conventional compilers build the whole program as an EXE file BEFORE the first time you run it. For newer style programs, an assembly is generated with pseudocode (p-code). Only AFTER you execute the program on the OS (e.g., by double-clicking on its icon) will the (JIT) compiler kick in and generate machine code (m-code) that the Intel-based processor or whatever will understand. It is used to improve the performance. It compiles JAVA byte code to native machine code and execute it directly on the underlying hardware and hence reduces the amount of time needed for compilation. Q:What is classloader? A:The classloader is a system that is used to load classes and interfaces which are required to run the application. There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader etc. Q:What is byte code verifier? A:Byte code verifier checks for illegal code like pointers, violated access rights on objects etc. in complied byte code. 1. Check whether classes follow JVM specification for classes 2. Check for stack overflows 3. Check for access restriction violations 4. Illegal data conversions Q:What is the default value of the local variables? A:Local variables are not initialized to any default value, neither primitives nor object references. Q:What will be the initial value of an object? A:All object references are initialized to null in Java. Q:Is constructor inherited? A:No, constructor is not inherited. Q:Can you make a constructor final? A:No, constructor can't be final. Q:Can you override private or static method in Java ? A:You can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding. Q:What is the difference between creating String as new() and literal? A:When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap. String s = new String("Test"); It does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. Its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool. Q:How are this() and super() used with constructors? A:Constructors use this to refer to another constructor in the same class with a different parameter list. Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain. Q:How to define a constant variable in Java? A:Variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed. static final int MAX_LENGTH = 50; is an example for constant. Q: How one can change the heap size of a JVM? A: We can use the below command: java -Xms -Xmx program For example: java -Xms64m -Xmx128m program Q:What is blank final variable? A:final variable, not initialized at the time of declaration, is known as blank final variable.It can only be initialized in construtor. Q:What is immutable object? A:Immutable classes are Java classes whose objects can not be modified once created.Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.