package org.code;
import java.util.Arrays;
import java.util.Random;
/**
* @author Purna
*
* this class just shuffles the given set of cards assuming there are 52
* cards 1-52
*/
public class CardsShuffler {
public static Random randomGenerator = new Random();
public static void main(String args[]) {
int[] cards = new int[5];
for (int index = 0; index < cards.length; index++) {
cards[index] = index + 1;
}
printCards(cards);
shuffleCards(cards);
}
/**
* shuffles the cards using
*
* Knuth Shuffle
*
* @param cards
*/
private static void shuffleCards(int[] cards) {
for (int index = 1; index < cards.length; index++) {
int cardToShuffleWith = randomGenerator.nextInt(index);
swapNumbers(cards, index, cardToShuffleWith);
// printing the cards on every shuffle
printCards(cards);
}
}
/**
* Swaps two Cards
*
* @param cards
* @param index
* @param cardToShuffleWith
*/
private static void swapNumbers(int[] cards, int index,
int cardToShuffleWith) {
int temp = cards[index];
cards[index] = cards[cardToShuffleWith];
cards[cardToShuffleWith] = temp;
}
/**
* prints the cards
*
* @param cards
*/
private static void printCards(int[] cards) {
System.out.println(Arrays.toString(cards));
}
}
Labels
Cards Shuffle Code in Java
Remove duplicate Characters without extra memory in java
/**
* Without using extra(large) memory Complexity O(n^2)
* @param word
*/
private static void removeDuplicates(char[] word) {
int currentIndex = 1;
for (int i = 0; i < word.length; i++) {
int j;
for (j = 0; j < currentIndex; j++) {
if (word[i] == word[j]) {
break;
}
}
if (currentIndex == j) {
word[currentIndex++] = word[i];
}
}
while (currentIndex < word.length) {
word[currentIndex++] = ' ';
}
}
Insertion Sort in Java
Before Sorting, Input :0 10 2 9 3 8 1 6 5 7 4 the first element is sorted here
0 10 2 9 3 8 1 6 5 7 4 first 2 elements are sorted
0 2 10 9 3 8 1 6 5 7 4 and so on….
0 2 9 10 3 8 1 6 5 7 4
0 2 3 9 10 8 1 6 5 7 4
0 2 3 8 9 10 1 6 5 7 4
0 1 2 3 8 9 10 6 5 7 4
0 1 2 3 6 8 9 10 5 7 4
0 1 2 3 5 6 8 9 10 7 4
0 1 2 3 5 6 7 8 9 10 4
0 1 2 3 4 5 6 7 8 9 10
After Sorting, output :0 1 2 3 4 5 6 7 8 9 10
/*** every element before the index is sorted. so select the number at the* index location and put it in appropriate position** @param numbers*/private static void sortList(Integer[] numbers) {for (int index = 0; index < numbers.length; index++) {for (int sortIndex = index; sortIndex > 0; sortIndex--) {if (numbers[sortIndex] < numbers[sortIndex - 1]) {swap(sortIndex, sortIndex - 1, numbers);} else {break;}}printArray(numbers);}}/*** swap 2 numbers at the index** @param indexOne* @param indexTwo* @param numbers*/private static void swap(int indexOne, int indexTwo, Integer[] numbers) {Integer temp = numbers[indexOne];numbers[indexOne] = numbers[indexTwo];numbers[indexTwo] = temp;}
Selection Sort in Java
- Find the smallest entry for an Index
- Swap it with the index element do this iteratively till the end of the array
Complexity: (n power 2)/2 comparisions & n exchanges
/*** find the minimum in the series and swap it to the index* @param numbers*/private static void sortList(Integer[] numbers) {for (int index = 0; index < numbers.length; index++) {int minIndex = findMininRest(index, numbers);if (minIndex != index) {swap(minIndex, index, numbers);printArray(numbers);}}}/*** swap 2 numbers at the index* @param minIndex* @param index* @param numbers*/private static void swap(int minIndex, int index, Integer[] numbers) {Integer temp = numbers[minIndex];numbers[minIndex] = numbers[index];numbers[index] = temp;}/*** find the minimum in the rest of the series** @param index* the current index to fill* @param numbers* all the numbers* @return returns the index of the minimum element in the rest series from* index*/private static int findMininRest(int index, Integer[] numbers) {int currentMin = index;for (int restIndex = index + 1; restIndex < numbers.length; restIndex++) {if (numbers[currentMin] > numbers[restIndex]) {currentMin = restIndex;}}return currentMin;}
Trace of the sort per Iteration
0 10 2 9 3 8 1 6 5 7 4 INPUT
0 1 2 9 3 8 10 6 5 7 4
0 1 2 3 9 8 10 6 5 7 4
0 1 2 3 4 8 10 6 5 7 9
0 1 2 3 4 5 10 6 8 7 9
0 1 2 3 4 5 6 10 8 7 9
0 1 2 3 4 5 6 7 8 10 9
0 1 2 3 4 5 6 7 8 9 10 OUTPUT
Java Object Class
it is the base class of all the classes in java
Methods in Java Object class
- hashCode:
- the more unique the hashCode is the more efficient is the hash map/table
- used to find the bucket in which an object goes into in a hash table.
- more than one invocation of hashCode of the same object should return same Integer.
- if two objects are equal according to equals method then their hashCode must be same.
- equals:
- is used in hashMap when two objects have same hashCode.
- if two objects are equal their hashCode must be same.
- it should be
- reflexive : x.equals(x)
- symmetric: x.equals(y) and y.equals(x)
- transtive: x.equals(y) y.equals(z) implies => x.equals(z)
- consitent: x.equals(y) should allways return same value.
- for null it should be false: x.equals(null) false
- the default behaviour of equals = “==” i.e is object comparision
- toString :
- the default implementation is
- classname @ hex format of the hashCode.
- its good to override toString .
- also should be concise and informative.
- clone:
- to clone the object .
- x.clone() != x
- x.clone().getClass() == x.getClass() Not mandatory *
- x.clone().equals(x) Not mandatory *
- alternative to clone is copy constructor
Must have Eclipse Plugins
- m2eclipse: maven plugin for eclipse
- PIT Mutation Test: this plugin helps run mutation tests in eclipse
- Sonar plugin for eclipse: run sonar analysis locally or remotely.
- Jupiter Plugin:Code Review
- TDD Plugins
- http://www.happyprog.com/pairhero/
- http://www.happyprog.com/pulse/
- http://www.happyprog.com/tdgotchi/
- infinitest: runs junit infinetlyhttp://infinitest.github.com/user_guide.html : run related junits for every change
- Static Code Analsis: PMD Programmer Mistakes detector and FindBugs for eclipse
- JUNIT Coverage : EclEmma/clover
- JUNIT junit helper, quick unit
Double.MIN_Value is greater than zero
A constant holding the smallest positive nonzero value of type (oracle java)
0x0.0000000000001P-1022; // 4.9e-324
Annotations @ Runtime
for an annotation to be accessible at runtime it has to be annotated as follows
@Retention(RUNTIME)
How to access annotations
Method[] methods = cls.getMethods();
for(int i=0;i<methods.length';i++){
Annotation[] annos = methods[i].getAnnotations();
// the annos[] can be type casted to the annotation and then used.
}
Web Services
Web Service: a software system designed to support interoperable machine-to-machine interaction over a network.
the interface (contract) of communication is called WSDL.
Web Services Architecture
Service Registry:An registry which maintains the list of service providers.
Service Provider:The one which provides the service.
Service Requestor: The one which requests the service which is the client.
the service requestor or the client sends a SOAP request in an HTTP/SNMP/UDP packet and at the service provider
side the SOAP request is extracted from the packet and interpreted.
Top – Down / Bottom Up Approaches
In top-down approach wsdl is written first and then the java code is generated and implemented.
in bottom-up approach java code is written first and then the wsdl is generated for the same.
Web services with eclipse
eclipse plugin to install: http://axis.apache.org/axis2/java/core/tools/index.html axis2-eclipse-codegen-plugin
downlaod and extract to plugins folder of eclipse.
WSDL- web services description Language.
- describes a web service
- is an xml
- is a w3c standard http://www.w3.org/TR/wsdl
- Service : is a collection of network endpoints, or ports.
- Binding : the communication protocol used along with the data format specification.
- Port Type :collection of abstract operations.
- Messages : the data being exchanged.
- Types : has the data types used by the web service.
- Operation : description of the operation supported by the service.
- Port : endpoint which is a combination of a binding port and a network address
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions>
<wsdl:types>
</wsdl:types>
<wsdl:message name="messageName">
</wsdl:message>
<wsdl:portType name="portName">
</wsdl:portType>
<wsdl:binding name="soapBinding" type="impl:portTypeName">
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/protocol"/>
</wsdl:binding>
<wsdl:service name="serviceName">
<wsdl:port binding="soapBinding" name="HelloWorld">
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
<soap:binding transport indicates the protocol used for sending the soap requesthttp,snmp,smtp,ftp etc.- create a new project with name HelloWebService
- write a simple Java Class
public class HelloImpl {
// says hellopublic String sayHello() {return "Hello world";
}
// adds two numberspublic int addNumbers(int a, int b) {
return a + b;}
}
- Right click on the above class file, select –> Web Services –> Create Web Service
- and select test Service from the panel, which will create the webservice as well as test the service.
- the server runtime can be used to select the application/web server and click next.
6. Select the methods of the java class to be exposed as webservice operations in this case , sayHello and addNumbers operations
![]()
7. Start the server clicking the start button in the next window and then click next.
8. click next and Finish, which will open the Web services Explorer
Take JVM Heap Dump
Approximate Search or Spell Check using Trie in Java
the main program which has to be run is MainRunner.Java
modify the searchString variable in the main program.
books.txt : this file has the list of books which are indexed for the approximate search.
commonwords.txt this file has the words which will be ignored.
Features:
can detect 4 types of errors
the exact word say is programming
1) Transposition : prorgamming
2) Insertion: programNming
3) Deletion: programing {m is deleted}
4) Substitution: projramming
would all list the results of books which have programming text.
Java Bean
1) setters and getters- general properties
2) persistance just like normal objects, even beans have their own persistance api to save and retreive beans which internally uses ObjectOutputStream.
There are some classes in beans api which let you do this
3) listener-event model:when ever there is change in bean properties listeners can be notified
Say the bean has properties
Types of bean properties
a) The notified listeners can veto the change in the bean properties ( Constrained)
b) when ever a property changes there can be another property which is dependant on this this is (bound)so when ever there is change in property the one which is bound is notified about the change
c)( simple properties) no notification onli the property is changed
d) indexed - has range of values like in array
http://java.sun.com/docs/books/tutorial/javabeans/TOC.html
java synchronized block
-------------------------------------------------------------------------------------
inc1(String name) {
synchronized(this) {
c1++ --------------------T1 can enter , this cannot be modified else where
}
}
inc2(String name) {
synchronized(this) { --------------------T2 (thread 2 cannot go inside and change)
c2++
}
}
example 2
-------------------------------------------------------------------------------------
inc1() {
synchronized(lock1) { ---------------lock1 cannot be modified else where
c1++;-------------------------------T1 can enter
}
}
inc2() {
synchronized(lock2) { ---------------lock2 cannot be modified else where
c2++; ------------------- T2 also can enter and change
}
}
Java Virtual Machine ( JVM )
Read Modify XML,using the getElementById
<books>
<book id="1">
<name>java
</name>
</book>
<book id="2">
<name>perl
</name>
</book>
<book id="3">
<name>java 2
</name>
</book>
</books>
the XSD where you specify the id so that getElementById method can be used
<!ELEMENT name (#PCDATA)>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT book (name)*>
<!ATTLIST book id ID #REQUIRED >
<!--- Put your DTDDoc comment here. -->
<!ELEMENT books (book)*>
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//parse the xml file
Document doc = docBuilder.parse(new File("a.xml"));
doc.getElementById("1").getChildNodes().item(1).setTextContent("new book name");
Transformer transformer = TransformerFactory.newInstance().newTransformer(); StreamResult result = new StreamResult(new File("a.xml"));
//write the dom tree which is updated back to the same xml file
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
JDBC-API to connect to a DB
Class.forName("com.mysql.jdbc.Driver")
this will create an instance of Class for com.mysql.jdbc.Driver
find the class file and get the binary data
Constructing the class from the binary data.
then the static block of which instantiates a new Driver of this class and registers with DriverManager
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} .......
}
//added to the drivers in the DriverManager
writeDrivers.addElement(di);
println("registerDriver: " + di);
readDrivers = (java.util.Vector) writeDrivers.clone();
2)Get the connection Object
for (int i = 0; i < drivers.size(); i++) { //iterates over all the drivers list
DriverInfo di = (DriverInfo)drivers.elementAt(i);
try {
println(" trying " + di);
Connection result = di.driver.connect(url, info);
result is the connection object.
Connection newConn = new com.mysql.jdbc.Connection(host(props),
port(props), props, database(props), url, this);
Connection is an interface which is implemented by the providers class
3)create a statement , and execute the query
/* Create a statement*/
Statement statement = connection.createStatement();
String query = "Select * from yourTABLE ";
ResultSet rs = statement.executeQuery(query);



