SlideShare a Scribd company logo
What is JVM? 
A Java Virtual Machine is a runtime environment required for execution of a Java application.Every Java 
application runs inside a runtime instance of some concrete implementation of abstract specifications of 
JVM.It is JVM which is crux of 'platform independent' nature of the language. 
What are the principle concepts of OOPS? 
There are four principle concepts upon which object oriented design and programming rest. They are: 
· Abstraction 
· Polymorphism 
· Inheritance 
· Encapsulation 
2.What is Abstraction? 
Abstraction refers to the act of representing essential features without including the background details or 
explanations. 
3.What is Encapsulation? 
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside 
access only as appropriate. It prevents other objects from directly altering or accessing the properties or 
methods of the encapsulated object. 
4.What is the difference between abstraction and encapsulation? 
· Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information 
hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented. 
· Abstraction solves the problem in the design side while Encapsulation is the Implementation. 
· Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your 
abstraction to suit the developer needs. 
5.What is Inheritance? 
· Inheritance is the process by which objects of one class acquire the properties of objects of another 
class. 
· A class that is inherited is called a superclass. 
· The class that does the inheriting is called a subclass. 
· Inheritance is done by using the keyword extends. 
· The two most common reasons to use inheritance are: 
o To promote code reuse 
o To use polymorphism 
6.What is Polymorphism? 
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a 
characteristic of being able to assign a different meaning or usage to something in different contexts - 
specifically, to allow an entity such as a variable, a function, or an object to have more than one form. 
7.How does Java implement polymorphism? 
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). 
Polymorphism manifests itself in Java in the form of multiple methods having the same name. 
· In some cases, multiple methods have the same name, but different formal argument lists 
(overloaded methods). 
· In other cases, multiple methods have the same name, same return type, and same formal argument 
list (overridden methods).
8.Explain the different forms of Polymorphism. 
There are two types of polymorphism one is Compile time polymorphism and the other is run time 
polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done 
using inheritance and interface. 
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in 
Java: 
· Method overloading 
· Method overriding through inheritance 
· Method overriding through the Java interface 
9.What is runtime polymorphism or dynamic 
method dispatch? 
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden 
method is resolved at runtime rather than at compile-time. In this process, an overridden method is called 
through the reference variable of a superclass. The determination of the method to be called is based on the 
object being referred to by the reference variable. 
10.What is Dynamic Binding? 
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic 
binding (also known as late binding) means that the code associated with a given procedure call is not 
known until the time of the call at run-time. It is associated with polymorphism and inheritance. 
11.What is method overloading? 
Method Overloading means to have two or more methods with same name in the same class with different 
arguments. The benefit of method overloading is that it allows you to implement methods that support the 
same semantic operation but differ by argument number or type. 
Note: 
· Overloaded methods MUST change the argument list 
· Overloaded methods CAN change the return type 
· Overloaded methods CAN change the access modifier 
· Overloaded methods CAN declare new or broader checked exceptions 
· A method can be overloaded in the same class or in a subclass 
12.What is method overriding? 
Method overriding occurs when sub class declares a method that has the same type arguments as a method 
declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s 
specific to a particular subclass type. 
Note: 
· The overriding method cannot have a more restrictive access modifier than the method being 
overridden (Ex: You can’t override a method marked public and make it protected). 
· You cannot override a method marked final 
· You cannot override a method marked static 
13.What are the differences between method overloading and method overriding? 
Overloaded Method Overridden Method 
Arguments Must change Must not change 
Return type Can change Can’t change except for covariant returns
Exceptions Can change Can reduce or eliminate. Must not throw 
new or broader checked exceptions 
Access Can change Must not make more restrictive (can be less 
restrictive) 
Invocation Reference type determines which 
overloaded version is selected. Happens at 
compile time. 
Object type determines which method is 
selected. Happens at runtime. 
14.Can overloaded methods be override too? 
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler 
will not binding the method calls since it is overloaded, because it might be overridden now or in the future. 
15.Is it possible to override the main method? 
NO, because main is a static method. A static method can't be overridden in Java. 
16.How to invoke a superclass version of an Overridden method? 
To invoke a superclass method that has been overridden in a subclass, you must either call the method 
directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the 
view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the 
method. 
// From subclass 
super.overriddenMethod(); 
17.What is super? 
super is a keyword which is used to access the method or member variables from the superclass. If a method 
hides one of the member variables in its superclass, the method can refer to the hidden variable through the 
use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the 
method can invoke the overridden method through the use of the super keyword. 
Note: 
· You can only go back one level. 
· In the constructor, if you use super(), it must be the very first code, and you cannot access any 
this.xxx variables or methods to compute its parameters. 
18.How do you prevent a method from being overridden? 
To prevent a specific method from being overridden in a subclass, use the final modifier on the method 
declaration, which means "this is the final implementation of this method", the end of its inheritance 
hierarchy. 
public final void exampleMethod() { 
// Method statements 
} 
19.What is an Interface? 
An interface is a description of a set of methods that conforming implementing classes must have. 
Note: 
· You can’t mark an interface as final. 
· Interface variables must be static. 
· An Interface cannot extend anything but another interfaces.
20.Can we instantiate an interface? 
You can’t instantiate an interface directly, but you can instantiate a class that implements an interface. 
21.Can we create an object for an interface? 
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be 
instantiated in their own right, so you must write a class that implements the interface and fulfill all the 
methods defined in it. 
22.Do interfaces have member variables? 
Interfaces may have member variables, but these are implicitly public, static, and final- in other words, 
interfaces can declare only constants, not instance variables that are available to all implementations and 
may be used as key references for method arguments for example. 
23.What modifiers are allowed for methods in an Interface? 
Only public and abstract modifiers are allowed for methods in interfaces. 
24.What is a marker interface? 
Marker interfaces are those which do not declare any required methods, but signify their compatibility with 
certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do 
not contain any methods, but classes must implement this interface in order to be serialized and de-serialized. 
25.What is an abstract class? 
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that 
is declared, but contains no implementation. 
Note: 
· If even a single method is abstract, the whole class must be declared abstract. 
· Abstract classes may not be instantiated, and require subclasses to provide implementations for the 
abstract methods. 
· You can’t mark a class as both abstract and final. 
26.Can we instantiate an abstract class? 
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed). 
27.What are the differences between Interface and Abstract class? 
Abstract Class Interfaces 
An abstract class can provide complete, default code 
and/or just the details that have to be overridden. 
An interface cannot provide any code at all,just the 
signature. 
In case of abstract class, a class may extend only one 
abstract class. A Class may implement several interfaces. 
An abstract class can have non-abstract methods. All methods of an Interface are abstract. 
An abstract class can have instance variables. An Interface cannot have instance variables. 
An abstract class can have any visibility: public, 
private, protected. An Interface visibility must be public (or) none. 
If we add a new method to an abstract class then we 
have the option of providing default implementation 
If we add a new method to an Interface then we have 
to track down all the implementations of the interface
and therefore all the existing code might work 
properly. and define implementation for the new method. 
An abstract class can contain constructors . An Interface cannot contain constructors . 
Abstract classes are fast. Interfaces are slow as it requires extra indirection to 
find corresponding method in the actual class. 
28.When should I use abstract classes and when should I use interfaces? 
Use Interfaces when… 
· You see that something in your design will change frequently. 
· If various implementations only share method signatures then it is better to use Interfaces. 
· you need some classes to use some methods which you don't want to be included in the class, then 
you go for the interface, which makes it easy to just implement and make use of the methods defined in the 
interface. 
Use Abstract Class when… 
· If various implementations are of the same kind and use common behavior or status then abstract 
class is better to use. 
· When you want to provide a generalized form of abstraction and leave the implementation task with 
the inheriting subclass. 
· Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good 
choice for nonleaf classes in class hierarchies. 
29.When you declare a method as abstract, can other nonabstract methods access it? 
Yes, other nonabstract methods can access a method that you declare as abstract. 
30.Can there be an abstract class with no abstract methods in it? 
Yes, there can be an abstract class without abstract methods. 
What is an exception? 
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of 
the program's instructions. 
2.What is error? 
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass 
of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by 
the JVM itself. 
3.Which is superclass of Exception? 
"Throwable", the parent class of all exception related classes. 
4.What are the advantages of using exception handling? 
Exception handling provides the following advantages over "traditional" error management techniques: 
· Separating Error Handling Code from "Regular" Code. 
· Propagating Errors Up the Call Stack. 
· Grouping Error Types and Error Differentiation. 
5.What are the types of Exceptions in Java 
There are two types of exceptions in Java, unchecked exceptions and checked exceptions. 
· Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), 
excluding class RuntimeException and its subclasses. Each method must either handle all checked 
exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception. 
· Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked 
exceptions. Class Error and its subclasses also are unchecked.
6.Why Errors are Not Checked? 
A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from 
compile-time checking because they can occur at many points in the program and recovery from them is 
difficult or impossible. A program declaring such exceptions would be pointlessly. 
7.Why Runtime Exceptions are Not Checked? 
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time 
checking because, in the judgment of the designers of the Java programming language, having to declare 
such exceptions would not aid significantly in establishing the correctness of programs. Many of the 
operations and constructs of the Java programming language can result in runtime exceptions. The 
information available to a compiler, and the level of analysis the compiler performs, are usually not 
sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the 
programmer. Requiring such exception classes to be declared would simply be an irritation to programmers. 
8.Explain the significance of try-catch blocks? 
Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we 
use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. 
One or more catch clauses match a specific exception to a block of code that handles it. 
What is the use of finally block? 
The finally block encloses code that is always executed at some point after the try block, whether an 
exception was thrown or not. This is right place to close files, release your network sockets, connections, 
and perform any other cleanup your code requires. 
Note: If the try block executes with no exceptions, the finally block is executed immediately after the try 
block completes. It there was an exception thrown, the finally block executes immediately after the proper 
catch block completes 
What if there is a break or return statement in try block followed by finally block? 
If there is a return statement in the try block, the finally block executes right after the return statement 
encountered, and before the return executes. 
Can we have the try block without catch block? 
Yes, we can have the try block without catch block, but finally block should follow the try block. 
Note: It is not valid to use a try clause without either a catch clause or a finally clause. 
12.What is the difference throw and throws? 
throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, 
so that callers of the method can guard themselves against that exception. If a method is declared as
throwing a particular class of exceptions, then any other method that calls it must either have a try-catch 
clause to handle that exception or must be declared to throw that exception (or its superclass) itself. 
A method that does not handle an exception it throws has to announce this: 
public void myfunc(int arg) throws MyException { 
… 
} 
throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can 
catch that type of exception. The flow of execution stops immediately after the throw statement; any 
subsequent statements are not executed. 
To throw an user-defined exception within a block, we use the throw command: 
throw new MyException("I always wanted to throw an exception!); 
What is Constructor? 
· A constructor is a special method whose task is to initialize the object of its class. 
· It is special because its name is the same as the class name. 
· They do not have return types, not even void and therefore they cannot return values. 
· They cannot be inherited, though a derived class can call the base class constructor. 
· Constructor is invoked whenever an object of its associated class is created. 
32.How does the Java default constructor be provided? 
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter- 
constructor (default-constructor) for the class in the byte code. The access modifier 
(public/private/etc.) of the default constructor is the same as the class itself. 
33.Can constructor be inherited? 
No, constructor cannot be inherited, though a derived class can call the base class constructor. 
34.What are the differences between Contructors and Methods? 
Constructors Methods 
Purpose Create an instance of a class Group Java statements 
Modifiers Cannot be abstract, final, native, static, or 
synchronized 
Can be abstract, final, native, static, or 
synchronized 
Return Type No return type, not even void void or a valid return type 
Name Same name as the class (first letter is 
capitalized by convention) -- usually a 
noun 
Any name except the class. Method names 
begin with a lowercase letter by convention 
-- usually the name of an action 
this Refers to another constructor in the same 
class. If used, it must be the first line of the 
constructor 
Refers to an instance of the owning class. 
Cannot be used by static methods. 
super Calls the constructor of the parent class. If 
used, must be the first line of the 
constructor 
Calls an overridden method in the parent 
class
Inheritance Constructors are not inherited Methods are inherited 
35.How are this() and super() used with constructors? 
· 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. 
36.What are the differences between Class Methods and Instance Methods? 
Class Methods Instance Methods 
Class methods are methods which are declared as 
static. The method can be called without creating an 
instance of the class 
Instance methods on the other hand require an 
instance of the class to exist before they can be called, 
so an instance of a class needs to be created by using 
the new keyword. 
Instance methods operate on specific instances of 
classes. 
Class methods can only operate on class members and 
not on instance members as class methods are 
unaware of instance members. 
Instance methods of the class can also not be called 
from within a class method unless they are being 
called on an instance of that class. 
Class methods are methods which are declared as 
static. The method can be called without creating an 
instance of the class. 
Instance methods are not declared as static. 
37.How are this() and super() used with constructors? 
· 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. 
38.What are Access Specifiers? 
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a 
class and making this class available only through methods. Java allows you to control access to classes, 
methods, and fields via so-called access specifiers.. 
39.What are Access Specifiers available in Java? 
Java offers four access specifiers, listed below in decreasing accessibility: 
· Public- public classes, methods, and fields can be accessed from everywhere. 
· Protected- protected methods and fields can only be accessed within the same class to which the 
methods and fields belong, within its subclasses, and within classes of the same package. 
· Default(no specifier)- If you do not set access to specific level, then such a class, method, or field 
will be accessible from inside the same package to which the class, method, or field belongs, but not from 
outside this package. 
· Private- private methods and fields can only be accessed within the same class to which the 
methods and fields belong. private methods and fields are not visible within subclasses and are not inherited 
by subclasses. 
Situation public protected default private 
Accessible to class yes yes yes no
from same package? 
Accessible to class 
from different package? yes no, unless it is a subclass no no 
40.What is final modifier? 
The final modifier keyword makes that the programmer cannot change the value anymore. The actual 
meaning depends on whether it is applied to a class, a variable, or a method. 
· final Classes- A final class cannot have subclasses. 
· final Variables- A final variable cannot be changed once it is initialized. 
· final Methods- A final method cannot be overridden by subclasses. 
41.What are the uses of final method? 
There are two reasons for marking a method as final: 
· Disallowing subclasses to change the meaning of the method. 
· Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code. 
42.What is static block? 
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to 
the main method the static block will execute. 
43.What are static variables? 
Variables that have only one copy per class are known as static variables. They are not attached to a 
particular instance of a class but rather belong to a class as a whole. They are declared by using the static 
keyword as a modifier. 
static type varIdentifier; 
where, the name of the variable is varIdentifier and its data type is specified by type. 
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default 
value. The default value depends on the data type of the variables. 
44.What is the difference between static and non-static variables? 
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static 
variables take on unique values with each object instance. 
45.What are static methods? 
Methods declared with the keyword static as modifier are called static methods or class methods. They are 
so called because they affect a class as a whole, not a particular instance of the class. Static methods are 
always invoked without reference to a particular instance of a class. 
Note:The use of a static method suffers from the following restrictions: 
· A static method can only call other static methods. 
· A static method must only access static data. 
· A static method cannot reference to the current object using keywords super or this. 
What if the main method is declared as private? 
<br /><font size=-1> 
The program compiles properly but at runtime it will give “Main method not public.” message. 
What is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the value. Pass by value means 
passing a copy of the value. 
If you’re overriding the method equals() of an object, which other method you might also consider? 
hashCode() 
What is Byte Code? 
Or 
What gives java it’s “write once and run anywhere” nature? 
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any 
platform and hence java is said to be platform independent. 
Expain the reason for each keyword of public static void main(String args[])? 
public- main(..) is the first method called by java environment when a program is executed so it has to 
accessible from java environment. Hence the access specifier has to be public. 
static: Java environment should be able to call this method without creating an instance of the class , so this 
method must be declared as static. 
void: main does not return anything so the return type must be void 
The argument String indicates the argument type which is given at the command line and arg is an array for 
string given during command line. 
What are the differences between == and .equals() ? 
Or 
what is difference between == and equals 
Or 
Difference between == and equals method 
Or 
What would you use to compare two String variables - the operator == or the method equals()? 
Or 
How is it possible for two String objects with identical values not to be equal under the == operator? 
The == operator compares two objects to determine if they are the same object in memory i.e. present in the 
same memory location. It is possible for two String objects to have the same value, but located in different 
areas of memory. 
== compares references while .equals compares contents. The method public boolean equals(Object obj) is 
provided by the Object class and can be overridden. The default implementation returns true only if the 
object is compared with itself, which is equivalent to the equality operator == being used to compare aliases 
to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value 
equality means that they contain the same character sequence. For the Wrapper classes, value equality 
means that the primitive values are equal. 
public class EqualsTest { 
public static void main(String[] args) { 
String s1 = “abc”; 
String s2 = s1; 
String s5 = “abc”; 
String s3 = new String(”abc”); 
String s4 = new String(”abc”); 
System.out.println(”== comparison : ” + (s1 == s5)); 
System.out.println(”== comparison : ” + (s1 == s2)); 
System.out.println(”Using equals method : ” + s1.equals(s2));
System.out.println(”== comparison : ” + s3 == s4); 
System.out.println(”Using equals method : ” + s3.equals(s4)); 
} 
} 
Output 
== comparison : true 
== comparison : true 
Using equals method : true 
false 
Using equals method : true 
What if the static modifier is removed from the signature of the main method? 
Or 
What if I do not provide the String array as the argument to the method? 
Program compiles. But at runtime throws an error “NoSuchMethodError”. 
What is the difference between final, finally and finalize? What do you understand by the java final 
keyword? 
Or 
What is final, finalize() and finally? 
Or 
What is finalize() method? 
Or 
What is the difference between final, finally and finalize? 
Or 
What does it mean that a class or member is final? 
o final - declare constant 
o finally - handles exception 
o finalize - helps in garbage collection 
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not 
be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the 
compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method 
can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). 
finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in 
exception handling and will be executed whether or not an exception is thrown. For example, closing of 
open connections is done in the finally method. 
What is the Java API? 
The Java API is a large collection of ready-made software components that provide many useful 
capabilities, such as graphical user interface (GUI) widgets. 
Why there are no global variables in Java? 
Global variables are globally accessible. Java does not support globally accessible variables due to 
following reasons: 
· The global variables breaks the referential transparency 
· Global variables creates collisions in namespace. 
How to convert String to Number in java program? 
The valueOf() function of Integer class is is used to convert string to Number. Here is the code example: 
String numString = “1000″; 
int id=Integer.valueOf(numString).intValue();
What is the SimpleTimeZone class? 
The SimpleTimeZone class provides support for a Gregorian calendar. 
What is the difference between a while statement and a do statement? 
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should 
occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop 
should occur. The do statement will always execute the loop body at least once. 
What is the Locale class? 
The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or 
cultural region. 
Describe the principles of OOPS. 
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation. 
Explain the Inheritance principle. 
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows 
well-tested procedures to be reused and enables changes to make once and have effect in all relevant places 
What is implicit casting? 
Implicit casting is the process of simply assigning one entity to another without any transformation guidance 
to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all 
scenarios. 
Example 
int i = 1000; 
long j = i; //Implicit casting 
Is sizeof a keyword in java? 
The sizeof operator is not a keyword. 
What is a native method? 
A native method is a method that is implemented in a language other than Java. 
In System.out.println(), what is System, out and println? 
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in 
the out object. 
What are Encapsulation, Inheritance and Polymorphism 
Or 
Explain the Polymorphism principle. Explain the different forms of Polymorphism. 
Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used 
as a general category for different types of actions. The specific action is determined by the exact nature of 
the situation. 
Polymorphism exists in three distinct forms in Java: 
• Method overloading 
• Method overriding through inheritance 
• Method overriding through the Java interface 
What is explicit casting? 
Explicit casting in the process in which the complier are specifically informed to about transforming the 
object.
Example 
long i = 700.20; 
int j = (int) i; //Explicit casting 
What is the Java Virtual Machine (JVM)? 
The Java Virtual Machine is software that can be ported onto various hardware-based platforms 
What do you understand by downcasting? 
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down 
the hierarchy 
What are Java Access Specifiers? 
Or 
What is the difference between public, private, protected and default Access Specifiers? 
Or 
What are different types of access modifiers? 
Access specifiers are keywords that determine the type of access to the member of a class. These keywords 
are for allowing 
privileges to parts of a program such as functions and variables. These are: 
• Public : accessible to all classes 
• Protected : accessible to the classes within the same package and any subclasses. 
• Private : accessible only to the class to which they belong 
• Default : accessible to the class to which they belong and to subclasses within the same package 
Which class is the superclass of every class? 
Object. 
Name primitive Java types. 
The 8 primitive types are byte, char, short, int, long, float, double, and boolean. 
What is the difference between static and non-static variables? 
Or 
What are class variables? 
Or 
What is static in java? 
Or 
What is a static method? 
A static variable is associated with the class as a whole rather than with specific instances of a class. Each 
object will share a common copy of the static variables i.e. there is only one copy per class, no matter how 
many objects are created from it. Class variables or static variables are declared with the static keyword in a 
class. These are declared outside a class and stored in static memory. Class variables are mostly used for 
constants. Static variables are always called by the class name. This variable is created when the program 
starts and gets destroyed when the programs stops. The scope of the class variable is same an instance 
variable. Its initial value is same as instance variable and gets a default value when its not initialized 
corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than 
any object of the class and doesn’t apply to an object or even require that any objects of the class have been 
instantiated. 
Static methods are implicitly final, because overriding is done based on the type of the object, and static 
methods are attached to a class, not an object. A static method in a superclass can be shadowed by another 
static method in a subclass, as long as the original method was not declared final. However, you can’t 
override a static method with a non-static method. In other words, you can’t change a static method into an 
instance method in a subclass. 
Non-static variables take on unique values with each object instance.
What is the difference between the boolean & operator and the && operator? 
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the 
&& operator is a short cut operator. When an expression involving the && operator is evaluated, the first 
operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the 
first operand evaluates to false, the evaluation of the second operand is skipped. 
How does Java handle integer overflows and underflows? 
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. 
What if I write static public void instead of public static void? 
Program compiles and runs properly. 
What is the difference between declaring a variable and defining a variable? 
In declaration we only mention the type of the variable and its name without initializing it. Defining means 
declaration + initialization. E.g. String s; is just a declaration while String s = new String (”bob”); Or String 
s = “bob”; are both definitions. 
What type of parameter passing does Java support? 
In Java the arguments (primitives and objects) are always passed by value. With objects, the object 
reference itself is passed by value and so both the original reference and parameter copy both refer to the 
same object. 
Explain the Encapsulation principle. 
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a 
single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be 
encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a 
protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside 
the wrapper. 
What do you understand by a variable? 
Variable is a named memory location that can be easily referred in the program. The variable is used to hold 
the data and it can be changed during the course of the execution of the program. 
What do you understand by numeric promotion? 
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral 
and floating-point operations may take place. In the numerical promotion process the byte, char, and short 
values are converted to int values. The int values are also converted to long values, if necessary. The long 
and float values are converted to double values, as required. 
What do you understand by casting in java language? What are the types of casting? 
The process of converting one data type to another is called Casting. There are two types of casting in Java; 
these are implicit casting and explicit casting. 
What is the first argument of the String array in main method? 
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by 
default is the program name. If we do not provide any arguments on the command line, then the String array 
of main method will be empty but not null. 
How can one prove that the array is not null but empty? 
Print array.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 array.length.
Can an application have multiple classes having main method? 
Yes. 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 amongst the multiple 
classes having main method. 
When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded 
in Java? 
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has 
to be created. Static variables will be allocated memory space when they have been loaded. The code in a 
static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number 
of static blocks. Static block is not member of a class, they do not have a return statement and they cannot 
be called directly. Cannot contain this or super. They are primarily used to initialize static fields. 
Can I have multiple main methods in the same class? 
We can have multiple overloaded main methods but there can be only one main method with the 
following signature : 
public static void main(String[] args) {} 
No the program fails to compile. The compiler says that the main method is already defined in the class. 
Explain working of Java Virtual Machine (JVM)? 
JVM is an abstract computing machine like any other real computing machine which first converts .java file 
into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes. 
How can I swap two variables without using a third variable? 
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. 
and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and 
Assign to First Variable. Example: 
int a=5,b=10;a=a+b; b=a-b; a=a-b; 
An other approach to the same question 
You use an XOR swap. 
for example: 
int a = 5; int b = 10; 
a = a ^ b; 
b = a ^ b; 
a = a ^ b; 
What is data encapsulation? 
Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN) which are used to 
access the fields of the object. Typically the fields are made private while the get and set methods are 
public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is 
stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for 
instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is 
nothing but wrapping up the data and associated methods into a single unit in such a way that data can be 
accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data 
hiding. 
What is reflection API? How are they implemented? 
Reflection is the process of introspecting the features and state of a class at runtime and dynamically 
manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method,
Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the 
getName method. 
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or 
the heap maintained by the JVM? Why 
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects 
are on the STACK. 
What is phantom memory? 
Phantom memory is false memory. Memory that does not exist in reality. 
Can a method be static and synchronized? 
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang. 
Class instance associated with the object. It is similar to saying: 
synchronized(XYZ.class) { 
} 
What is difference between String and StringTokenizer? 
A StringTokenizer is utility class used to break up string. 
Example: 
StringTokenizer st = new StringTokenizer(”Hello World”); 
while (st.hasMoreTokens()) { 
System.out.println(st.nextToken()); 
} 
Output: 
Hello 
World 
What is the difference between interpreted code and compiled code? 
An interpreter produces a result from a program, while a compiler produces a program written in assembly 
language and in case of Java from bytecodes.The scripting languages like JavaScript,Python etc. require 
Interpreter to execute them.So a program written in scripting language will directly be executed with 
interpreter installed on that computer,if it is absent then this program will not execute.While in case of 
compiled code,an assembler or a virtual machine in case of Java is required to convert assembly level code 
or bytecodes into machine level instructions/commands.Generally, interpreted programs are slower than 
compiled programs, but are easier to debug and revise. 
What is the difference between JVM and JRE? 
A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any computer.A JRE 
contains a Java Virtual Machine(JVM),all standard,core java classes and runtime libraries. It does not 
contain any development tools such as compiler, debugger, etc. JDK(Java Development Kit) is a whole 
package required to Java Development which essentially contains JRE+JVM,and tools required to compile 
and debug,execute Java applications.

More Related Content

What's hot

Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
Aravind NC
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
G C Reddy Technologies
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
Gradeup
 
Java Core
Java CoreJava Core
Java Core
Gaurav Mehta
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
M. Raihan
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
talha ijaz
 
inheritance
inheritanceinheritance
inheritance
Mohit Patodia
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
Ahmed Nobi
 
Hp syllabus
Hp syllabusHp syllabus
Hp syllabus
Nitish Nagar
 
Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
karthikenlume
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
talha ijaz
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
JavaTportal
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 

What's hot (20)

Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
 
Pocket java
Pocket javaPocket java
Pocket java
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
9 abstract interface
9 abstract interface9 abstract interface
9 abstract interface
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Java Core
Java CoreJava Core
Java Core
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Chap11
Chap11Chap11
Chap11
 
javainterface
javainterfacejavainterface
javainterface
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 
inheritance
inheritanceinheritance
inheritance
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
Hp syllabus
Hp syllabusHp syllabus
Hp syllabus
 
Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
 

Viewers also liked

Jira work flows
Jira work flowsJira work flows
Jira work flows
Shivaraj R
 
Cucumber questions
Cucumber questionsCucumber questions
Cucumber questions
Shivaraj R
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
rithustutorials
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
girichinna27
 
Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questionsPyadav010186
 
Niyati_Manual_Testing_ISTQB_Certified_Resume
Niyati_Manual_Testing_ISTQB_Certified_ResumeNiyati_Manual_Testing_ISTQB_Certified_Resume
Niyati_Manual_Testing_ISTQB_Certified_ResumeNiyati Madad
 
Manual Testing
Manual TestingManual Testing
Manual Testing
G.C Reddy
 
Nike interview questions and answers
Nike interview questions and answersNike interview questions and answers
Nike interview questions and answersselinasimpson304
 
Manual testing interview question by INFOTECH
Manual testing interview question by INFOTECHManual testing interview question by INFOTECH
Manual testing interview question by INFOTECH
Pravinsinh
 

Viewers also liked (9)

Jira work flows
Jira work flowsJira work flows
Jira work flows
 
Cucumber questions
Cucumber questionsCucumber questions
Cucumber questions
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
 
Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questions
 
Niyati_Manual_Testing_ISTQB_Certified_Resume
Niyati_Manual_Testing_ISTQB_Certified_ResumeNiyati_Manual_Testing_ISTQB_Certified_Resume
Niyati_Manual_Testing_ISTQB_Certified_Resume
 
Manual Testing
Manual TestingManual Testing
Manual Testing
 
Nike interview questions and answers
Nike interview questions and answersNike interview questions and answers
Nike interview questions and answers
 
Manual testing interview question by INFOTECH
Manual testing interview question by INFOTECHManual testing interview question by INFOTECH
Manual testing interview question by INFOTECH
 

Similar to Core java interview questions

Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
Arun Vasanth
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and Interfaces
Habtamu Wolde
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
Thakur Amit Tomer
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
Gaurav Mehta
 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar
 
software engineer interview questions.pdf
software engineer interview questions.pdfsoftware engineer interview questions.pdf
software engineer interview questions.pdf
RaajpootQueen
 
Java
JavaJava
Top 10 Interview Questions For Java
Top 10 Interview Questions For JavaTop 10 Interview Questions For Java
Top 10 Interview Questions For Java
EME Technologies
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
Kuntal Bhowmick
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Freshers
zynofustechnology
 
Java session2
Java session2Java session2
Java session2
Rajeev Kumar
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
nishajj
 
C# interview
C# interviewC# interview
C# interview
Thomson Reuters
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
Shashwat Shriparv
 

Similar to Core java interview questions (20)

Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and Interfaces
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
software engineer interview questions.pdf
software engineer interview questions.pdfsoftware engineer interview questions.pdf
software engineer interview questions.pdf
 
C# question answers
C# question answersC# question answers
C# question answers
 
Java
JavaJava
Java
 
Top 10 Interview Questions For Java
Top 10 Interview Questions For JavaTop 10 Interview Questions For Java
Top 10 Interview Questions For Java
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Freshers
 
Java session2
Java session2Java session2
Java session2
 
Intervies
InterviesIntervies
Intervies
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
 
C# interview
C# interviewC# interview
C# interview
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
Core java questions
Core java questionsCore java questions
Core java questions
 
Core java questions
Core java questionsCore java questions
Core java questions
 

Recently uploaded

Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 

Recently uploaded (20)

Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 

Core java interview questions

  • 1. What is JVM? A Java Virtual Machine is a runtime environment required for execution of a Java application.Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM.It is JVM which is crux of 'platform independent' nature of the language. What are the principle concepts of OOPS? There are four principle concepts upon which object oriented design and programming rest. They are: · Abstraction · Polymorphism · Inheritance · Encapsulation 2.What is Abstraction? Abstraction refers to the act of representing essential features without including the background details or explanations. 3.What is Encapsulation? Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. 4.What is the difference between abstraction and encapsulation? · Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented. · Abstraction solves the problem in the design side while Encapsulation is the Implementation. · Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs. 5.What is Inheritance? · Inheritance is the process by which objects of one class acquire the properties of objects of another class. · A class that is inherited is called a superclass. · The class that does the inheriting is called a subclass. · Inheritance is done by using the keyword extends. · The two most common reasons to use inheritance are: o To promote code reuse o To use polymorphism 6.What is Polymorphism? Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. 7.How does Java implement polymorphism? (Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name. · In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). · In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
  • 2. 8.Explain the different forms of Polymorphism. There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface. Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java: · Method overloading · Method overriding through inheritance · Method overriding through the Java interface 9.What is runtime polymorphism or dynamic method dispatch? In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. 10.What is Dynamic Binding? Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance. 11.What is method overloading? Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type. Note: · Overloaded methods MUST change the argument list · Overloaded methods CAN change the return type · Overloaded methods CAN change the access modifier · Overloaded methods CAN declare new or broader checked exceptions · A method can be overloaded in the same class or in a subclass 12.What is method overriding? Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. Note: · The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected). · You cannot override a method marked final · You cannot override a method marked static 13.What are the differences between method overloading and method overriding? Overloaded Method Overridden Method Arguments Must change Must not change Return type Can change Can’t change except for covariant returns
  • 3. Exceptions Can change Can reduce or eliminate. Must not throw new or broader checked exceptions Access Can change Must not make more restrictive (can be less restrictive) Invocation Reference type determines which overloaded version is selected. Happens at compile time. Object type determines which method is selected. Happens at runtime. 14.Can overloaded methods be override too? Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future. 15.Is it possible to override the main method? NO, because main is a static method. A static method can't be overridden in Java. 16.How to invoke a superclass version of an Overridden method? To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method. // From subclass super.overriddenMethod(); 17.What is super? super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. Note: · You can only go back one level. · In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters. 18.How do you prevent a method from being overridden? To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy. public final void exampleMethod() { // Method statements } 19.What is an Interface? An interface is a description of a set of methods that conforming implementing classes must have. Note: · You can’t mark an interface as final. · Interface variables must be static. · An Interface cannot extend anything but another interfaces.
  • 4. 20.Can we instantiate an interface? You can’t instantiate an interface directly, but you can instantiate a class that implements an interface. 21.Can we create an object for an interface? Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it. 22.Do interfaces have member variables? Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example. 23.What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces. 24.What is a marker interface? Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized. 25.What is an abstract class? Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Note: · If even a single method is abstract, the whole class must be declared abstract. · Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. · You can’t mark a class as both abstract and final. 26.Can we instantiate an abstract class? An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed). 27.What are the differences between Interface and Abstract class? Abstract Class Interfaces An abstract class can provide complete, default code and/or just the details that have to be overridden. An interface cannot provide any code at all,just the signature. In case of abstract class, a class may extend only one abstract class. A Class may implement several interfaces. An abstract class can have non-abstract methods. All methods of an Interface are abstract. An abstract class can have instance variables. An Interface cannot have instance variables. An abstract class can have any visibility: public, private, protected. An Interface visibility must be public (or) none. If we add a new method to an abstract class then we have the option of providing default implementation If we add a new method to an Interface then we have to track down all the implementations of the interface
  • 5. and therefore all the existing code might work properly. and define implementation for the new method. An abstract class can contain constructors . An Interface cannot contain constructors . Abstract classes are fast. Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. 28.When should I use abstract classes and when should I use interfaces? Use Interfaces when… · You see that something in your design will change frequently. · If various implementations only share method signatures then it is better to use Interfaces. · you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface. Use Abstract Class when… · If various implementations are of the same kind and use common behavior or status then abstract class is better to use. · When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass. · Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies. 29.When you declare a method as abstract, can other nonabstract methods access it? Yes, other nonabstract methods can access a method that you declare as abstract. 30.Can there be an abstract class with no abstract methods in it? Yes, there can be an abstract class without abstract methods. What is an exception? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. 2.What is error? An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself. 3.Which is superclass of Exception? "Throwable", the parent class of all exception related classes. 4.What are the advantages of using exception handling? Exception handling provides the following advantages over "traditional" error management techniques: · Separating Error Handling Code from "Regular" Code. · Propagating Errors Up the Call Stack. · Grouping Error Types and Error Differentiation. 5.What are the types of Exceptions in Java There are two types of exceptions in Java, unchecked exceptions and checked exceptions. · Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception. · Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.
  • 6. 6.Why Errors are Not Checked? A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly. 7.Why Runtime Exceptions are Not Checked? The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers. 8.Explain the significance of try-catch blocks? Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. One or more catch clauses match a specific exception to a block of code that handles it. What is the use of finally block? The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires. Note: If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes What if there is a break or return statement in try block followed by finally block? If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes. Can we have the try block without catch block? Yes, we can have the try block without catch block, but finally block should follow the try block. Note: It is not valid to use a try clause without either a catch clause or a finally clause. 12.What is the difference throw and throws? throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as
  • 7. throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself. A method that does not handle an exception it throws has to announce this: public void myfunc(int arg) throws MyException { … } throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. To throw an user-defined exception within a block, we use the throw command: throw new MyException("I always wanted to throw an exception!); What is Constructor? · A constructor is a special method whose task is to initialize the object of its class. · It is special because its name is the same as the class name. · They do not have return types, not even void and therefore they cannot return values. · They cannot be inherited, though a derived class can call the base class constructor. · Constructor is invoked whenever an object of its associated class is created. 32.How does the Java default constructor be provided? If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter- constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself. 33.Can constructor be inherited? No, constructor cannot be inherited, though a derived class can call the base class constructor. 34.What are the differences between Contructors and Methods? Constructors Methods Purpose Create an instance of a class Group Java statements Modifiers Cannot be abstract, final, native, static, or synchronized Can be abstract, final, native, static, or synchronized Return Type No return type, not even void void or a valid return type Name Same name as the class (first letter is capitalized by convention) -- usually a noun Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action this Refers to another constructor in the same class. If used, it must be the first line of the constructor Refers to an instance of the owning class. Cannot be used by static methods. super Calls the constructor of the parent class. If used, must be the first line of the constructor Calls an overridden method in the parent class
  • 8. Inheritance Constructors are not inherited Methods are inherited 35.How are this() and super() used with constructors? · 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. 36.What are the differences between Class Methods and Instance Methods? Class Methods Instance Methods Class methods are methods which are declared as static. The method can be called without creating an instance of the class Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class. Class methods are methods which are declared as static. The method can be called without creating an instance of the class. Instance methods are not declared as static. 37.How are this() and super() used with constructors? · 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. 38.What are Access Specifiers? One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers.. 39.What are Access Specifiers available in Java? Java offers four access specifiers, listed below in decreasing accessibility: · Public- public classes, methods, and fields can be accessed from everywhere. · Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package. · Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. · Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. Situation public protected default private Accessible to class yes yes yes no
  • 9. from same package? Accessible to class from different package? yes no, unless it is a subclass no no 40.What is final modifier? The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method. · final Classes- A final class cannot have subclasses. · final Variables- A final variable cannot be changed once it is initialized. · final Methods- A final method cannot be overridden by subclasses. 41.What are the uses of final method? There are two reasons for marking a method as final: · Disallowing subclasses to change the meaning of the method. · Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code. 42.What is static block? Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute. 43.What are static variables? Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier. static type varIdentifier; where, the name of the variable is varIdentifier and its data type is specified by type. Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables. 44.What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. 45.What are static methods? Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class. Note:The use of a static method suffers from the following restrictions: · A static method can only call other static methods. · A static method must only access static data. · A static method cannot reference to the current object using keywords super or this. What if the main method is declared as private? <br /><font size=-1> The program compiles properly but at runtime it will give “Main method not public.” message. What is meant by pass by reference and pass by value in Java?
  • 10. Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value. If you’re overriding the method equals() of an object, which other method you might also consider? hashCode() What is Byte Code? Or What gives java it’s “write once and run anywhere” nature? All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent. Expain the reason for each keyword of public static void main(String args[])? public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public. static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static. void: main does not return anything so the return type must be void The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line. What are the differences between == and .equals() ? Or what is difference between == and equals Or Difference between == and equals method Or What would you use to compare two String variables - the operator == or the method equals()? Or How is it possible for two String objects with identical values not to be equal under the == operator? The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory. == compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal. public class EqualsTest { public static void main(String[] args) { String s1 = “abc”; String s2 = s1; String s5 = “abc”; String s3 = new String(”abc”); String s4 = new String(”abc”); System.out.println(”== comparison : ” + (s1 == s5)); System.out.println(”== comparison : ” + (s1 == s2)); System.out.println(”Using equals method : ” + s1.equals(s2));
  • 11. System.out.println(”== comparison : ” + s3 == s4); System.out.println(”Using equals method : ” + s3.equals(s4)); } } Output == comparison : true == comparison : true Using equals method : true false Using equals method : true What if the static modifier is removed from the signature of the main method? Or What if I do not provide the String array as the argument to the method? Program compiles. But at runtime throws an error “NoSuchMethodError”. What is the difference between final, finally and finalize? What do you understand by the java final keyword? Or What is final, finalize() and finally? Or What is finalize() method? Or What is the difference between final, finally and finalize? Or What does it mean that a class or member is final? o final - declare constant o finally - handles exception o finalize - helps in garbage collection Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method. What is the Java API? The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. Why there are no global variables in Java? Global variables are globally accessible. Java does not support globally accessible variables due to following reasons: · The global variables breaks the referential transparency · Global variables creates collisions in namespace. How to convert String to Number in java program? The valueOf() function of Integer class is is used to convert string to Number. Here is the code example: String numString = “1000″; int id=Integer.valueOf(numString).intValue();
  • 12. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. What is the difference between a while statement and a do statement? A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once. What is the Locale class? The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region. Describe the principles of OOPS. There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation. Explain the Inheritance principle. Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places What is implicit casting? Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios. Example int i = 1000; long j = i; //Implicit casting Is sizeof a keyword in java? The sizeof operator is not a keyword. What is a native method? A native method is a method that is implemented in a language other than Java. In System.out.println(), what is System, out and println? System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object. What are Encapsulation, Inheritance and Polymorphism Or Explain the Polymorphism principle. Explain the different forms of Polymorphism. Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation. Polymorphism exists in three distinct forms in Java: • Method overloading • Method overriding through inheritance • Method overriding through the Java interface What is explicit casting? Explicit casting in the process in which the complier are specifically informed to about transforming the object.
  • 13. Example long i = 700.20; int j = (int) i; //Explicit casting What is the Java Virtual Machine (JVM)? The Java Virtual Machine is software that can be ported onto various hardware-based platforms What do you understand by downcasting? The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy What are Java Access Specifiers? Or What is the difference between public, private, protected and default Access Specifiers? Or What are different types of access modifiers? Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing privileges to parts of a program such as functions and variables. These are: • Public : accessible to all classes • Protected : accessible to the classes within the same package and any subclasses. • Private : accessible only to the class to which they belong • Default : accessible to the class to which they belong and to subclasses within the same package Which class is the superclass of every class? Object. Name primitive Java types. The 8 primitive types are byte, char, short, int, long, float, double, and boolean. What is the difference between static and non-static variables? Or What are class variables? Or What is static in java? Or What is a static method? A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated. Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass. Non-static variables take on unique values with each object instance.
  • 14. What is the difference between the boolean & operator and the && operator? If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped. How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. What if I write static public void instead of public static void? Program compiles and runs properly. What is the difference between declaring a variable and defining a variable? In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String (”bob”); Or String s = “bob”; are both definitions. What type of parameter passing does Java support? In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object. Explain the Encapsulation principle. Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. What do you understand by a variable? Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program. What do you understand by numeric promotion? The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required. What do you understand by casting in java language? What are the types of casting? The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting. What is the first argument of the String array in main method? The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null. How can one prove that the array is not null but empty? Print array.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 array.length.
  • 15. Can an application have multiple classes having main method? Yes. 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 amongst the multiple classes having main method. When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java? Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields. Can I have multiple main methods in the same class? We can have multiple overloaded main methods but there can be only one main method with the following signature : public static void main(String[] args) {} No the program fails to compile. The compiler says that the main method is already defined in the class. Explain working of Java Virtual Machine (JVM)? JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes. How can I swap two variables without using a third variable? Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example: int a=5,b=10;a=a+b; b=a-b; a=a-b; An other approach to the same question You use an XOR swap. for example: int a = 5; int b = 10; a = a ^ b; b = a ^ b; a = a ^ b; What is data encapsulation? Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding. What is reflection API? How are they implemented? Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method,
  • 16. Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK. What is phantom memory? Phantom memory is false memory. Memory that does not exist in reality. Can a method be static and synchronized? A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang. Class instance associated with the object. It is similar to saying: synchronized(XYZ.class) { } What is difference between String and StringTokenizer? A StringTokenizer is utility class used to break up string. Example: StringTokenizer st = new StringTokenizer(”Hello World”); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } Output: Hello World What is the difference between interpreted code and compiled code? An interpreter produces a result from a program, while a compiler produces a program written in assembly language and in case of Java from bytecodes.The scripting languages like JavaScript,Python etc. require Interpreter to execute them.So a program written in scripting language will directly be executed with interpreter installed on that computer,if it is absent then this program will not execute.While in case of compiled code,an assembler or a virtual machine in case of Java is required to convert assembly level code or bytecodes into machine level instructions/commands.Generally, interpreted programs are slower than compiled programs, but are easier to debug and revise. What is the difference between JVM and JRE? A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any computer.A JRE contains a Java Virtual Machine(JVM),all standard,core java classes and runtime libraries. It does not contain any development tools such as compiler, debugger, etc. JDK(Java Development Kit) is a whole package required to Java Development which essentially contains JRE+JVM,and tools required to compile and debug,execute Java applications.