Ans: Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.
OR:
Java is a fast, secure and reliable language used for many games, devices and applications.
Ans:
simple. Java was designed with a small number of language constructs so that programmers could learn it quickly. It eliminates several language features available in C/C++ that are associated with poor programming practices or rarely used: goto statements, header files, structures, operator overloading, multiple inheritance and pointers.
object-oriented. Java is an OOPL that supports the construction of programs that consist of collections of collaborating objects. These objects have a unique identity, encapsulate attributes and operations, and are instances of classes related by inheritance and polymorphism.
distributed. Java is designed to support various levels of network connectivity. Java applications are network aware: TCP/IP support is built into Java class libraries. They can open and access remote objects on the Internet.
interpreted. Java is compiled to bytecodes, which are interpreted by a Java run-time environment.
robust. Java is designed to eliminate certain types of programming errors. Java is strongly typed, which allows extensive compile-time error checking. It does not support memory pointers, which eliminates the possibility of overwriting memory and corrupting data. In addition, its automatic memory management (garbage collection) eliminates memory leaks and other problems associated with dynamic memory allocation/de-allocation.
secure. Java is designed to be secure in a networked environment. The Java run-time environment uses a bytecode verification process to ensure that code loaded over the network does not violate Java security constraints.
architecture neutral. Java applications that are compiled to bytecodes can be interpreted by any system that implements the Java Virtual Machine. Since the Java Virtual Machine is supported across most operating systems, this means that Java applications are able to run on most platforms.
portable. In addition to supporting architecture neutrality, Java ensures that other implementation-dependent aspects of language specification are eliminated. For example, Java specifies the sizes of primitive data types and their arithmetic behavior.
high performance. Although Java is an interpreted language, it was designed to support “just-in-time” compilers, which dynamically compile bytecodes to machine code.
multithreaded. Java supports multiple threads of execution (a.k.a., lightweight processes), including a set of synchronization primitives. This makes programming with threads much easier.
dynamic language. Java supports dynamic loading of classes (a.k.a. “load on demand”), dynamic compilation, and automatic memory management (garbage collection).
Ans: An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.
A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.
Ans: In Java, access specifiers are the keywords used before a class name which defines the access scope. The types of access specifiers for classes are:
Ans: When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.
Ans: Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.
Ans: An object consists of methods and class which depict its state and perform operations. A java program contains a lot of objects instructing each other their jobs. This concept is a part of core java.
Ans: Java encapsulates the codes in various classes which define new data types. These new data types are used to create objects.
Ans:
Ans: Java includes the feature of inheritance which an object-oriented programming concept. Inheritance lets a derived class to inherit the methods of a base class.
Ans: When a Java program contains more than one methods with the same name but different properties, then it is called method overloading.
Ans: Overloading refers to the case of having two methods of same name but different properties, but overriding occurs when there are two methods of same name and properties, but one is in child class and one is in parent class.
Ans: Singleton is created with double checked locking as before Java 5 acts as an broker and it’s been possible to have multiple instances of Singleton when multiple threads creates an instance of Singleton at the same time. Java 5 made it easy to create thread-safe Singleton using Enum. Using a volatile variable is essential for the same.
Ans:
String Buffer | String Builder |
StringBuffer methods are synchronized | StringBuilder is non synchronized |
Storage area is Heap and modified easily. | Storage is Heap and can be modified. |
StringBuffer is thread safe. | StringBuilder is fast as it is not thread safe |
Performance is very slow | Performance is very fast. |
Ans:
Array List | Vector |
Array List is not synchronized. | Vector is synchronized. |
Array List is fast as it’s non-synchronized. | Vector is slow as it is thread safe. |
If an element is inserted into the Array List, it increases its Array size by 50%. | Vector defaults to doubling size of its array. |
Array List does not define the increment size. | Vector defines the increment size. |
Array List can only use Iterator for traversing an Array List. | Except Hashtable, Vector is the only other class which uses both Enumeration and Iterator. |
Ans:
Iterator | Enumeration |
Iterator is an interface found in the java.util package. | Enumeration is an object that generates elements one at a time. Used for passing through a collection for unknown size. |
Uses 3 methods to interface such as:
1. i) hasNext() 2. ii) next() 3. iii) remove() |
Methods used are:
1. i) hasMoreElements() 2. ii) nextElement() |
Iterators allow removing elements from the given collection during the iteration with well-defined semantics. | It is used for passing through a collection, usually of unknown size. |
Iterator method names have been improved. | The traversing of elements can only be done once per creation |
Ans: We can restrict inheritance for class by following steps:
Ans: Yes, We can execute any code, even before the main method. We are using a static block of code in the class when creating the objects at load time of class. Any statements within this static block of code will get executed one time while loading the class, even before the creation of objects in the main method.
Ans: Java doesn’t support multiple inheritance. Because we cannot use different methods in one class it creates an ambiguity.
Example:
class Intellipaat1
{
void test()
{
system.out.println("test() method");
}
}class Intellipaat2
{
void test()
{
system.out.println("test() method");
}
}Multiple inheritance
class C extends Intellipaat1, Intellipaat2
{
………………………………………….
…………………………………………..
}
Intellipaat1 and Intellipaat2 test() methods are inheriting to class C
So which test() method C class will take. As Intellipaat1 & Intellipaat2 class test () methods are different, So here we would face ambiguity.
Ans: Multi threading is a programming concept to run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel. It helps in performance improvement of any program.
Ans: Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi threading.
Ans: Multi threaded applications can be developed in Java by using any of the following two methodologies:
Ans: Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it’s always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.
Ans: Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases too.
If break isn’t used after each case, all cases after the valid case also get executed resulting in wrong results.
Ans: In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.
Ans: If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.
Ans: If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time.
In the example below, continent class is sub-class of world class and it’s super class of country class.
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class world {
..........
}
public class continenet extends world {
............
}
public class country extends continent {
......................
} |
Ans: Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.
Ans: In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it.
Ans: Constructor is called automatically when we create an object using new keyword. It’s called only once for an object at the time of object creation and hence, we can’t invoke the constructor again for an object after its creation.
Ans: Private members of a class aren’t accessible outside the scope of that class and any other class even in the same package can’t access them.
Ans: We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.
For example in the class below we have two print methods with same name but different parameters. Depending upon the parameters, appropriate one will be called:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class methodExample {
public void print() {
system.out.println("Print method without parameters.");
}
public void print(String name) {
system.out.println("Print method with parameter");
}
public static void main(String args[]) {
methodExample obj1= new methodExample();
obj1.print();
obj1.print("xx");
}
} |
Ans: We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.
Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.
Ans: Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.
Ans: Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package,not outside the package.
Ans: There are no pointers in Java. So we can’t use concept of pointers in Java.
Ans: If we want a class not to be extended further by any class, we can use the keyword Final with the class name.
In the following example, Stone class is Final and can’t be extend
1
2 3 4 5 |
public Final Class Stone {
// Class methods and Variables
} |
Ans: When a method or a variable is declared with Protected access specifier, it becomes accessible in the same class,any other class of the same package as well as a sub-class.
MODIFIER | CLASS | PACKAGE | SUBCLASS | WORLD |
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |
Access Levels |
Ans: Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.
Ans: If we want certain variables of a class not to be serialized, we can use the keyword transient while declaring them. For example, the variable trans_var below is a transient variable and can’t be serialized:
1
2 3 4 5 6 7 |
public class transientExample {
private transient trans_var;
// rest of the code
} |
[teaserbox type="5" img="2803" title="Interested in Learning Artificial Intelligence" subtitle="Join myTectra" link_url="http://www.mytectra.com/artificial-intelligence-training-in-bangalore.html" target="blank"]
Ans: Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.
Ans: Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code.
Ans: A thread in Java can be in either of the following states:
Ans: Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and developer can use only those constructors which are defined in the class.
Ans: The basic condition of method overriding is that method name, arguments as well as return type must be exactly same as is that of the method being overridden. Hence using a different return type doesn’t override a method.
1
2 3 4 5 6 7 8 9 10 11 |
public class operatorExample {
public static void main(String args[]) {
int x=4;
system.out.println(x++);
}
} |
Ans: In this case postfix ++ operator is used which first returns the value and then increments. Hence it’s output will be 4.
Ans: Main method is an entry point of Java class and is required for execution of the program however; a class gets compiled successfully even if it doesn’t have a main method. It can’t be run though.
Ans: Non-Static methods are owned by objects of a class and have object level scope and in order to call the non-Static methods from a static block (like from a static main method), an object of the class needs to be created first. Then using object reference, these methods can be invoked.
Ans: Java programs can be executed in a machine only once following two environment variables have been properly set:
Ans: In Java, if a variable is used in a code without prior initialization by a valid value, program doesn’t compile and gives an error as no default value is assigned to variables in Java.
Ans: In Java, a class can be derived from only one class and not from multiple classes. Multiple inheritances is not supported by Java.
Ans: Constructor in Java must have same name as the class name and if the name is different, it doesn’t act as a constructor and compiler thinks of it as a normal method.
Ans: Round(3.7) returns 4 and Ceil(3.7) returns 4.
Ans: In Java, there is not goto keyword and java doesn’t support this feature of going to a particular labeled line.
Ans: In java, a thread which is in dead state can’t be started again. There is no way to restart a dead thread.
1
2 3 4 5 |
public abstract final class testClass {
// Class methods and variables
} |
Ans: The above class declaration is incorrect as an abstract class can’t be declared as Final.
Ans: JDK is development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required.
Ans: In Java, equals() method is used to compare the contents of two string objects and returns true if the two have same value while == operator compares the references of two string objects.
In the following example, equals() returns true as the two string objects have same values. However == operator returns false as both string objects are referencing to different objects:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class equalsTest {
public static void main(String args[]) {
String srt1 = "Hello World";
String str2 = "Hello World";
if (str1.equals(str2))
{// this condition is true
system.out.println("str1 and str2 are equal in terms of values");
}
if (str1==str2) {
//This condition is not true
system.out.println("Both strings are referencing same object");
}
else
{
// This condition is true
system.out.println("Both strings are referencing different objects");
}
}} |
Ans: Yes, we can do this by use of native methods. In case of native method based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like C separately.
Ans: In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.
Ans: No a variable can’t be static as well as local at the same time. Defining a local variable as static gives compilation error.
Ans: Static methods can’t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java.
Ans: No, we can’t change the value of any variable of an interface in the implementing class as all variables defined in the interface are by default public, static and Final and final variables are like constants which can’t be changed later.
Ans: Even though automatic garbage collection is provided by Java, it doesn’t ensure that a Java program will not go out of memory as there is a possibility that creation of Java objects is being done at a faster pace compared to garbage collection resulting in filling of all the available memory resources.
So, garbage collection helps in reducing the chances of a program going out of memory but it doesn’t ensure that.
Ans: No, Java class main method can have only void return type for the program to get successfully executed.
Nonetheless , if you absolutely must return a value to at the completion of main method , you can use System.exit(int status)
Ans: Once an object has been destroyed by garbage collector, it no longer exists on the heap and it can’t be accessed again. There is no way to reference it again.
Ans: Run() is a method of Runnable interface that must be implemented by all threads.
Ans: This can be implemented by use of the concept of synchronization. Database related code can be placed in a method which hs synchronized keyword so that only one thread can access it at a time.
Ans: In order to throw an exception in a block of code manually, throw keyword is used. Then this exception is caught and handled in the catch block.
1
2 3 4 5 6 7 8 9 10 11 12 |
public void topMethod(){
try{ excMethod(); }catch(ManualException e){ } }
public void excMethod{ String name=null; if(name == null){ throw (new ManualException("Exception thrown manually "); } } |
Ans: If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only.
Ans: In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects.
Ans: In java, there is no way to find out the exact size of an object on the heap.
Class A: Three methods, four variables, no object
Class B: Five methods, three variables, no object
Ans: Memory isn’t allocated before creation of objects. Since for both classes, there are no objects created so no memory is allocated on heap for any class.
Ans: If an exception is not handled in a program using try catch blocks, program gets aborted and no statement executes after the statement which caused exception throwing.
Ans: If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this().
Ans: An anonymous class is a class defined without any name in a single line of code using new keyword.
For example, in below code we have defined an anonymous class in one line of code:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public java.util.Enumeration testMethod()
{
return new java.util.Enumeration()
{
@Override
public boolean hasMoreElements()
{
// TODO Auto-generated method stub
return false;
}
@Override
public Object nextElement()
{
// TODO Auto-generated method stub
return null;
}
} |
Ans: Arrays are static and once we have specified its size, we can’t change it. If we want to use such collections where we may require a change of size ( no of items), we should prefer vector over array.
Ans: If there is main method in more than one classes in a java application, it won’t cause any issue as entry point for any application will be a specific class and code will start from the main method of that particular class only.
Ans: The best way to persist data for future use is to use the concept of serialization.
Ans: In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where its defined.
Ans: Although String and StringBuffer both represent String objects, we can’t compare them with each other and if we try to compare them, we get an error.
Ans: Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.
Ans: No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type.
Ans: The basic requirement of method overriding in Java is that the overridden method should have same name, and parameters.But a method can be overridden with a different return type as long as the new return type extends the original.
For example , method is returning a reference type.
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Class B extends A{
A method(int x){
//original method
}
B method(int x){
//overridden method
}
} |
Ans: In Java, Java.lang.Throwable is the super class of all exception classes and all exception classes are derived from this base class.
Ans: In case of inheritance, when a new object of a derived class is created, first the constructor of the super class is invoked and then the constructor of the derived class is invoked.
Ans: Lazy loading is a kind of setting that decides whether to load the child entities with the parent entities or not. When enabling this feature the associated entities will be loaded only when it is requested directly. The default value of this setting is true which stops child entities from loading.
Ans: We can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:
Ans: The Dispatcher Servlet class works as the front controller in Spring MVC.
Ans: The states of an object in hibernate are:
Ans: If we mark a class as mutable=”false”, the class will be treated as an immutable class. The default value of mutable is “true”.
Ans: In Hashtable , if two different keys have the same hash value then it leads to hash -collision. A bucket of type linked list used to hold the different keys of same hash value.
Ans: Collections.synchronizedCollection(Collection collectionObj) will convert a given collection to synchronized collection.
Ans: We can make the Collection readOnly by using the following lines code:
General : Collections.unmodifiableCollection(Collection c)Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
Ans: The below latest features are introduced in Java 8. Lambda Expressions, Interface Default and Static Methods, Method Reference, Parameters Name, Optional Streams, Concurrency.
Ans: Binding is the process of associating or registering a name for a remote object, which can be used as a further, in order to look up that remote object. A remote object can be associated with a name using the bind / rebind methods of the Naming class.
Ans: @Functional Interface annotation
@Repeatable annotation,
@Functional Interface annotation: It was introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.
@Repeatable annotation: introduced in Java SE 8, indicates that the marked annotation can be applied many times to the same declaration or type use.
Ans: A predicate takes one argument and returns a Boolean value.
A function takes one argument and returns an object.
Both are useful for evaluating lambda expressions.
Ans:
. private void sortUsingJava8(List names){
Collections.sort(names, (p1, p2) -> p1.compareTo(p2));
}
Ans: StringJoiner is an util method to construct a string with the desired delimiter.
Sample CodeStringJoiner strJoiner = new StringJoiner(".");
strJoiner.add("AAA").add("BBB");
System.out.println(strJoiner);
OutPut: