Thursday, August 7, 2014

Basics about Java (Class, Variables Methods, Keywords, Identfiers, Coding conventions)

About Java :

Java is a programming language and computing platform first released by Sun Microsystems in 1995.

Features Of Java

The major characteristics of Java are:
  • The programs you create are portable in a network. (See portability.) Your source program is compiled into what Java calls bytecode, which can be run anywhere in a network on a server or client that has a Java virtual machine. The Java virtual machine interprets the bytecode into code that will run on the real computer hardware. This means that individual computer platform differences such as instruction lengths can be recognized and accommodated locally just as the program is being executed. Platform-specific versions of your program are no longer needed.
  • The code is robust, here meaning that, unlike programs written in C++ and perhaps some other languages, the Java objects can contain no references to data external to themselves or other known objects. This ensures that an instruction can not contain the address of data storage in another application or in the operating system itself, either of which would cause the program and perhaps the operating system itself to terminate or "crash." The Java virtual machine makes a number of checks on each object to ensure integrity.
  • Java is object-oriented, which means that, among other characteristics, an object can take advantage of being part of a class of objects and inherit code that is common to the class. Objects are thought of as "nouns" that a user might relate to rather than the traditional procedural "verbs." A method can be thought of as one of the object's capabilities or behaviors.
  • In addition to being executed at the client rather than the server, a Java applet has other characteristics designed to make it run fast.
  • Relative to C++, Java is easier to learn. (However, it is not a language you'll pick up in an evening!)
Java was introduced by Sun Microsystems in 1995 and instantly created a new sense of the interactive possibilities of the Web. Both of the major Web browsers include a Java virtual machine. Almost all major operating system developers (IBM, Microsoft, and others) have added Java compilers as part of their product offerings.
The Java virtual machine includes an optional just-in-time compiler that dynamically compiles bytecode into executable code as an alternative to interpreting one bytecode instruction at a time. In many cases, the dynamic JIT compilation is faster than the virtual machine interpretation.

Java includes


■ Class A template that describes the kinds of state and behavior that objects of its type support.

■ Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object which is an instance of that class. That object will have its own state, and access to all of the behaviors defined by its class.

■ State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state. 

■ Behavior (methods) When a programmer creates a class, she creates methods for that class. Methods are where the class' logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.


Identifiers

All the Java components we just talked about—classes, variables, and methods— need names. In Java these names are called identifiers, and, as you might expect, there are rules for what constitutes a legal Java identifier. 

The three aspects of Java identifiers that we cover here are:

■ Legal Identifiers The rules the compiler uses to determine whether a  name is legal.
    Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).  

Here are some of the rules you do need to know:

  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.  
  • You can't use a Java keyword as an identifier.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.

Examples of legal and illegal identifiers follow, first some legal identifiers:

  • int identifier1;
  • char _name;
  • int  _________2_w;
  • float $currency;
  • int this_is_a_very_big_identifier;

The following are illegal:

  • int :b;
  • int -d;
  • int e#;
  • int .f;
  • int 7g;


■ Sun's Java Code Conventions Sun's recommendations for naming classes, variables, and methods. Sun has created a set of coding standards for Java, and published those standards in a document cleverly titled "Java Code Conventions," which you can find at java.sun.com. It's a great document, short and easy to read and we recommend it highly.

Here are the naming standards that Sun recommends:


Classes and interfaces The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "camelCase"). For classes, the names should typically be nouns. For example:
  • Dog
  • Account
  • PrintWriter
  • For interfaces, the names should typically be adjectives like
    • Runnable
    • Serializable

Methods The first letter should be lowercase, and then normal camelCase rules should be used. In addition, the names should typically be verb-noun pairs. For example:
  • getBalance
  • doCalculation
  • setCustomerName


Variables Like methods, the camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us. Some examples:
  • buttonWidth
  • accountBalance
  • myString

Constants Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators:

  • MIN_HEIGHT

JavaBeans Naming Standards The naming requirements of the JavaBeans specification.
By using naming rules, the JavaBeans spec helps guarantee that tools can recognize and use components built by different developers.

First, JavaBeans are Java classes that have properties. For our purposes, think of 
properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

JavaBean Property Naming Rules

If the property is not a boolean, the getter method's prefix must be get. For example, getSize()is a valid JavaBeans getter name for a property named "size".
■ If the property is a boolean, the getter method's prefix is either get or is. For example, getStopped() or isStopped() are both valid JavaBeans names for a boolean property.
■ The setter method's prefix must be set. For example, setSize() is the valid JavaBean name for a property named size. 
■ To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then append it to the appropriate prefix (get, is, or set). 
■ Setter method signatures must be marked public, with a void return type and an argument that represents the property type. 
■ Getter method signatures must be marked public, take no arguments, and have a return type that matches the argument type of the setter method for that property.

JavaBean Listener Naming Rules
■ Listener method names used to "register" a listener with an event source must use the prefix add, followed by the listener type. For example, addActionListener() is a valid name for a method that an event source will have to allow others to register for Action events.
■ Listener method names used to remove ("unregister") a listener must use the prefix remove, followed by the listener type (using the same rules as the registration add method).
■ The type of listener to be added or removed must be passed as the argument to the method.
■ Listener method names must end with the word "Listener". 

Examples of valid JavaBean method signatures are

  • public void setMyValue(int v)
  • public int getMyValue()
  • public boolean isMyStatus()
  • public void addMyListener(MyListener m)
  • public void removeMyListener(MyListener m)

Examples of invalid JavaBean method signatures are

  • void setCustomerName(String s) // must be public
  • public void modifyMyValue(int v) // can't use 'modify'
  • public void addXListener(MyListener m) // listener type mismatch



 Keywords


abstract
const
finally
int
public
this
assert
boolean
continue
float
interface
return
throw
enum
break
default
for
long
short
throws

byte
do
goto
native
static
transient

case
double
if
new
strictfp
try

catch
else
implements
package
super
void

char
extends
import
private
switch
volatile

class
final
instanceof
protected
synchronized
while


Monday, January 6, 2014

Core Java Questions



CORE JAVA QUESTIONS

OOPS Interview Questions

1.What are the principle concepts of OOPS?
There are four principle concepts upon which object oriented design and programming rest. They are:
•    Abstraction
•    Polymorphism
•    Inheritance
•    Encapsulation
(i.e. easily remembered as A-PIE).

2.What is an Abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations.

Abstraction in Object Oriented Programming helps to hide the irrelevant details of an object. Abstraction is separating the functions and properties that logically can be separated to a separate entity which the main type depends on.

So here we just using jSp  Tags, but we are not aware of these tag implementations, those are hidden by Java People.
Interface an abstract class

3. What is Encapsulation?

Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

Encapsulation in Java or object oriented programming language is a concept which enforce protecting variables, functions from outside of class, in order to better manage that piece of code and having least impact or no impact on other parts of program duec to change in protected code. Encapsulation in Java is visible at different places and Java language itself provide many construct to encapsulate members. You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifier like protected or public.

-Private or protected members
- using accessors and mutators  (setters and getters)

The idea of private class members (attributes, fields) is to access them directly inside the declaring class (not instance!) only. All other classes will have to use other accessors, for example getter and setter methods. So the way how the AdressBookEntry stores the name, address, telNo and email values, is perfectly hidden inside the class.


4.What is the difference between abstraction and encapsulation?

Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
•    Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

5.What is Inheritance?

Inheritance is the process by which objects of one class acquire the properties of objects of another class.
•    A class that is inherited is called a superclass.
•    The class that does the inheriting is called a subclass.
•    Inheritance is done by using the keyword extends.
•    The two most common reasons to use inheritance are:
o  To promote code reuse
o  To use polymorphism

6.What is Polymorphism?

Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

7.How does Java implement polymorphism?

(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name.

•    In some cases, multiple methods have the same name, but different formal argument lists
(overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

8.Explain the different forms of Polymorphism.

There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:

•    Method overloading
•    Method overriding through inheritance
•    Method overriding through the Java interface

9.What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

10.What is Dynamic Binding?

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

11.What is method overloading?

Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement
methods that support the same semantic operation but differ by argument number or type.
Note:
•    Overloaded methods MUST change the argument list
•    Overloaded methods CAN change the return type
•    Overloaded methods CAN change the access modifier
•    Overloaded methods CAN declare new or broader checked exceptions
•    A method can be overloaded in the same class or in a subclass

12.What is method overriding?

Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:

The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
•    You cannot override a method marked final
•    You cannot override a method marked static

13.What are the differences between method overloading and method overriding?

Arguments

Return type

Exceptions

Access

Invocation


14.Can overloaded methods be override too?

Yes derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.,

15.Is it possible to override the main method?
NO, because main is a static method. A static method can't be overridden in Java.

16.How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.

// From subclass super.overriddenMethod();
17.What is super?

super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides
one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:

•    You can only go back one level.
In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.

18.How do you prevent a method from being overridden?

To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.

public final void exampleMethod() {
//  Method statements
}

19.What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must have.

Note:

•    You can’t mark an interface as final.
•    Interface variables must be static.
•    An Interface cannot extend anything but another interfaces.

20.Can we instantiate an interface?

You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.

21.Can we create an object for an interface?

Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.

public interface MyInterface {

    public String hello = "Hello";

    public void sayHello();
}

22.Do interfaces have member variables?

Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.

23.What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

24.What is a marker interface?

Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

25.What is an abstract class?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:

•    If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
•    You can’t mark a class as both abstract and final.

26.Can we instantiate an abstract class?

An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

27.What are the differences between Interface and Abstract class?

Abstract Class


  • An abstract class can provide complete, default code and/or just the details that have to be overridden.
  • In case of abstract class, a class may extend only one abstract class.
  • An abstract class can have non-abstract methods.
  • An abstract class can have instance variables.
  • An abstract class can have any visibility: public, private, protected.
  • If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
  • An abstract class can contain constructors .
  • Abstract classes are fast.


28.When should I use abstract classes and when should I use interfaces?

Use Interfaces when…

•    You see that something in your design will change frequently.
•    If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.

Use Abstract Class when…

If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.

29.When you declare a method as abstract, can other nonabstract methods access it?

Yes, other nonabstract methods can access a method that you declare as abstract.

30.Can there be an abstract class with no abstract methods in it?

Yes, there can be an abstract class without abstract methods.

31.What is Constructor?

•    A constructor is a special method whose task is to initialize the object of its class.
•    It is special because its name is the same as the class name.
•    They do not have return types, not even void and therefore they cannot return values.
•    They cannot be inherited, though a derived class can call the base class constructor.
•    Constructor is invoked whenever an object of its associated class is created.

32.How does the Java default constructor be provided?

If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.

33.Can constructor be inherited?

No, constructor cannot be inherited, though a derived class can call the base class constructor.

34.What are the differences between Contructors and Methods?

Constructors                                              Methods

Purpose               Create an instance of a class                    Group Java statements


Modifiers            Cannot be abstract, final, native, static, or synchronized

Can be abstract, final, native, static, or synchronized


Return Type       No return type, not even void                  void or a valid return type

Name                   Same name as the class (first letter is      Any name except the class. Method

capitalized by convention) -- usually a noun

names begin with a lowercase letter by convention -- usually the name of an action



this                       Refers to another constructor in the same class. If used, it must be the first line of the constructor

Refers to an instance of the owning class. Cannot be used by static methods.



super                    Calls the constructor of the parent class. If used, must be the first line of the constructor

Calls an overridden method in the parent class


Inheritance         Constructors are not inherited                 Methods are inherited


35.How are this() and super() used with constructors?

Constructors use this to refer to another constructor in the same class with a different parameter list.
•    Constructors use super to invoke the superclass's constructor. If a constructor uses super,
it must use it in the first line; otherwise, the compiler will complain.

36.What are the differences between Class Methods and Instance Methods?

Class Methods

Class methods are methods which are declared as static. The method can be called without creating an instance of the class

Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.

Class methods are methods which are declared as static. The method can be called without creating an instance of the class.


37.What are Access Specifiers?

One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..

39.What are Access Specifiers available in Java?

Java offers four access specifiers, listed below in decreasing accessibility:

•    Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
protected


yes


no, unless it is a subclass
private


no


no
public


yes


yes
Situation

Accessible to class from same package?

Accessible to class
from different package?
default


yes


no







40.What is final modifier?

The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.

•    final Classes- A final class cannot have subclasses.
•    final Variables- A final variable cannot be changed once it is initialized.
•    final Methods- A final method cannot be overridden by subclasses.

41.What are the uses of final method?

There are two reasons for marking a method as final:

•    Disallowing subclasses to change the meaning of the method.
     Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

42.What is static block?

Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.

43.What are static variables?

Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.

static type  varIdentifier;

where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.

44.What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

45.What are static methods?

Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:

•    A static method can only call other static methods.
•    A static method must only access static data.
•    A static method cannot reference to the current object using keywords super or this.




46. Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?
The very first class is especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.

CLASS LOADER reloadable? Explanation
Bootstrap
(primordial) No Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar) rt.jarcontains all of the compiled class files for the base Java Runtime environment.
Extensions No Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
System No Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line
options)


Q.  What do you need to do to run a class with a main() method in a package?

 Say,  you  have  a  class  named  “Pet”  in  a  project  folder  “c:\myProject”  and  package  named com.xyz.client, will you be able to compile and run it as it is?

package com.xyz.client;

public class Pet {
public static void main(String[] args) { System.out.println("I am found in the classpath");
}
}

To run   c:\myProject> java com.xyz.client.Pet

The answer is no and you will get the following exception: “Exception in thread "main" java.lang.- NoClassDefFoundError: com/xyz/client/Pet”. You need to set the classpath. How can you do that? One of the following ways:

1. Set the operating system CLASSPATH environment variable to have the project folder “c:\myProject”. [Shown in the above diagram as the System –classpath class loader]
2.    Set the operating system CLASSPATH environment variable to have a jar file “c:/myProject/client.jar”, which
has the Pet.class file in it. [Shown in the above diagram as the System –classpath class loader].
3.    Run it with –cp or –classpath option as shown below:

c:\>java –cp c:/myProject com.xyz.client.Pet
OR
c:\>java -classpath c:/myProject/client.jar com.xyz.client.Pet

Q. Explain static vs. dynamic class loading?


Q. What are “static initializers” or “static blocks with no function names”? When a class is loaded, all blocks that are  declared static and don’t have function name (i.e. static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields. CO

public class StaticInitializer {
public static final int A = 5;
public static final int B; //note that it is not   public static final int B = null;
//note that since B is final, it can be initialized only once.

//Static initializer block, which is executed only once when the class is loaded.

static {
if(A == 5) B = 10;
else
B = 5;
}

public StaticInitializer(){} //constructor is called only after static initializer block
}

The following code gives an Output of A=5, B=10.

public class Test {
System.out.println("A =" + StaticInitializer.A + ", B =" + StaticInitializer.B);
}

47. How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between composition and aggregation?
  The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for

Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses
extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a
Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.















Q. Which one to favor, composition or inheritance? The guide is that inheritance should be only used when
subclass ‘is a’ superclass.

Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse. Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the superclass is modified.

Do not  use inheritance just to get polymorphism. If there is no ‘is a’  relationship and all you  want is polymorphism then use interface inheritance with composition, which gives you code reuse (Refer Q10 in Java section for interface inheritance).

What is the difference between aggregation and composition?











47 What is design by contract? Explain the assertion construct?
A 11: Design by contract specifies the obligation(duty) of a calling-method and called-method to each other. Design by contract is a valuable technique, which should be used to build well-defined interfaces.   The strength of this programming methodology is that it gets the programmer to think clearly about what a function does, what pre and post conditions it must adhere to and also it provides documentation for the caller. Java uses the assert statement to implement pre- and post-conditions. Java’s exceptions handling also support design by contract especially checked exceptions (Refer Q39 in Java section for checked exceptions). In design by contract in addition to specifying programming code to carrying out intended operations of a method the programmer also specifies:


1. Preconditions – This is the part of the contract the calling-method must agree to. Preconditions specify the conditions that must be true before a called method can execute. Preconditions involve the system state and the arguments passed into the method at the time of its invocation. If a precondition fails then there is a bug in the calling-method or calling software component.

On public methods On non-public methods
Preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. You should not use assertion to check the parameters of the public methods but can use for the non-public methods. Assert is inappropriate because the method guarantees that it will always enforce the argument checks. It  must check its  arguments whether or  not assertions are enabled. Further, assert construct does not throw an exception of a specified type. It can throw only an AssertionError.

public void setRate(int rate) {
if(rate <= 0 || rate > MAX_RATE){
throw new IllegalArgumentException(“Invalid rate  ” + rate);
}
setCalculatedRate(rate);
} You can use assertion to check the parameters of the non-public methods.

private void setCalculatedRate(int rate) {
assert (rate > 0 && rate < MAX_RATE) : rate;
//calculate the rate and set it.
}

Assertions can be disabled, so programs must not assume that assert construct will be always executed:

//Wrong:
//if assertion is disabled, “pilotJob” never gets removed
assert jobsAd.remove(pilotJob);

//Correct:
boolean pilotJobRemoved = jobsAd.remove(pilotJob);
assert pilotJobRemoved;

2. Postconditions – This is the part of the contract the called-method agrees to. What must be true after a method completes successfully.   Postconditions can be used  with assertions in both public  and non-public methods. The postconditions involve the old system state, the new system state, the method arguments and the method’s return value. If a postcondition fails then there is a bug in the called-method or called software component.

public double calcRate(int rate) {
if(rate <= 0 || rate > MAX_RATE){
throw new IllegalArgumentException(“Invalid rate !!! ”);
}

//logic to calculate the rate and set it goes here

assert this.evaluate(result) < 0 : this; //message sent to AssertionError on failure return result;
}

3. Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method completes. If an invariant fails then there could be a bug in either calling-method or called-method. There is no particular mechanism for checking invariants but it is convenient to combine all the expressions required for checking invariants into a single internal method that can be called by assertions. For example if you have a class, which deals with negative integers then you define the isNegative() convenient internal method:

class NegativeInteger {
Integer value = new Integer (-1); //invariant

//constructor
public NegativeInteger(Integer int) {
//constructor logic goes here
assert isNegative();
}

// rest of the public and non-public methods goes here. public methods should call
// assert isNegative(); prior to its return

// convenient internal method for checking invariants.
// Returns true if the integer value is negative

private boolean isNegative(){
return value.intValue() < 0 ;
}
}


The  isNegative() method should be true  before  and  after any  method completes,  each  public  method  and constructor should contain the following assert statement immediately prior to its return.

assert isNegative();

Explain the assertion construct? The assertion statements have two forms as shown below:

assert Expression1;
assert Expression1 : Expression2;

Where:
Expression1  is a boolean expression. If the Expression1 evaluates to false, it throws an AssertionError without any detailed message.
       Expression2  if the Expression1 evaluates to false throws an AssertionError with using the value of the Expression2 as
the error’s detailed message.

Note:   If you are using assertions (available from JDK1.4 onwards), you should supply the JVM argument to enable it by package name or class name.

java -ea[:packagename...|:classname] or java -enableassertions[:packagename...|:classname]
java –ea:Account

Q. When to use an abstract class?: In case where you want to use implementation inheritance then it is usually  provided by an abstract  base class.  Abstract  classes are  excellent  candidates inside of  application frameworks. Abstract classes let you define some default behavior and force subclasses to provide any specific behavior. Care should be taken not to overuse implementation inheritance as discussed in Q10 in Java section.

Q. When to use an interface?: For polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract.  CO  Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition. For example: The Spring framework’s dependency injection promotes code to an interface principle. Another justification for using interfaces is that they solve the ‘diamond problem’ of traditional multiple inheritance as shown in the figure. Java does not support multiple inheritance. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by this ‘diamond problem’.



48 What is the main difference between pass-by-reference and pass-by-value?
Other languages use pass-by-reference or pass-by-pointer. But in Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (i.e. copy-by-value) works.
If your method call involves inter-process (e.g. between two JVMs) communication, then the reference of the calling method has a different address space to the called method sitting in a separate process (i.e. separate JVM). Hence inter-process communication involves calling method passing objects as arguments to called method
by-value in a serialized form, which can adversely affect performance due to marshaling and unmarshaling cost.