Monday, 16 November 2015

How to check wheather file exists

checking the code
        String filename = "test01.xml";
        URL url = getClass().getResource(filename);

        File file = new File(url.toURI());
        log.info("File exists: {}", file.exists());

Monday, 26 October 2015

All about CMS - Content Management System


Joomla is estimated to be the second most used content management system on the Internet, after WordPress.

The Google's product Blogger is also treated as CMS, since it gives a way to people to maintain their content of interest. It offers customizable dashboard where people can manage their content as their wish.

There are many content management systems out there in the market. Wordpress, Joomla and Blogger are amongst the most populous CMS tools.
 

Thursday, 15 October 2015

java command execution


java -cp . com.bt.noas.sipt.App
java -cp rhino-profiles-1.0-SNAPSHOT.jar com.bt.noas.sipt.App
java -cp . -jar jarfilename.jar com.bt.noas.sipt.App

Thursday, 1 October 2015

Jenkins

Key highlights of Jenkins:

  • Jenkins is a Continuous Integration Tool, which triggers the SCM to download your code from the code repository.
  • Builds your application.
  • Runs the unit test cases.
  • Triggers deployment of your application.
  • Once your application got deployed you can fire all your functional test cases as Junit test cases to ensure the regression is smooth.


http://www.itisopen.net/2013/08/Installing_jenkins_on_CentOS_6.4/ ==CentOS installation Jenkins


Monday, 28 September 2015

Save it

 Many developer thinks to include their classes inside rt.jar to solve classpath related problems, but that is a bad idea. You should never be messing with rt.jar, it contains class files which is trusted by JVM and loaded without stringent security check it does for other class files.

 Modulo/reminder(%)

 is used to calculate reminder.
 is used to calculate last digit.
 is used to calculate even/odd number.


 String binaryString = Integer.toBinaryString(number)
String octalString = Integer.toOctalString(number);
String hexString = Integer.toHexString(number);
binaryString = Integer.toString(number,2);
octalString = Integer.toString(number,8);
hexString = Integer.toString(number,16);

public static int binaryToDecimal(int number) {
        int decimal = 0;
        int binary = number;
        int power = 0;

        while (binary != 0) {
            int lastDigit = binary % 10;
            decimal += lastDigit * Math.pow(2, power);
            power++;
            binary = binary / 10;
        }
        return decimal;
    }


public static int reverse(int number){
        int reverse = 0;
        int remainder = 0;
        do{
            remainder = number%10;
            reverse = reverse*10 + remainder;
            number = number/10;
         
        }while(number > 0);
     
        return reverse;
    }

How Substring can cause memory leak in Java,
Why String is immutable in Java
Storing password in character array clearly mitigates security risk of stealing password.

Integer.parseInt() method will throw NumberFormatException if String provided is not a proper number.

StringBuilder - 1.5

Friday, 25 September 2015

EXCEL TIPS


HIDE AND UNHIDE COMMAND
Why do we need to know this?

Allows us to hide and unhide particular rows or columns.

Simplifies working with the spreadsheet.

Prevent certain information from being seen.
How do we use this feature?

Select the row(s) or column(s) to be hidden / unhidden.

Select Format : Row : Hide/Unhide or Format : Column : Hide/Unhide
MOVING AROUND A SPREADSHEET WITH CTRL, SHIFT, AND ARROW KEYS
Why do we need to know this?

Save lots of time.

Move the first or last cell of a contiguous data block without scrolling.
How do we use this feature?

Ctrl-Arrow : Move to the first/last data cell in the arrow direction.

Ctrl-Shift-Arrow: Selects the cells between the current cell and the first/last data cell.
NAME CELLS/RANGES
Why do we need to know this?

Allows specific cells or cell ranges to be referred to by name.

Allows us to write equations such as = Quantity*Cost instead of =$B$12*$C$4
How do we use this feature?

Select the cell or cell range.

Select Insert: Name: Define from the menu bar.
SORT COMMAND
Why do we need to know this?

Correctly sorting a series of rows or columns without disassociating the data is critical to many modeling efforts.
How do we use this feature?

To sort by single category, just click into column, NEVER highlight column (would destroy table integrity)

To use multiple criteria, click any cell of data table, select Data…Sort

Data table will be selected.

Indicate if have Header row, which will not be included in sort

Select Options to use Custom lists (create first)

Select Tools/Options/Custom Lists to create specialized sort orders, e.g.

To sort months and weekdays according to their calendar order instead of their alphabetic order

To rearrange lists in a specific order (such as High/Medium/Low entries)
TOGGLING AMONG RELATIONAL AND ABSOLUTE REFERENCES
Why do we need to know this?

Saves lots of time.
How do we use this feature?

F4 key toggles through the different options.
FILL DOWN AND FILL RIGHT COMMANDS
Why do we need to know this?

Saves lots of time.

Allows for copying of cell content to contiguous cells with a single keystroke.
How do we use this feature?

Select the cell with the content to be copied and drag to select the cells to which the content should be copied.

Ctrl-R to fill right.

Ctrl-D to fill down.

Double-check the formulas for absolute vs. relative references.
IF FUNCTION
Why do we need to know this?

Conditional comparisons are used in virtually all spreadsheets.

Knowing how to use IF in a nested manner and in combination with other functions will save hours of time.
How do we use this feature?

IF(Comparison,TrueAction,FalseAction)

IF(Comparison,TrueAction,) ==> Cell shows 0 if condition is false.

IF(Comparison,TrueAction,””) ==> Cell shows blank if condition is false.
AND AND OR FUNCTIONS
Why do we need to know this?

Used with the IF function to enable more complicated logical comparisons.
How do we use this feature?

AND(Comparison 1,Comparison2,Comparison3,…)

OR(Comparison 1,Comparison2,Comparison3,…)
SUM AND SUMIF FUNCTIONS
Why do we need to know this?

SUM is used in virtually all spreadsheets

SUMIF can save lots of time in most spreadsheets if we know how to use the function.
How do we use this feature?

SUM (Range1, Range2, Value1,…)

SUMIF(Range,”Comparison”,SumRange)

If a SumRange IS NOT specified, SUMIF sums the cells meeting the Comparison criteria in the specified Range

If a SumRange IS specified, SUMIF sums the cells in SumRange where the corresponding cells in Range meets the Comparison criteria
NOTE: The “” signs must be used for the Comparison value
SUBTOTALS AND TOTALS
Why do we need to know this?

Want to add lines with subtotals in our P&L or balance sheet, but still need to run the total over all numbers? Don’t want to get confused with nested subtotals and totals in your spreadsheet?
How do we use this feature?

Instead of ‘=sum(range)’ add ‘=subtotal(9,range)’ where you need a subtotal or total.

We may nest this function as we like. Excel keeps track of everything
SUMPRODUCT FUNCTION
Why do we need to know this?

If we need to multiply two columns and need the sum of the multiplication, sumproduct comes easy.
How do we use this feature?

Insert =sumproduct(range1,range2)
NPV FUNCTION
Why do we need to know this?

We can create our own discounting table and then calculate the NPV of our cash flow series or just use the NPV function
How do we use this feature?

Insert =NPV(discount rate,cash flow numbers,...)

The discount rate is in percent

The cash flow numbers are either an array or individual numbers in individual cells

Attention: The first cash flow number is in period 1, e.g. the end of the period. If we have for example an initial investment in period 0, just type =NPV(…)+period 0 payment in our calculation
COUNT FUNCTIONS
Why do we need to know this?

Prevents us from wasting time counting items manually or creating dummy variables to count such items
How do we use this feature?

COUNT(Range1,Range2,Value1,...) ==> count the number of cells containing numbers

COUNTA(Range1,Range2,Value1,...) ==> count the number of non-empty cells

COUNTBLANK(Range) ==> count the number of empty cells in the range

COUNTIF(Range,”Criteria”) ==> count the number of cells in the Range containing the Criteria.
NOTE: The “” signs must be used for the Criteria value
ROUND, ROUNDUP AND ROUNDDOWN FUNCTIONS
Why do we need to know this?

Many situations exist when we need to have exact numbers instead of various fractions in our calculations (e.g., there cannot be 536.235 bank branches)
How do we use this feature?

ROUND(Number,Digits) ==> Round the number (or cell) to the specified number of digits

If Digit = 0, then Number is rounded to nearest integer

If Digit > 0, then Number is rounded to the specified number of decimal places

If Digit < 0, then Number is rounded to the specified number of digits left of the decimal place

ROUNDDOWN(Number,Digits) and ROUNDUP(Number,Digits) work the same way as ROUND, but the direction of rounding is specified by the function
VLOOKUP AND HLOOKUP FUNCTIONS
Why do we need to know this?

Allows us to automatically lookup a particular cell of data from a larger data range. This is especially useful when we have

A large data section that contains information for multiple records somewhere on the spreadsheet (e.g., a small database)

A calculation area somewhere else, and we need to refer to some specific data elements for specific records.
How do we use this feature?

VLOOKUP and HLOOKUP allows us to find a specific cell of data in a larger data range.

Use VLOOKUP when each row contains a separate record and the associated columns contain data for that one record

Use HLOOKUP when each column contains a separate record

VLOOKUP(SearchValue,Range,ColumnNumber,Error) ==> look for a value in the row specified by SearchValue and the column specified by ColumnNumber

SearchValue indicates the “match key” (i.e., find the row that contains the SearchValue in the first column)

Range specifies the cells containing the data

ColumnNumber specifies the column that contains the data element you want

Error determines what happens when Excel does not find the exact SearchValue you want. FALSE leads Excel to display a #N/A when an exact match cannot be found. TRUE leads Excel to display the next smaller value than SearchValue

HLOOKUP(SearchValue,Range,RowNumber,Error) ==> look for a value in the column specified by SearchValue and the row specified by RowNumber.
NOTE: The 1st column of data must be sorted in ascending order when using VLOOKUP, and the 1st row of data must be sorted if using HLOOKUP
INSERT FUNCTION COMMAND
Why do we need to know this?

What do we do if we do not know what functions are available or how to enter the arguments for a function?
How do we use this feature?

Select the cell

Select Insert : Function from the menu bar
PASTE SPECIAL COMMAND
Why do we need to know this?

Saves lots of time

Retyping formulas

Converts formulas into values

Reformatting cells

Transposing cells (i.e., convert row-entered data blocks into column-entered ones
How do we use this feature?

Copy the cells of interest

Place the cursor where we want to past the information

Select Edit : Paste Special from the menu bar

Select the appropriate options from the dialog box that appears
AUDITING FEATURES
Why do we need to know this?

Quickly find the cells referenced by a formula and/or quickly find which cells reference a particular cell of interest
How do we use this feature?

Select View : Toolbars : Customize from the menu bar. Check the Auditing box from the Toolbars tab

Click on the cell of interest

Select the Trace Precedents or Trace Dependents icon from the Auditing Toolbar
SPLIT WINDOWS AND FREEZE PANES
Why do we need to know this?

Splitting a window allows us to work on multiple parts of a large spreadsheet simultaneously.

Freezing the pane allows us to always keep one part of the spreadsheet (e.g., column or row labels) visible.
How do we use this feature?

Drag the split horizontal and split vertical icons to the desires positions

Click on the freeze pane icon from the tool bar to freeze the panes.
GOAL SEEK ADD-IN
Why do we need to know this?

Easily find what one input variable needs to be to achieve some desired result in a calculation
How do we use this feature?

Select the calculated cell

Select Tools : Goal Seek from the menu bar

Enter the desired resulting calculation into the “To Value” form in the dialog that appears

Enter the input cell in the “By changing cell:” form
SOLVER ADD-IN
Why do we need to know this?

Allows us to use linear programming to find the optimal inputs to achieve some desired calculation result (e.g., maximize revenues by increasing daily tickets, increasing store size, average sale/ticket, etc. simultaneously)

Use Solver instead of Goal Seek when:

We need to place constraints on the input variable (e.g., cannot open a store for more than 24 hours a day)

More than 1 input variables are involved

We want to minimize or maximize the resulting calculation in addition to just setting the calculation to a predetermined value
How do we use this feature?

Select the final calculated cell, then select Tools : Solver from the menu bar

Select what we want to do from the “Equal to” section (i.e., maximize, minimize, or set to a specific value)

Reference the input cells (note, separate cells by using a comma or “:” if cells are contiguous.

If the input values have constraints, click on Add to enter the constraints

Click on Solve
DATA TABLES COMMAND
Why do we need to know this?

Simplest way to run sensitivity analyses
How do we use this feature?

Input the values which we want to test for a particular variable on separate rows (e.g., A6:A13)

In the cell above and to the right of the first sensitivity value, reference the final result of your calculations (e.g., A5 = C3)

Select the cells containing the calculation and input variables (e.g., A5:B13)

Select Data : Tables from the menu bar

Input the cell referenced by the formula in the “Column input cell” (e.g., A2). This example uses in “Column input cell” because the value to test in the sensitivity analysis are arranged in a single column
SCENARIOS ADD-IN
Why do we need to know this?

If we have created a model and need to run various scenarios. Then use the scenario function under the tools menu. Keeps our inputs and outputs from the model nicely together
How do we use this feature?

Assign names to the excel cells that act as input parameters for our model

Start the scenario function by selecting Tools: Scenarios from the menu bar.

Click Add to enter our first scenario

Create a name

Select ALL cells that will be our input to the model.

Assign the desired scenario value to each input parameter.

Add more scenarios as needed

When finished click on summary and select scenario summary (the pivot table is not so helpful)
PIVOT TABLES
Why do we need to know this?

Most powerful tool to arrange huge amounts of data in a more structured way than pure sorting. In particular helpful to run quick sums, averages, distributions, etc. in combination with a structure criteria, e.g. total number and average sales per store size band
How do we use this feature?

Select Data: PivotTable Report…
o
Step 1: Microsoft Excel list
o
Step 2: Select the relevant data area
o
Step 3: Drag and drop data elements on row and column (this is your table structure), the data you want to analyze on the data area
o
Step 4: Just press Finish
PROTECTING CELLS AND WORKSHEETS
Why do we need to know this?

Sometimes we want to give our Excel file to someone else and prevent them from changing the formulas for seeing some hidden cells
How do we use this feature?

Protecting a spreadsheet or workbook involves two steps
o
Designating which cells to be locked or hidden
o
Protecting the spreadsheet or workbook

Note several weird peculiarities:
o
The default for all cells in a spreadsheet if LOCKED. So if you want the receiver of your worksheet to change the content of a cell, unlock the cell before protecting the spreadsheet
o
The formulas in a cell can be seen even if the spreadsheet is lock -- UNLESS you hide that cell before protecting the spreadsheet

To lock/unlock and hide/unhide a cell, select the cell(s) and select Format: Cell. Select the Protection tab when the dialog box appears

To protect/unprotect a spreadsheet, select Tools : Protection : Protect Sheet
EDITING MULTIPLE WORKSHEETS SIMULTANEOUSLY
Why do we need to know this?

Avoid having to redo our work on multiple spreadsheets in a single workbook
How do we use this feature?

Select the first spreadsheet to be edited

Hold the Ctrl key while clicking on the additional spreadsheets

Do our editing
CONDITIONAL FORMATTING
Why do we need to know this?

Sometimes we would to color the output of cells in different colors, e.g. negative numbers in red, positive numbers in black, or add a frame, etc.
How do we use this feature?

Mark the relevant fields and select Format: Conditional Formatting

Select the criteria for the format and adjust the format. We can actually change the font, the border and the color

Click on Add to select additional criteria for the formatting
AUTOFILTER COMMAND
Why do we need to know this?

We have a huge pile of data and quickly want to find some specific information, e.g. all sets that meet criteria or the top 10 items etc.
How do we use this feature?

Click into our table or better mark the data area and select Data: Filter: Autofilter

Using the drop-down boxes per item allows us to display only specific filtered information

Selecting multiple matches (up to 3 maximum with autofilter) we can narrow down our search
OR

add our own criteria for filtering by clicking on the custom criteria
CUSTOMIZE TOOL BARS
Why do we need to know this?

How many icons on the tool bar to use regularly?

How often do we have to use the menu bar or mouse to do something we wish were accessible with a single click?
How do we use this feature?

Select View : Toolbars : Customize

Click on the Commands tab

Drag items on and off the toolbar as our wish
OR

Right click toolbar area
o
Select Customize
o
Select Commands tab in Customize dialog box
o
From appropriate menu, find the command for which we want to add button
o
Drag button to location on toolbar

Other favorites ...
o
Paste values
o
Select visible cells
o
Save as
o
Show comment (toggles it)
o
Set print area
o
Page setup
o
Merge cells
o
Auto filter
o
Paste values
CHANGING DEFAULT WORKBOOK
Why do we need to know this?

How often do we use the menu bar to change the normal font or number formats?

We can create the basic number and font formats you use regularly, save it as a template, and have Excel use that template every time we create a new workbook
How do we use this feature?

Create a workbook with the formatting we use regularly and save it under the name “Book” and Template format

Move the “Book” template to the Microsoft Office : Office : Xlstart folder
GROUP/UNGROUP PARTS OF SPREADSHEETS
Why do we need to know this?

How often would we like to hide or unhide parts of a complex spreadsheet?

If answer is “very often”. We will like to group/ungroup function instead of the hide/unhide command, since we will be able to toggle between hidden or displayed columns or rows.
How do we use this feature?

Mark the row or column that we would like to “fold”, i.e. hide for the moment.

Click on Data: Group and Outline: Group

To “fold” click now on the “minus” sign outside of our column or row

We may also group or ungroup hierarchically
SWITCH OFF THE MICROSOFT ACTORS
Why do we need to know this?

Also find the Microsoft Actors more disturbing than helpful?

Always popping up at the wrong moment
How do we use this feature?

Excel 97
o
Start the Windows Explorer
o
Go to the directory Program Files: Microsoft Office: Office: Actors
o
Rename the directory “Actors” to “Dead Actors”

Excel 2000
o
Go to Tools : Options : Edit and switch off „Provide feedback with animation“
CLEAN UP TEXT
Why do we need to know this?

Often clients have data on their mainframe. The best we can get for our PC is a text file dump. This trick will help us see through the data „mess“ we‘ve received.
How do we use this feature?

One easy method to split text into separate columns is the Data/Text to Column Wizard
o
Select the cells
o
Select Data/Text to Column

Check that Excel choose correct setting, change as needed

Be sure to supply the destination

Click finish
NOTE:
Be sure that enough empty columns for our conversion at the destination or Excel will OVERWRITE the contents of the cells
Split data appears in 2 columns.

Tuesday, 15 September 2015

Subversion


History for the application can't be tracked with trunk when we are dealing with multiple version of code , whereas in branch the history tracking 'll be more easy. 

Sunday, 30 August 2015

Iterate over HashMap

Best way to Iterate over HashMap in Java

Here is the code example of Iterating over any Map class in Java e.g. Hashtable or LinkedHashMap. Though I have used HashMap for iteration purpose, you can apply same technique to other Map implementations. Since we are only using methods from java.uti.Map interface, solution is extensible to all kinds of Map in Java. We will use Java 1.5 foreach loop and Iterating over each Map.Entry object, which we get by calling Map.entrySet() method. Remember to use Generics, to avoid type casting. Use of Generics and foreach loop result in very concise and elegant code, as shown below.


for(Map.Entry<Integer, String> entry : map.entrySet()){
    System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
}

This code snippet is very handy for iterating HashMap, but has just one drawback, you can not remove entries without risking ConcurrentModificationException. In next section, we will see code using Iterator, which can help you for removal of entries from Map.



Removing Entries from Map in Java

One reason for iterating over Map is removing selected key value pairs from Map. This is a general Map requirement and holds true for any kind of Map e.g. HashMap, Hashtable, LinkedHashMap or even relatively new ConcurrentHashMap. When we use foreach loop, it internally translated into Iterator code, but without explicit handle to Iterator, we just can not remove entries during Iteration. If you do,  your Iterator may throw ConcurrentModificationException. To avoid this, we need to use explicit Iterator and while loop for traversal. We will still use entrySet() for performance reason, but we will use Iterator's remove() method for deleting entries from Map. Here code example  to remove key values from HashMap in Java:



  //code goes here
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
   Map.Entry<Integer, String> entry = iterator.next();
   System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
   iterator.remove(); // right way to remove entries from Map,
                      // avoids ConcurrentModificationException
}


You can see, we are using remove() method from Iterator and not from java.util.Map, which accepts a key object. This code is safe from ConcurrentModificationException.


Read more: http://java67.blogspot.com/2013/08/best-way-to-iterate-over-each-entry-in.html#ixzz3kIiWUMZU

Sorting ArryList in java

Sorting ArrayList in Java is not difficult, by using Collections.sort() method you can sort ArrayList in ascending and descending order in Java. Collections.sort() method optionally accept a Comparator and if provided it uses Comparator's compare method to compare Objects stored in Collection to compare with each other, in case of no explicit Comparator, Comparable interface's compareTo() method is used to compare objects from each other. If object's stored in ArrayList doesn't implements Comparable than they can not be sorted using Collections.sort() method in Java.


Sorting ArrayList in Java – Code Example

ArrayList Sorting Example in Java - Ascending Descending Order Code
Here is a complete code example of How to sort ArrayList in Java, In this Sorting we have used Comparable method of String for sorting String on their natural order, You can also use Comparator in place of Comparable to sort String on any other order than natural ordering e.g. in reverse order by using Collections.reverseOrder() or in case insensitive order by using String.CASE_INSENSITIVE_COMPARATOR.

public class CollectionTest {

   
    public static void main(String args[]) {
   
        //Creating and populating ArrayList in Java for Sorting
        ArrayList<String> unsortedList = new ArrayList<String>();
       
        unsortedList.add("Java");
        unsortedList.add("C++");
        unsortedList.add("J2EE");
       
        System.err.println("unsorted ArrayList in Java : " + unsortedList);
       
        //Sorting ArrayList in ascending Order in Java
        Collections.sort(unsortedList);
        System.out.println("Sorted ArrayList in Java - Ascending order : " + unsortedList);
       
        //Sorting ArrayList in descending order in Java
        Collections.sort(unsortedList, Collections.reverseOrder());
        System.err.println("Sorted ArrayList in Java - Descending order : " + unsortedList);
    }
}

Iterator vs Enumerator

Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0, while iterator was introduced later. Iterator can be used with ArrayList, HashSet and other collection classes.  Another similarity between Iterator and Enumeration in Java is that  functionality of Enumeration interface is duplicated by the Iterator interface.

Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:

Enumeration
hasMoreElement()
nextElement()
N/A


Iterator
hasNext()
next()
remove()

So Enumeration is used when ever we want to make Collection objects as Read-only.

Thursday, 27 August 2015

Maven Failsafe plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.17</version>
    <executions>
        <execution>
            <id>integration-test</id>
            <goals>
                <goal>integration-test</goal>
            </goals>
            <configuration>
                <includes>
                    <include>**/it/SIPTResourceTestSuite.java,**/it/SIPTResourceTest.java</include>
                </includes>
            </configuration>
        </execution>
        <execution>
            <id>verify</id>
            <goals>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Maven Surefire plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.17</version>
    <configuration>
        <includes>
            <include>**/ut/ProvTestSuite.java, **/ut/*Test.java</include>
                </includes>
    </configuration>
</plugin>

Cargo Maven2 plugin

<plugin>
    <groupId>org.codehaus.cargo</groupId>
    <artifactId>cargo-maven2-plugin</artifactId>
    <version>1.4.10</version>
    <configuration>
        <container>
<containerId>jetty9x</containerId>
<type>remote</type>
        </container>
        <configuration>
<type>runtime</type>
<properties>
<cargo.runtime.args>force=true</cargo.runtime.args>
                <cargo.hostname>localhost</cargo.hostname>
                <cargo.servlet.port>${servlet.port}</cargo.servlet.port>
                <cargo.remote.username>admin</cargo.remote.username>
                <cargo.remote.password>admin</cargo.remote.password>                      
            </properties>
        </configuration>
        <deployables>
            <deployable>
                <groupId>${project.groupId}</groupId>
                <artifactId>${project.artifactId}</artifactId>
                <properties>
                    <context>/sipt-rs</context>
                    </properties>
                        <pingTimeout>300000</pingTimeout>
            </deployable>
        </deployables>
    </configuration>
    <executions>
        <execution>
            <id>redeploy-war-with-cargo</id>
            <phase>pre-integration-test</phase>
            <goals>
                <goal>deployer-redeploy</goal>
            </goals>
        </execution>
    </executions>
</plugin>



The above plug-in look for the cargo-jetty-7-and-onwards-deployer-1.4.11.war in side jetty/web-apps  folder and before that it identifies the jetty running on the specified host and port , later the binding with plug in and jetty happens via cargo war.

Once the binding is over, plug in will deploy the application war into the identified jetty. Later you can run the web/rest test cases from your java module.

Maven war plugin


<plugin>

         <artifactId>maven-war-plugin</artifactId>
          <version>2.5</version>

         <configuration>
                <warName>sipt-rest</warName>
          </configuration>

 </plugin>

Friday, 21 August 2015

Maven jar plugin

<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<!-- <addClasspath>true</addClasspath> -->
<!-- <classpathPrefix>lib/</classpathPrefix> -->
<mainClass>com.bt.noas.sipt.exportprofiles.ProfileExporter</mainClass>
</manifest>
</archive>
</configuration>
</plugin>

Thursday, 20 August 2015

SQL interview questions

How do you change the value for gender field in a table from Male to Female and vice versa.

update employees set gender = case gender when 'Male' then 'Female' when 'Female' then 'Male'     else 'Other' end

Monday, 10 August 2015

volatile Keyword in Java

In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

public class Foo extends Thread {
    private volatile boolean close = false;
    public void run() {
        while(!close) {
            // do work
        }
    }
    public void close() {
        close = true;
        // interrupt here if needed
    }
}


sleep() vs wait()

Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions.

Thread.UncaughtExceptionHandler

This can be done using Thread.UncaughtExceptionHandler.

Here’s a simple example:

// create our uncaught exception handler
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};

// create another thread
Thread otherThread = new Thread() {
    public void run() {
        System.out.println("Sleeping ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }
};

// set our uncaught exception handler as the one to be used when the new thread
// throws an uncaught exception
otherThread.setUncaughtExceptionHandler(handler);

// start the other thread - our uncaught exception handler will be invoked when
// the other thread throws an uncaught exception
otherThread.start();

Java Interview Questions - 2

Q: Is abstract keyword allowed for interface declaration ?
A: Yes, it is allowed. (static,final are not allowed)

Only public,abstract are permitted.

public abstract interface InterfaceTest {

} //perfect

Note: 
  • public,private,protected,default,static and abstract keywords are allowed for an interface declared inside a class.

Q: What are allowed types for a class ?
A: Only public,abstract,final,default(nothing) is allowed for outer class declarations.

Note: 
  • An inner class can be declared as public,private,protected,default,static,final and abstract.
  • Only either of final , abstract are allowed for inner class declaration.

Q: How do you find odd numbers in 1 to 100 ?

Q: How do you reverse a list ?

Q: How do you fetch data from multiple databases and merge and sort them in java ?

Q: What happens if hashcode produces same value in collections ?

Q: Query find duplicate entries in table ?
  • SELECT firstname, lastname, list.address FROM list INNER JOIN (SELECT address FROM list GROUP BY address HAVING count(id) > 1) dup ON list.address = dup.address
  • SELECT address, count(id) as cnt FROM list GROUP BY address HAVING cnt > 1

ThreadLocal Class

java.lang
Class ThreadLocal<T>

java.lang.Object
java.lang.ThreadLocal<T>
Direct Known Subclasses:
InheritableThreadLocal

public class ThreadLocal<T>
extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Since:
1.2

Strings vs character array


In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you're done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.

In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method,  It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality.

ArrayList vs LinkedList vs Vector

ArrayList, LinkedList, and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.
View the answer ?


Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC.

fail-fast vs fail-safe


The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.

Examples:

public class FailFastExample
{
   
    public static void main(String[] args)
    {
        Map<String,String> premiumPhone = new HashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
       
        Iterator iterator = premiumPhone.keySet().iterator();
       
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
    }
}

public class FailSafeExample
{
    public static void main(String[] args)
    {
        ConcurrentHashMap<String,String> premiumPhone =
                               new ConcurrentHashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
       
        Iterator iterator = premiumPhone.keySet().iterator();
       
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
   
   }
 

}

Sunday, 9 August 2015

Object class

public class Object
{

    public Object()
    {
    }

    private static native void registerNatives();

    public final native Class getClass();

    public native int hashCode();

    public boolean equals(Object obj)
    {
        return this == obj;
    }

    protected native Object clone()
        throws CloneNotSupportedException;

    public String toString()
    {
        return (new StringBuilder()).append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).toString();
    }

    public final native void notify();

    public final native void notifyAll();

    public final native void wait(long l)
        throws InterruptedException;

    public final void wait(long l, int i)
        throws InterruptedException
    {
        if(l < 0L)
            throw new IllegalArgumentException("timeout value is negative");
        if(i < 0 || i > 999999)
            throw new IllegalArgumentException("nanosecond timeout value out of range");
        if(i >= 500000 || i != 0 && l == 0L)
            l++;
        wait(l);
    }

    public final void wait()
        throws InterruptedException
    {
        wait(0L);
    }

    protected void finalize()
        throws Throwable
    {
    }

    static
    {
        registerNatives();
    }
}

Native methods

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI(Java Native Interface). It marks a method, that it will be implemented in other languages, not in Java. It works together with JNI (Java Native Interface).

Main.java:
public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:
#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Groovlets


public class GroovyServlet extends AbstractHttpServlet

This servlet will run Groovy scripts as Groovlets. Groovlets are scripts with these objects implicit in their scope:

request - the HttpServletRequest
response - the HttpServletResponse
application - the ServletContext associated with the servlet
session - the HttpSession associated with the HttpServletRequest
out - the PrintWriter associated with the ServletRequest

Your script sources can be placed either in your web application's normal web root (allows for subdirectories) or in /WEB-INF/groovy/* (also allows subdirectories).

To make your web application more groovy, you must add the GroovyServlet to your application's web.xml configuration using any mapping you like, so long as it follows the pattern *.* (more on this below). Here is the web.xml entry:

    <servlet>
      <servlet-name>Groovy</servlet-name>
      <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
      <servlet-name>Groovy</servlet-name>
      <url-pattern>*.groovy</url-pattern>
      <url-pattern>*.gdo</url-pattern>
    </servlet-mapping>

The URL pattern does not require the "*.groovy" mapping. You can, for example, make it more Struts-like but groovy by making your mapping "*.gdo".

Monday, 3 August 2015

JAX-RS Annotations


JAX-RS Annotations
Annotation
Description
@Path
The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted: for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example, you could ask for the name of a user and pass it to the application as a variable in the URI:/helloworld/{username}.
@GET
The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@POST
The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PUT
The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@DELETE
The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@HEAD
The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PathParam
The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
@QueryParam
The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
@Consumes
The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.
@Produces
The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client: for example, "text/plain".
@Provider
The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such asMessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReaderis used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return aResponse that wraps the entity and that can be built using Response.ResponseBuilder.

Maven - archetype:generate

Basic Maven project:

mvn archetype:generate -DgroupId=com.mycompany.app
 -DartifactId=my-app 
 -DarchetypeArtifactId=maven-archetype-quickstart
 -DinteractiveMode=false

Maven Web project:

mvn archetype:generate -DgroupId=com.mycompany.app 
 -DartifactId=RESTfulExample
 -DarchetypeArtifactId=maven-archetype-webapp
 -DinteractiveMode=false

mvn archetype:generate -DgroupId={project-packaging}
 -DartifactId={project-name}
 -DarchetypeArtifactId=maven-archetype-webapp
 -DinteractiveMode=false 

mvn archetype:generate -DgroupId=com.deegeu.dockerapp
 -DartifactId=dockerapp
 -DarchetypeArtifactId=maven-archetype-quickstart
 -DinteractiveMode=false 


Introduction to RESTful Web Services


RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.

The following principles encourage RESTful applications to be simple, lightweight, and fast:

Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery. See The @Path Annotation and URI Path Templates for more information.

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT creates a new resource, which can be then deleted by using DELETE. GET retrieves the current state of a resource in some representation. POST transfers a new state onto a resource. See Responding to HTTP Methods and Requests for more information.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. See Responding to HTTP Methods and Requests and Using Entity Providers to Map HTTP Response and Request Entity Bodies for more information.

Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction. See Using Entity Providers to Map HTTP Response and Request Entity Bodies and “Building URIs” in the JAX-RS Overview document for more information.

JAX-RS: Java API for RESTful Web Services (JAX-RS) is a Java
programming language API that provides support in creating
web services according to the Representational State
Transfer (REST) architectural pattern.[1] JAX-RS uses
annotations, introduced in Java SE 5, to simplify the
development and deployment of web service clients and
endpoints.

From version 1.1 on, JAX-RS is an official part of Java EE
6. A notable feature of being an official part of Java EE is
that no configuration is necessary to start using JAX-RS.
For non-Java EE 6 environments a (small) entry in the
web.xml deployment descriptor is required.

Implementations of JAX-RS include:
    Apache CXF, an open source Web service framework
    Jersey, the reference implementation from Sun (now
Oracle)
    RESTeasy, JBoss's implementation
    Restlet
    Apache Wink, Apache Software Foundation Incubator
project, the server module implements JAX-RS
    WebSphere Application Server from IBM:
        Version 7.0: via the "Feature Pack for
Communications Enabled Applications"
        Version 8.0 onwards: natively
    WebLogic Application Server from Oracle, see notes
    Apache Tuscany

Throw before return statement



  • The following code gives compilation error as return is unreachable when the throw is not handled.


public class TestThrow {
public static void main(String[] args) throws Exception {
throw new Exception();
return; //Unreacheble code
}
}


  • The following code is alright and the return is reachable with no compilation error as throw is handled.

public class TestThrow {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; // Now it's alright
}
}

Polymorphism works for static ??

No, polymorphism will not work at all for static methods. Method will be executed based on the type of the reference type not on the type of type of object pointed to.

Please find the example below.


public class StaticTest
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
       
        BaseClass bc = new SubClass();
        bc.method1();
    }
}


class BaseClass{

public static void method1(){

System.out.println("Base class");

}
}

class SubClass extends BaseClass{

public static void method1(){

System.out.println("Sub class");

}
}


Output:  Hello World!
                Base class

Tuesday, 28 July 2015

SingleTon Design Pattern


public class Runtime
{

    public static Runtime getRuntime()
    {
        return currentRuntime;
    }


    private Runtime()
    {
    }

    private static Runtime currentRuntime = new Runtime();

}

Friday, 24 July 2015

Generics

Generics in java were introduced as one of features in JDK 5.

generics sole purpose i.e. Type Safety.

Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. A class like LinkedList<E> is a generic type, that has a type parameter E . Instantiations, such as LinkedList<Integer> or a LinkedList<String>, are called parameterized types, and String and Integer are the respective actual type arguments.

If you closely look at java collection framework classes then you will observe that most classes take parameter/argument of type Object and return values from methods as Object. Now, in this form, they can take any java type as argument and return the same. They are essentially heterogeneous i.e. not of a particular similar type.

In original collection framework, having homogeneous collections was not possible without adding extra checks before adding some checks in code. Generics were introduced to remove this limitation to be very specific. They add this type checking of parameters in your code at compile time, automatically. This saves us writing a lot of unnecessary code which actually does not add any value in run-time, if written correctly.

Without this type safety, your code could have infected by various bugs which get revealed only in runtime. Using generics, makes them highlighted in compile time itself and make you code robust even before you get the bytecode of your java source code files.

In the heart of generics is “type safety“. What exactly is type safety? It’s just a guarantee by compiler that if correct Types are used in correct places then there should not be any ClassCastException in runtime.

Another important term in java generics is “type erasure“. It essentially means that all the extra information added using generics into source code will be removed from bytecode generated from it. Inside bytecode, it will be old java syntax which you will get if you don’t use generics at all. This necessarily helps in generating and executing code written prior java 5 when generics were not added in language.

Class Declarations

public class Throwable
  implements Serializable

public class IdentityHashMap extends AbstractMap
    implements Map, Serializable, Cloneable

public class File
    implements Serializable, Comparable

public class RandomAccessFile
    implements DataOutput, DataInput, Closeable

System Class In Java



The purpose of the System class is to provide access to system resources.

Runtime Class in Java



What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.

Thursday, 23 July 2015

Java Interview Questions - Section 1


How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What exception you get when you declare a class as private?
Illegal modifier for the class BaseClass; only public, abstract & final are permitted.

What is the List interface?
The List interface provides support for ordered collections of objects.

What is the Vector class?
The Vector class provides the capability to implement a growable array of objects

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.

What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.

If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

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.

If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

Is sizeof a keyword?
The sizeof operator is not a keyword.

What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.

Does garbage collection guarantee that a program will not run out of memory?
No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

What is a native method?
A native method is a method that is implemented in a language other than Java.

How can you write a loop indefinitely?
for(;;)--for loop; while(true)--always true, etc.

Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

What is a static method?
A static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.

What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.

What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

What is the difference between throw and throws keywords?
The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the mehtod, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.

Name primitive Java types.
The primitive types are byte, char, short, int, long, float, double, and boolean.

Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.

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.

What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.

How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.

How are this() and super() used with constructors? this() is used to invoke a constructor of the same class.
super() is used to invoke a superclass constructor.

How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

How the object oriented approach helps us keep complexity of software development under control?
We can discuss such issue from the following aspects: Objects allow procedures to be encapsulated with their data to reduce potential interference. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places. The well-defined separations of interface and implementation allows constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

What is polymorphism?
Polymorphism allows methods to be written that needn't be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of yet unconceived classes.

What is design by contract?
The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions. In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts