Sunday 30 October 2011

JAVA - Master List Of Core Java Questions



www.Technicalsymposium.com
One  s’Top solution for all your educational and technical needs 

Master List Of Core Java Questions

What is an Object?

An object is an entity with certain attributes or qualities and behaviors, for a simple example, a 'Laptop' is an object which has certain attributes like weight,color,screen size,manufacturer etc.It has various behaviors or activities to do or act upon, as play games, browse Internet,write/check emails , watch movies ,listen music etc.

What is a Class?

A class is a collection of attributes and behaviors of objects with certain similarities and an instance of a class is represented by an object.A simple example of class is a 'Car' which represents variety of Car objects with different attribute values and behaviors.The different objects of 'Car' class can be, for example : A Mercedes Car,a Toyota Car, two different objects from same class but different attributes and different behaviors too.

What is OOAD?

Object Oriented Analysis and Design(OOAD) is a methodology to analyze,design and develop application using objects and their relations and message based communication to each other.Everything in OOAD is visualized in terms of objects and classes.OOAD introduced a paradigm shift from thinking and programming procedurally to objects oriented programming.This approach helps in designing complex real time systems with ease.The features like Data Abstraction and Encapsulation, Inheritance and Polymorphism form fundamentals of object oriented programming.
Advantages:
  • Enhanced Reusability
  • Modular approach towards problem solving which will be
  • Better Maintainability
    Better Performance if system is designed cautiously using OOAD concepts

What is Data Abstraction?

Data Abstraction is extraction of essential information for a particular purpose and ingnoring the remainder of the information,e.g. a car is consisted of an engine,air filters,a carburetor,a gear box,a steering,a fuel tank,tyres etc.A driver of a car need not to be bothered about several finer points of the car,he/she should know what it requires to drive a car.Take another user, a car mechanic, he will require different set of information in order to repair the car.

What is Data Encapsulation?

Data Encapsulation is wrapping informations(attributes and behaviors) within an object.A suitable example is a class as it wraps methods and data within itself. The attributes of a class corresponds to its data members while behaviour corresponds to member methods of the class.

What is the difference between Data Abstraction and Information Hiding?

Data Abstraction is often confused with information hiding while they altogether are two different technical concepts.Here are few established definitions of Data Abstraction:

What is Inheritance and what are different types of it?

Inheritance is a mechanism by which a specific object acquires attributes and behaviors of more general objects.In OOP terminology ,Inheritance is the mechanism which allows a Class 'A' to inherit properties of Class 'B' and we say 'A inherits from B' or in other words B is a 'Superclass'/'Parent class' while A is a 'Subclass'/'Child class'. A typical example of inheritance is a family tree which consists of son,father,grandfather,great grandfather and so on.The different types of Inheritance are:

1.Single Inheritance
2.Multiple Inheritance
3.Multilevel Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance

Why Java uses Singly rooted hierarchy?

All objects in Java are inherited from same base class called 'Object'.In Java all objects have common interface to implement and it makes implementaion of Garbage collector lot easier in Java.The necessary implementaion is provided in base class , and the garbage collector can then send the necessary messages to every objectc in the system.Without singly rooted hierarchy,it would have been difficult to implement garbage collection feature.It enables lot of ease to programmers not to be bothered about memory management while development.It greatly simplifies argument passing amongst object too on the heap. As Java started from scratch and has no backward compatibility issues with any existing language, it was a logical choice to use the singly-rooted hierarchy in common with most other object-oriented programming languages.

Why does Java not support Multiple Inheritance?

Java does not support multiple inheritance atleast not the way it does in case of C++.In designer’s view Multiple Inheritance poses many problems and confusions than it solves.e.g. famous Diamond problem The diamond problem is an ambiguity that can occur when a class multiply inherits from two classes that both descend from a common super class. In such scenarios assuming if Java implements multiple inheritance then it would be difficult to know which method is to be called by an inheriting class object of two of the super classes. In Java, interfaces solve all these ambiguities caused by the diamond problem. Through interfaces, Java allows multiple inheritance of interface but not of implementation. Implementation, which includes instance variables and method implementations, is always singly inherited. As a result, confusion will never arise in Java over which inherited instance variable or method implementation to use.

Why is Java not 100% pure OOP language?

Java takes inspirations from C and C++.The native datatypes like 'char','int','float','double' are straight pick from C, which is not an Object Oriented Language.Resonably enough, Java is not a 100% pure Object Oriented Language.

What is Early Binding?

The assignment of types to variables and expressions at compilation time is known as 'Early Binding',it is also called 'static binding' and 'static typing'.

What is Polymorphism/Late Binding?

When an object is sent a message then it does not know itself what type it is, the runtime environment will decide about function calling over an object. This feature of connecting an object with its associated message at runtime is known as Polymorphism or Late binding or Dynamic binding.

What is method overloading?

A method with changed formal parameters will lead to implementing method overloading.
int calculateSum(int i,int j)
float calculateSum(float i,int j)
double calculateSum(double i,int j)
float calculateSum(int i,float j)

What is method overriding?

The method with same signature but with changed implementation lead to method overriding and that can occur in a parent child relation of classes. A method defined in parent class can be overridden in its child class with different implementation from its base class.
1.      Pointers are supported in C++ while not in Java. The memory management is done automatically with help of part of JVM called Garbage Collector.
2. Multiple inheritance is not supported in Java but supported in C++.
3. There are no structures and unions in Java.
4. There is no scope resolution operator in Java (::).
5. There are no destructors in Java like C++.
6. There is no virtual keyword in Java because all non-static method use dynamic binding.

How is Java different from C++?

Java is a platform independent, object oriented language while C++ is having some of its features from C, which is a procedural language so it is not pure object oriented. Even Java is not 100% pure object oriented.

1. Pointers are supported in C++ while not in Java. The memory management is done automatically with help of part of JVM called Garbage Collector.
2. Multiple inheritance is not supported in Java but supported in C++.
3. There are no structures and unions in Java.
4. There is no scope resolution operator in Java (::).
5. There are no destructors in Java like C++.
6. There is no virtual keyword in Java because all non-static method use dynamic binding.

What is UML and how is it useful in designing large systems?

Unified Modelling Language(UML) is a notational language which comprises of several tools and techniques to support object oriented development.UML captures scenarios(use case diagram),object interactions(sequence diagram),class interactions(class diagrams) and object states(state diagrams).

UML helps in designing large and complex systems.It starts with analysis of business requirement and coming up with basic business flow chart and static diagrams i.e. use case diagrams which gives pictorial view of business requirements and captures scenarios. The next step is Interaction diagrams,which mainly consists of Sequence diagrams.A Sequence diagram tells how objects interact with each other through message passing in most importantly in what sequence.Then classes are identified of the system with various class identification approaches like 'Noun Phrase Approach','CRC Approach',this exercise results in UML class diagrams.

A modular approach helps in breaking down the complex system where each module can further be divided into components like classes and objects.Once the whole system is refined in terms of reusability of objects,omitting unnecessary objects and classes.The building of skeleton code on best practices of coding, like pattern based approach, helps in foundation of efficient code.

Is UML useful for procedural programming ?

Procedural programming is an unstructured way of programming which consists of set of procedures/method calls/instructions to be executed sequentially in such a way to attain the objective of a program.UML can help here in a very basic way in laying out the sequence of executions of instructions.

What are different notations used in UML ?

UML predominantly includes static and dynamic model diagrams and each diagram has their own set of notations.
In brief, the classification of these diagrams is given as below: #

Structure Diagrams include the Class Diagram, Object Diagram, Component Diagram, Composite Structure Diagram, Package Diagram, and Deployment Diagram.

Behavior Diagrams include the Use Case Diagram (used by some methodologies during requirements gathering); Activity Diagram, and State Machine Diagram.

Interaction Diagrams, all derived from the more general Behavior Diagram, include the Sequence Diagram, Communication Diagram, Timing Diagram, and Interaction Overview Diagram.

What is a Use case and an Actor?

A Usecase represents a particular scenario which corresponds to functional requirement(s) of a system to be designed and developed.An Actor is a user/external program or a system(anyone or anything), which interacts with a system.An Actor may input/receive or both(input and receive) information from the system.
In the diagram shown below, a scenario of buying bus/train/tram ticket from a vending machine is captured through a use case diagram.Here actor is a 'Customer' as shown by a stickman and in ovals all usecases have been documented.

How to identify an Actor?

An Actor can be identified by finding an answer for following points: Who is:
-interacting
-benefited
-maintaining
-supplying information
-using information
-removing information Does system use an external resource?
A good/refined set of actors of system will be arrived iteratively.

What is Generalization?

In UML , a generalization relationship is a relationship in which one model element (the child) is based on another model element (the parent). Generalization relationships are used in class, component, deployment, and use case diagrams.
Generalization corresponds to inheritance implemenation amongst classes.

What is Association and how it maps into a Java class?

An Association specifies how objects are related to one another.To identify associations,look for verb and prepositional phrases like 'part of','next to','works for' or 'contained in'.While identifying implicit associations,a lot common sense and general knowledge is required.It is very important to eleminate redundant associations while desiging a system.The most important aspects of associations are:
Cardinality - a cardinality of one on a given relationship end generates a Java reference, for example
public class Customer
{
Purchase purchase; ...
}
A cardinality of many (depicted as a number or *) generates a Java container:

public class Customer
{
List purchases; ...
}

Navigability - For given an instance of an object on one side of a association you can access an instance on the other side. If a association can only be traversed in one direction then this will be indicated with arrows. If there are no arrows then the association is bi-directional.

Association end - A given class only sees the association through the attributes set on the association end. In other words that simple line actually represents two independent sets of data, one for each of the two classes involved. Besides the cardinality and navigability the most important attribute is the association end name. This name is used to generate the getter and setter methods and in persistent classes database column names.

The different types of associations can be Aggregation and Composition.I will describe them in more details in next blogs to come.

What is Aggregation and how it maps into a Java class?

An Aggregation is an Association which denotes an "is part of" relationship.

Take a 'Car', for example, it is consisted of an engine,a steering wheel, four tires,seats,gear box,fuel tank,engine oil tank, air filters etc.So all constituents of car are parts of it.

If a car is destroyed/smashed, its parts can still be used separately as spares in other cars,so these parts have individual use even when their conatiner entity is destroyed.

In a Java class, an aggregation can be represented from above example as :

class Car
{
List getTires();
List getSeats();
List getAllParts();
}

What is Composition and how it maps into a Java class

A Composition is a tight Association and denotes "whole-part" relationship.So when an object is destroyed then all its constituents are also destroyed, these 'parts' have no meaning/sense in their lone existence from their 'whole'.

The best example of Composition is a 'Human body' which is composed of two legs,two hands,two eyes,two ears and so on.During the lifetime of a human being,all organs make sense being part of whole,but once a human being is dead most of these parts are also dead,unless some of his body parts are not medically reused.

Now come to map composition to Java world, the best example is garbage collection feature of the language.While garbage collecting objects, whole has the responsibility of preventing all its parts being garbage collected by holding some references to them.

It is the responsibility of whole to protect references to its parts not being exposed to outside world.The only way to have true composition in Java is to never let references to internal objects escape their parent's scope.

An example of Inner class as shown in the following code snippet may give you an idea how to implement Composition in Java.

public class Human
{

public Human()
{
Brain brain = new Brain();
}

private class Brain
{
....
....
}

}

What is Dependency and how it maps into a Java class

A Dependency relationship means when a class consumes/uses methods or variables from other class(supplier).So a change to supplier class affects the consumer class as well.Here supplier is indepenedent of any changes being made to consumer classs.

In UML class diagrams, a dependency relationship connector appears as a dashed line with an open arrow that points from the consumer class to the supplier class. A dependency relationship means an "import" statement.

What is the purpose of State machine diagrams?

Objects have both attributes and behaviors. Attribute is also know as state. When objects are incredibly complicated then to have better understanding during different state changes one should develop one or more state machine diagrams, formerly called state chart diagrams in UML 1.x, describing how their instances work.

What are different kinds of Structure diagrams?

Structure Diagrams as part of UML2.1:

Class diagrams
Object diagrams
Composite structure diagrams
Component diagrams
Deployment diagrams
Package diagrams

What are different kinds of Interaction diagrams?

The Interaction diagrams represent how objects interact with one another through message passing.

There are two kinds of Interaction Diagrams :

Sequence Diagram
Collaboartion Diagram


If you want to study these diagrams in detail then go through given by OMG.

What are different kinds of Behavior diagrams?

Behavior Diagrams include :

-
Use Case Diagram (used by some methodologies during requirements gathering)
- Activity Diagram
- State Machine Diagram
.

What is a Java Virtual Machine (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 is a JVM consisted of?

Each time a Java Application is executed then an instance of JVM ,responsible for its running,is created.A JVM instance is described in terms of subsystems, memory areas, data types, and instructions.

What is a class loader and what is its responsibilities?

The Class loader is a subsystem of a JVM which is responsible,predominantly for loading classes and interfaces in the system.Apart from this,a class loader is responsible for the following activities:

-Verification of imported types(classes and interfaces)

-Allocating memory for class variables and initializing them to default values.Static fields for a class are created and these are set to standard default values but they are not explicitly initialized.The method tables are constructed for the class.

What is heap and stack?

The heap is the part of memory of JVM where all objects reside.

The stack is consisted of stack frames.When a thread invokes a method,the JVM pushes a new frame onto that thread's Java stack.Each stack frame is consisted of operand stack and the local variable array.All arguments,local variables,intermediate computations and return values if any are kept in these stack corresponding to the method invoked.The stack frame on the top of the stack is called the active stack frame,which is the current place of execution.When the method completes, the virtual machine pops and discards the frame for that method.

 

 

How is your Java program executed inside JVM?

When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance invoke main() method of Java application.The main() method of an application serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.

This thread has a program counter(PC) and Java stack.Whenever main() method is invoked, a stack frame is pushed onto the stack,this then becomes the active tack frame.The program counter in the new Java stack frame will point to the beginning of the method.

If there are more method invocations within main() method then this process of pushing new stack frame onto the stack for each method call is repeated as and when they are invoked.When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame.The PC is set to the instruction after the method call and the method continues.

There is only one heap corresponding to an instance of JVM and all objects created are stored here.This heap is shared by all threads created in an application.

Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application--the one that begins at main()--is a non- daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

When main() returns,it terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.

What is Java class file's magic number?

A Magic Number of a class file is a unique identifier for tools to quickly differentiate class files from non class files.The first four bytes of each Java class file has the magic value as 0xCAFEBABE.And the answer to why this number,I do not actually know but there may be very few sensible and acceptable options possible constructed from letters A-F which can surely not be 'CAFEFACE' or 'FADECAFE'....

How JVM performs Thread Synchronization?

JVM associates a lock with an object or a class to achieve mutilthreading. A lock is like a token or privilege that only one thread can "possess" at any one time. When a thread wants to lock a particular object or class, it asks the JVM.JVM responds to thread with a lock maybe very soon, maybe later, or never. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.If a thread has a lock,no other thread can access the locked data until the thread that owns the lock releases it.

 

How JVM performs Garbage Collection?

One of the most frequently asked questions during interviews and it seeks a precise and clear understanding of the concept. Whenever a reference to an object on heap lies dangling or no longer in use by an active program then it becomes eligible for being garbage collected by JVM.JVM specifications do not force any specific kind of garbage collection algorithm though there are several algorithms like reference

How to profile heap usage?

Try using -Xaprof to get a profile of the allocations (objects and sizes) of your application.

Also try -agentlib:hprof=heap=all (or other option, try -agentlib:hprof=help for a list) What will you do if VM exits while printing "OutOfMemoryError" and increasing max heap size doesn't help?

The Java HotSpot VM cannot expand its heap size if memory is completely allocated and no swap space is available. This can occur, for example, when several applications are running simultaneously. When this happens, the VM will exit after printing a message similar to the following.

Exception java.lang.OutOfMemoryError: requested bytes

If you see this symptom, consider increasing the available swap space by allocating more of your disk for virtual memory and/or by limiting the number of applications you run simultaneously. You may also be able to avoid this problem by setting the command-line flags -Xmx and -Xms to the same value to prevent the VM from trying to expand the heap. Note that simply increasing the value of -Xmx will not help when no swap space is available.

Should one pool objects to help GC? Should one call System.gc() periodically?

The answer is No!

Pooling objects will cause them to live longer than necessary. The garbage collection methods will be much more efficient if you let it do the memory management. The strong advice is taking out object pools.

Don't call System.gc(), HotSpot will make the determination of when its appropriate and will generally do a much better job.

An application has a lot of threads and is running out of memory, why?

You may be running into a problem with the default stack size for threads. In Java SE 6, the default on Sparc is 512k in the 32-bit VM, and 1024k in the 64-bit VM. On x86 Solaris/Linux it is 320k in the 32-bit VM and 1024k in the 64-bit VM.

On Windows, the default thread stack size is read from the binary (java.exe). As of Java SE 6, this value is 320k in the 32-bit VM and 1024k in the 64-bit VM.

You can reduce your stack size by running with the -Xss option. For example:

java -server -Xss64k

Note that on some versions of Windows, the OS may round up thread stack sizes using very coarse granularity. If the requested size is less than the default size by 1K or more, the stack size is rounded up to the default; otherwise, the stack size is rounded up to a multiple of 1 MB.

64k is the least amount of stack space allowed per thread.

If your program is I/O bound or running in native methods, do these activities engage JVM?

The answer is 'No'.If the program is I/O bound or running in native methods, then the VM is not involved in the consumption of CPU time. The VM technology will engage CPU for running bytecodes. Typical examples of time spent not running bytecode are graphical operations that make heavy use of native methods, and I/O operations such as reading and writing data to network sockets or database files.

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.

Why Java based GUI intensive program has performance issues?

GUI intensive Java application mostly run underlying OS specific native libraries which is time and more CPU cycles consuming.

The overall performance of a Java application depends on four factors:
  • The design of the application
  • The speed at which the virtual machine executes the Java bytecodes
  • The speed at which the libraries that perform basic functional tasks execute (in native code)
  • The speed of the underlying hardware and operating system
The virtual machine is responsible for byte code execution, storage allocation, thread synchronization, etc. Running with the virtual machine are native code libraries that handle input and output through the operating system, especially graphics operations through the window system. Programs that spend significant portions of their time in those native code libraries will not see their performance on HotSpot improved as much as programs that spend most of their time executing byte codes.

What is 64 bit Java ?

A 64-bit version of Java has been available to Solaris SPARC users since the 1.4.0 release of J2SE. A 64-bit capable J2SE is an implementation of the Java SDK (and the JRE along with it) that runs in the 64-bit environment of a 64-bit OS on a 64-bit processor. The primary advantage of running Java in a 64-bit environment is the larger address space.

This allows for a much larger Java heap size and an increased maximum number of Java Threads, which is needed for certain kinds of large or long-running applications. The primary complication in doing such a port is that the sizes of some native data types are changed. Not surprisingly the size of pointers is increased to 64 bits. On Solaris and most Unix platforms, the size of the C language long is also increased to 64 bits. Any native code in the 32-bit SDK implementation that relied on the old sizes of these data types is likely to require updating.

Within the parts of the SDK written in Java things are simpler, since Java specifies the sizes of its primitive data types precisely. However even some Java code needs updating, such as when a Java int is used to store a value passed to it from a part of the implementation written in C.

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.

What are different datatypes in Java?

Java supports following 8 primitive datatypes:
(click this picture to enlarge)
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhS50OcR9hbyplUD-PhaEjJVxC9Ny475_3-sV5e9lo2cwcz4kDDn1XCLTyzUHAdVufSok9rTpCAMa9c4vKupJRNCzcjPPdqfoyaBnIZkxn3V34YKfmVmv3loi-TB3JqtLv8IsGgtWV0Xsz_/s400/datatypes.JPG

What are expressions,statements and blocks in Java?

An expression is a construct made up of variables, operators, and method invocations, which are built-up according to the syntax of the language, that evaluates to a single value.

Some examples of expression:
int val = 0;
iArr[0] = 20;
int var = 4 + 2; // var is now 6

A statement is complete unit of execution.Any expression which is :

  • An assignment expression

  • ++ or --

  • Method invocation

  • Object creation

What is a transient variable?

The lexical meaning of word transient is 'existing for a short duration',in Java,a transient variable is one which one would not like to be saved during seralization.This is mostly the case when a variable is sensitive enough that it should not be saved during serialization, such as a password.Even when such variable is private in the object,once it is serialized it is possible to read it inside a file or over a network.The keyword 'transient' is solution for such variables that are not required to be serialized.

What is the difference between the '&' operator and the '&&' operator?

'&&' is a Logical operator while '&' is a Bitwise operator.
e.g.

int x=12; binary represenation of 12---------> 1100
int y=10; 1010 binary represenation of 10---------> 1010
int z=x & y; binary represenation of (x & y)---------> 1000
Here value of z will be 8.

In case of logical operatior '&&':
condition1 && condition2
if condition1 is false then (condition1 && condition2) will always be false, that is the reason why this logical operator is also known as short circuit operator.
if condition1 is true then condition2 is to be evaluated, if it is true then overall result will be true else it will be false.

Why main method of Java has public static void?

It is the main entry point of a java file. Every java file has just single copy of main method from where main thread is invoked and that's why main method is static. This method can be overloaded but JVM will distinguish public static void main from rest of the overloaded main methods.

What are the command line arguments?

Whenever a java file is executed it is done by java command given as below: java Usage: java [-options] class [args...]
(to execute a class)
or java -jar [-options] jarfile [args...]
(to execute a jar file)
when some arguments are also passed with execution command then these arguments are called command line arguments as they are taken as an array of String as a parameter in main method.

Does Java support multi dimensional arrays?

The Java programming language does not really support multi-dimensional arrays. It does, however, support arrays of arrays. In Java, a two-dimensional array 'arr' is really an array of one-dimensional arrays:
int[][] arr = new int[4][6];
The expression arr[i] selects the one-dimensional array; the expression arr[i][j] selects the element from that array.
The built-in multi-dimensional arrays suffer the same indignities that simple one-dimensional arrays do: Array indices in each dimension range from zero to , where length is the array length in the given dimension. There is no array assignment operator. The number of dimensions and the size of each dimension is fixed once the array has been allocated.

What are the restrictions for static method?

Whenever you say something is static that means data or method is not associated with an object instance of that class.They are allocated when a class is loaded,during compile time. Only a single copy of that will be created for that class. So even if you have never created an object of a class you an always access static data and method of that class. If you have class by name 'Vehicle' and you have a static method 'drive()' then it can simply be invoked by ' Vehicle.drive()', no need of object cretaion in this scenario.A static method cannot access non static data and can invoke other static methods.All static methods are automatically final. It is redundant to make them final.

Why an abstract method cannot be static?

An abstract method is usually defined in an abstract class or an interface,for which implementation is provided in a subclass or a class implementing the interface.As static methods just have single copy per class and are interpreted at code compile time,not at runtime, so it is impossible to have polymorphic behaviour out of them.In other words, they cannot be overridden.
An abstract class is one which cannot be instantiated but a static method defined in abstract class can be invoked without creating an instance.So there is no mechanism to ensure call of an abstract static method.
Moreover this is a design decision by language designers. :-)

Is 'sizeof' a keyword?

No, 'sizeof' is an operator used in C and C++ to determine the bytes of a data item, but it is not used in Java as all data types are standard sized in all machines as per specifications of the language.
A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.In JDK 1.5+ you can use java.lang.instrument.Instrumentation. getObjectSize() to get the object size.
On JavaWorld, I have found an interesting article on Objects' size determination, read.

What is the precedence of operators in Java?

The precedence of operators suggests the sequence in which operators will be work upon in case of compounded statements containing several operators.
For example, in the expression
x = a + b * c;
the first "+" operator still first determines its left operand ("a" in this case) and then its right operand. But in this case the right operand consists of the expression "b*c". The multiplication operator "*" has a higher precedence than the additive "+".
Precedence can be overridden with parentheses, e.g.
x = (a + b) * c;
will force the addition of b to a, and then this sum is multiplied by c.
The table shown in image below is organised from higher precedence to low, when you traverse from top to the bottom of the table.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2Jqk0oniz1JTwhBFwPAl7M4AhxG7Fe9dWVV_bGpi0odgfbouGrENOoGFnXS1BYeXPzzx_sJXwQ95-ojircl7ngFxcas7yQpILAuUwgZePq4SCfkMuLFaB_mrBkArbjA24496toA-ymYNS/s400/precedence.JPG

How is an argument passed in Java methods?

In Java no matter if the variable is primitive datatype or an object when passed as an argument to a method, they are always passed by value.
This is a most common error that most of newcomers to language and even veterans do in understanding this concept.
Please go through to following link on java.sun.com website for a detailed discussion and understanding of this concept.

What is the difference between class variable, member variable and automatic(local) variable?

The class variable is a static variable and it does not belong to any instance of class but shared across all the instances.
The member variable belongs to a particular instance of class and can be called from any method of the class.
The automatic or local variable is created on a method entry and valid within method scope and they have to be initialized explicitly.

When are static and non static variables of a class initialized?

The static variables are initialized at class load time during compilation and non static variables are initialized just before the constructor is called.

Can shift operators be applied to float types?

No, shift operators are applicable only on integer or long types.

What are different Java declarations and their associated rules?

All variables in Java are introduced/declared with some basic datatypes with some basic values, e.g. every decimal value by default is a double.The names of variables must avoid reserved Java keywords.The local variables are explicitly initialized.

What are Java Modifiers?

Java classes, interfaces, and their members can be declared with one or more modifiers.They can be categorised as:

Class Modifiers :
ClassModifier: one of
public private(for inner classes) protected(for inner classes)
abstract static final strictfp
Any top level class can either be public or package private(no explicit modifier)

Field Modifiers
FieldModifier: one of
public protected private
static final transient volatile

Method Modifiers
MethodModifier: one of
public protected private abstract static
final synchronized native strictfp

Constructor Modifiers
ConstructorModifier: one of
public protected private

The following matrix of the all modifiers in Java shows which modifier maps to which element:-
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZGKWBl267EM8F32O2bGpxl6FvsmmzcsrXKbplAzs7LRY6rUZLWCQf3bPLG2ro8V53Gd2u_UJ2onpun1duRuAygOz5soscIbrC46Xcg-XvdUO4eM857hwc7ZWSkWgJqp2icf2jxVXS-Ncf/s400/ModifierElementsMatrix.JPG

Explain final modifier.

'final' modifier can be applied to classes, methods and variables and the features cannot be changed. final class cannot be subclassed, methods cannot be overridden

Can you change the reference of the final object?

No the reference cannot be changed, but the data in that object can be changed.

Can abstract class be instantiated?

No,an abstract class cannot be instantiated i.e you cannot create a new object of this class. When does the compiler insist that the class must be abstract?

In following conditions,compiler insists 'abstract' keyword with a class :
  • If one or more methods of the class are abstract.
  • If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
  • If class implements an interface and provides no implementation for those methods

Where can static modifiers be used?

They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class.They are loaded at the class compile time.

What is static initializer code?

A class can have a block of initializer code that is simply surrounded by curly braces and labeled as static e.g.
public class Demo{
static int =10;
static{
System.out.println("Hello world');
}
}
And this code is executed exactly once at the time of class load.

Can an anonymous class implement an interface and extend a class at the same time?

No,an anonymous class can either implement an interface or extend a class at a particular time but not both at the same time.


What are volatile variables?

A volatile variable is modified asynchronously by concurrently running threads in a Java application.It is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

Can protected or friendly features be accessed from different packages?

No,when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package.

How many ways can one write an infinite loop ?

Personally I would recommend following ways to implement infinite loop in Java but their can be other ways like calling a method recursively , though I never tested that.

- while (true)

- for (;;) { }

When do you use 'continue' and 'break' statements?

When one wants to complete the iteration of a loop prematurely then 'continue' statement is used.
While the 'break' statement is used to exit the entire loop whenever encountered.

What is the difference between 'while' and 'do while' loop?

In case of 'do-while' loop, body is always executed at least once,since test is performed at the end of the body.It should usually be ignored while coding.

What is an Assertion and why using assertion in your program is a good idea ?

In a Java program,several times, one would like to make certain assumptions for executing a program.For example,while taking a square root of a numeric value it has to be assumed that this value should not be negative.An assertion is a statement in the Java programming language that enables to test assumptions about one's program.Assertions are supported from J2SE1.4 and later.A simple exmaple of assertion can be checking of an employee object from being null:
Employee employee = null;


Explain Assertions with a code example

The main reason of introducing assertions in Java from R1.4 onwards is to reduce the chances of bugs which otherwise would have gone unnoticed, in one's code.In fact, finding and removing bugs is one tedious and not so exciting task.Assertions should be used for scenarios which ideally should never happen in the lifecycle of a program,check assumptions about data structures (such as ensuring that an array is of the correct length), or enforcing constraints on arguments of private methods.Assertions help in a way to block these bugs at the beginning of writing actual logic inside your code that saves lot of efforts,time and most significantly, costs.A simple assertion facility provides a limited form of design-by-contract programming.In design-by-contract programming identification of preconditions and post conditions to a program are must before even starting the coding itself.

Here is simple Java code which uses assertions, here the task is to determine the gender of a person.We have used a switch-case statement to define the over all flow of the logic :

How many forms of assertions we have?

There are two forms of assertions:
The first, simpler form is:
assert Expression1 ;
where Expression1 is a boolean expression.
When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
While the second form of the assertion statement is:
assert Expression1 : Expression2 ;
where:
Expression1 is a boolean expression.
Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)
This form is used when the assert statement has to provide a detail message for the AssertionError.The system passes the value of Expression2 to the appropriate AssertionError constructor, and this constructor uses the string representation of the value as the error's detail message. This detail message helps in analysing and diagnosing the assertion failure which ultimately helps in resolving the error.


When assertions should be avoided?

In following situations the assertions should be avoided:
-When assertion becomes a performance issue.It means an assertion should not include too complex logic equalling implementation of a method.
-Do not use assertions in argument checking of public methods.As argument checking is part of a method implementation and if these arguments are erroneous then it will throw runtime exception and assertion failure will not result in any error.

What situations are best suitable for implementing assertions?

Assertions can best be implemented :
- As Internal Invariants
- As Control flow Invariants
- As Preconditions and Postconditions
- As Class Invariants

What is Exception ?

An exception is an abnormal behavior existing during a normal execution of a program. For example: When writing to a file if there does not exist required file then an appropriate exception will be thrown by java code.

What is a user-defined exception?

For every project you implement you need to have a project dependent exception class so that objects of this type can be thrown so in order to cater this kind of requirement the need for user defined exception class is realized.
for example:

class MyException extends Exception{
public MyException(){};
public MyException(String msg){
super(msg);
}

What do you know about the garbage collector?

In Java, memory management is done automatically by JVM.A programmer is free of this responsibility of handling memory. A garbage collector is a part of JVM responsible for removing objects from heap, which is no longer in use. The garbage collector typically runs in a background thread, periodically scanning the heap, identifying garbage objects, and releasing the memory they occupy so that the memory is available for future objects.

Why Java does not support pointers?

As per the design decision Java does not support pointers explicitly.This greatly reduces the burden of dynamic memory management while coding from programmers.Though programmers dynamically allocate memory while coding but they need not worry about deallocating this memory.The automatic garbage collection feature of Java collects dangling references of objects though it has a trade off on performance as programmer managed memory management will be efficient as compared to JVM driven automatic garbage collection.

Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. As garbage collection is JVM dependent then It is possible for programs to use memory resources faster than they are garbage collected.Moreover garbage collection cannot be enforced,it is just suggested.Java guarantees that the finalize method will be run before an object is Garbage collected,it is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
The garbage collection is uncontrolled, it means you cannot predict when it will happen, you thus cannot predict exactly when the finalize method will run. Once a variable is no longer referenced by anything it is available for garbage collection.You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen.

What is finally in Exception handling?

'finally' is a part of try-catch-throw and finally blocks for exception handling mechanism in Java.'finally' block contains snippet which is always executed irrespective of exception occurrence. The runtime system always executes the statements within the finally block regardless of what happens within the try block. The cleanup code is generally written in this part of snippet e.g. dangling references are collected here.

What can prevent the execution of the code in finally block?

Use of System.exit()
-The death of thread
-Turning off the power to CPU
-An exception arising in the finally block itself

Explain 'try','catch' and 'finally' blocks?

In Java exceptions are handled in try, catch, throw and finally blocks. It says try a block of Java code for a set of exception/s catch an exception if it appears in a catch block of code separate from normal execution of code. It clearly segregates errors from a block of code in an effective and efficient manner. The exceptions, which are caught, thrown using throw keyword. A finally block is called in order to execute clean up activities for any mess caused during abnormal execution of program.

Define Checked and Unchecked exception.

A checked exception is one, which a block of code is likely to throw, and represented by throws clause.It represents invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files).
In Java it is expected that a method 'throws' an exception which is a checked exception.They are subclasses of Exception.
While unchecked exceptions represent defects in the program (often invalid arguments passed to a non-private method).
According to definition in The Java Programming Language, by Gosling, Arnold, and Holmes,"Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time." They are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).

What is the difference between an abstract class and an interface?

An abstract class allows its subclasses to override the methods defined in it. It is never instantiated and a class can inherit from a single class, as Java doesn't support for Multiple Inheritance. It may contain both abstract and non-abstract methods.
An interface has public, abstract methods and may have public, static and final variables (read only). It introduces multiple inheritance by a class implementing several interfaces.

What is the use of interface?

An interface is a collection of public abstract methods and read only i.e. public, static and final variables.
The concept of interfaces in Java makes Multiple Inheritance a reality. Two or more non-related classes can implement the same interface. A class can implement multiple interfaces.Whenever there has to be an ancestry associated with classes along with some concrete behaviors then it is good idea to come up with abstract classes in such scenario but when implementation is more generic in nature and not dependent upon class relations or type hierarchy then such behaviors should be packaged inside an interface.The methods defined inside an interface can be implemented by non related classes.

What is serializable interface?

In java.io package there is an interface called java.io.Serializable, which is a syntactic way of serializing objects. This interface does not define any method. The purpose of serialization is persistence, communication over sockets or RMI. In Object serialization an object can be converted into byte stream and vice versa.

Does a class inherit constructors from its superclass?

The answer is No.Constructors cannot be inherited.Constructors are used to initialize a valid sate of an object.Whenever a subclass instance is created then it calls no argument default constructor of super class.

The following code will explain implicit call to default constructor of base class:-

class Base {
Base() {
System.out.println("I am constructing Base");
}
}
class Child extends Base {
Child() {
System.out.println("I am constructing Child");
}
}

public class A {
public static void main(String[] args) {
Child child = new Child();
}
}

Once executed this code will print:

I am constructing Base
I am constructing Child

It means when a child class object is created it inherently calls no arg default constructor of base class.

What's the difference between constructors and other methods?

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

If the method to be overridden has access type 'protected', can subclass have the access type as 'private'?

No, it must have access type as protected or public, since an overriding method must restrict access of the method it overrides.

If you use super() or this() in a constructor where should it appear in the constructor?

It should always be the first statement in the constructor.

What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected,
private, static, final, or abstract.

Can an inner class be defined inside a method?

Yes it can be defined inside a method and it can access data of the
enclosing methods or a formal parameter if it is final.

What is an anonymous class?

It is a type of inner class with no name.Once defined an object can be
created of that type as a parameter all in one line. it cannot have
explicitly declared constructor.The compiler automatically provides an
anonymous constructor for such class.
An anonymous class is never abstract. An anonymous class is always an
inner class; it is never static. An anonymous class is always
implicitly final.

What is a thread?

A thread is most fundamental unit of a computer program which is under execution independent of other parts.A thread and a task are similar and often confused.An operating system executes a program by allocating it certain resources like memory,CPU cycles and when there are many a programs doing several things corresponding to several users requests.In such a scenario each program is viewed as a 'task' by OS for which it identifies an allocate resources. An OS treats each application e.g. Word Processor,spreadsheet,email client etc as a separate task , if a certain program initiates some parallel activity e.g. doing some IO operations,printing then a 'thread' will be created fro doing this job.

What is the difference between process and threads?

A thread is part of a process; a process may contain several different threads. Two threads of the same process share a good deal of state and are not protected against one another, whereas two different processes share no state and are protected against one another. Two threads of the same process have different values of the program counter; different stacks (local variables); and different registers.The program counter, stack pointer, and registers are therefore saved in the thread table. Two threads share open files and memory allocation; therefore, file information and memory information (e.g. base/limit register or page table) is stored in the process table.

What are two types of multitasking?

Co-operative
In case of co-operative multitasking applications consume resources i.e. memory and CPU cycle and once it is completed with its execution of set of instructions, it returns control back to the OS. The scheme depends on the application co-operating and so is known as co-operative multitasking. In cases where the application entered an endless loop and never reached the code which handed control back to the operating system, the whole machine became locked up. An example is Windows 3.1
Pre -emptive
In this technique the operating system allocates resources to an application. This will enable it to execute. Rather than wait for the application to give the resources up, the operating system is
activated at certain time intervals and may take the resources back from the executing application and allocate them to another application that is waiting.Example: Unix, Windows NT, and 32 bit programs running under Windows '95


 


Thanks for visiting our site
For More information logon to www.Technicalsymposium.com