Thursday, August 6, 2015

Basic Java Interview Questions & Answers

Java Basics:

What is the most important feature of Java?
Java is a platform independent language.

What do you mean by platform independence?
Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

What is a JVM?
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

Are JVM's platform independent?
JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.

What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

What is a pointer and does Java support pointers?
Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

What is the base class of all classes?
java.lang.Object

Does Java support multiple inheritance?
Java doesn't support multiple inheritance.

Is Java a pure object oriented language?
Java uses primitive data types and hence is not a pure object oriented language.

Are arrays primitive data types?
In Java, Arrays are objects.

Also read: Mobile App Test Strategy

What is difference between Path and Classpath?
Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

What are local variables?
Local varaiables are those which are declared within a block of code like methods. Local variables should be initialised before accessing them.

What are instance variables?
Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.

Should a main() method be compulsorily declared in all java classes?
No not required. main() method should be defined only if the source class is a java application.

What is the return type of the main() method?
Main() method doesn't return anything hence declared void.

What is the argument of main() method?
main() method accepts an array of String object as arguement.

Can a main() method be overloaded?
Yes. You can have any number of main() methods with different method signature and implementation in the class.

Can a main() method be declared final?
Yes. Any inheriting class will not be able to have it's own default main() method.

Does the order of public and static declaration matter in main() method?
No. It doesn't matter but void should always come before main().


What is a package?
Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

What is the access scope of a protected method?
A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.

What is the purpose of declaring a variable as final?
A final variable's value can't be changed. final variables should be initialized before using them.

What is the impact of declaring a method as final?
A method declared as final can't be overridden. A sub-class can't have the same method signature with a different implementation.

I don't want my class to be inherited by any other class. What should i do?
You should declared your class as final. But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class.

How is final different from finally and finalize()?
final is a modifier which can be applied to a class or a method or a variable. final class can't be inherited,final method can't be overridden and final variable can't be changed.

finally is an exception handling code section which gets executed whether an exception is raised or not by the try block code segment.

finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults

This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

A variable declared anywhere in a class can be seen everywhere in a class.
The scope of a method's formal parameters is the entire method.
The scope of a variable declared in a block (indicated by braces, { }) extends from the declaration to the closing brace. A method body is always a block.
The scope of a variable declared in the initialization part of a for loop is the entire for loop.

public : You can access it from anywhere.

protected : You can access it from any other class in the same directory (folder), or from any subclass.

package (default) : You can access it from any other class in the same directory.

private : You cannot access it from outside the class. Surprisingly, private variables and methods can be accessed by other objects in the same class.

If the message and the method have a different number of parameters, no match is possible.
If the message and the method have exactly the same types of parameters, that is the best possible match.
Messages with specific actual parameter types can invoke methods with more general formal parameter types. For example if the formal parameter type is Object, an actual parameter of type String is acceptable (since a String value can be assigned to an Object variable). If the formal parameter is type double, an actual parameter of type int can be used (for similar reasons).
If there is no clear best match, Java reports a syntax error.

Can a class be declared as static?
We can not declare top level class as static, but only inner class can be declared static.
public class Test
{
    static class InnerClass
    {
        public static void InnerMethod()
        { System.out.println("Static Inner Class!"); }
    }
    public static void main(String args[])
    {
       Test.InnerClass.InnerMethod();
    }
}
//output: Static Inner Class!

When will you define a method as static?
When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

I want to print "Hello" even before main() is executed. How will you acheive that?
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.

What is the importance of static variable?
Static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

Can we declare a static variable inside a method?
Static variables are class level variables and they can't be declared inside a method. If declared, the class will not compile.

What is an Abstract Class and what is it's purpose?
A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

Can a abstract class be declared final?
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

What is use of a abstract variable?
Variables can't be declared as abstract. only classes and methods can be declared as abstract.

Can a abstract class be defined without any abstract methods?
Yes it's possible. This is basically to avoid instance creation of the class.

What is the difference between private, protected, and public?
Explain the usage of Java packages.

What's the difference between the methods sleep() and wait()
What would you use to compare two String variables - the operator == or the method equals()?

public class HelloWorld {

    // method main(): ALWAYS the APPLICATION entry point
    public static void main (String[] args) {
            System.out.println ("Hello World!");
    }
}

Classes and objects

A class describes the data and the methods of its objects. Every object belongs to some class.
An object contains data (instance variables) representing its state, and instance methods, which are the things it can do.

A class may also contain its own data (class variables) and class methods. The keyword static denotes such data and methods.

Classes form a hierarchy (tree), with Object at the root. Every class, except Object, has one and only one immediate superclass, but that class has its own immediate superclass, and so on all the way up toObject at the root, and all of these are superclasses of the class. The keyword extends denotes the immediate superclass.

Access
Variables and methods are accessed by name.
There are three dimensions to accessing names: namespaces, scope, and access modifiers.
The scope of a name is the part of a class in which it can be seen.
Class variables and class methods (denoted by the keyword static) can be used anywhere within the class.
You can refer to a name (class or instance) in another class if and only if you have access privileges. Possible access privileges are:

Methods
A method is a named executable chunk of code.
All executable statements must be in methods.
A method has a signature consisting of its name and the number and types of its parameters.
A method has a return type, which is not part of its signature. If the return type is other than void, then the method must return a value of the specified type.
Every method must have a signature that is unique within its class. Methods in other classes (even superclasses and subclasses) may have the same signature.

Polymorphism
The two kinds of polymorphism are overloading and overriding.
Overloading occurs when a class declares two or more methods with the same name but different signatures. When a message is sent to an object or class with overloaded methods, the method with the best matching signature is the one that is used ("invoked").
A class can declare a variable with the same name as an inherited variable, thus "hiding" or shadowing the inherited version. (This is like overriding, but for variables.)

Interfaces and abstract classes
The purpose of interfaces and abstract methods is to ensure that any classes derived from them will share the same set of methods.

Inner classes
An inner class is a class declared within another class. The four kinds of inner class are: (1) member class, (2) static member class, (3) local inner class, and (4) anonymous inner class. Unlike "outer" classes, the usual scope rules apply to inner classes.

Java: 


Java is an open source, platform indipendent and Object oriented programming language.

JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.

The JVM performs following main tasks:
1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment

JRE: JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.

JDK: JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.

Features of Java:
Simple
Object-Oriented
Platform independent
Secured
Robust
Architecture neutral
Portable
Dynamic
Interpreted
High Performance
Multithreaded
Distributed

OOPs: Object-Oriented Programming is a methodology to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
1.Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Object: Any entity that has state and behaviour like Car.

Class: Collection of objects is called class. It is a logical entity.

Inheritance: When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism: When one task is performed by different ways i.e. known as polymorphism.
Example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction: Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.

Encapsulation: Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.


Constructor: Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor:
1.Constructor name must be same as its class name
2.Constructor must have no explicit return type
Types of java constructors:
1. Default.
2. Parametrised.

Java static keyword:
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class

static variable:
The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.


Java static method:
If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.

Super keyword in java:
The super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
super is used to invoke immediate parent class method.

Final Keyword In Java:
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
variable
method
class

6 comments:

  1. 바카라사이트 바카라사이트 betway betway 우리카지노 우리카지노 dafabet link dafabet link 온라인카지노 온라인카지노 온라인카지노 온라인카지노 온라인카지노 온라인카지노 다파벳 다파벳 269

    ReplyDelete