Monday, March 30, 2015

SQL Syntax

select columnnames from tablename where condition;
Eg:
SELECT empid,empname,email,salary FROM employee WHERE empid=1;

insert into tablename(col1,col2...) values(val1,val2,...)
Eg:
INSERT INTO employee(empid,empname,email,salary) VALUES(1,'xxxx','xxx@gmail.com',10000);


delete from tablename where condition;
Eg:
DELETE FROM employee WHERE empid=1;


update employee set empname='cccc' where empid=1;

Monday, March 23, 2015

IO Stream

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

OutputStream

Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.
InputStream

Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.

FileInputStream and FileOutputStream (File Handling)

In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java.

import java.io.FileOutputStream;

class Test {
public static void main(String args[]) {
try {
FileOutputStream fout = new FileOutputStream("C:\\abc.txt"); // It is creating a new file
String s = "Sachin Tendulkar is my favourite player!!!!!";
byte b[] = s.getBytes();// converting string into byte array
fout.write(b); //Sending Byte[] to write method in FileOutputStream
//fout.close();  
/*FileOutputStream fout1 = new FileOutputStream("C:\\abc.txt");*/
String str = "New char";
byte[] b1 = str.getBytes();
fout.write(b1);
System.out.println("success...");
} catch (Exception e) {
System.out.println(e);
}
}
}

Tuesday, March 17, 2015

Queue

package com.queuesample;

import java.util.*;

public class QueueDemo {

public static void main(String[] args) {

System.out.println( "Queue in Java" );
System.out.println("-----------------------" );
System.out.println("Adding items to the Queue"  );
// Creating queue would require you to create instance of LinkedList
// and assign
// it to Queue
// Object. You cannot create an instance of Queue as it is abstract
Queue queue = new LinkedList();

// you add elements to queue using add method
queue.add("Java");
queue.add(".NET");
queue.add("Javascript");
queue.add("HTML5");
queue.add("Hadoop");

System.out.println( "Items in the queue..." + queue );
System.out.println("Before removing "+queue.element());
// You remove element from the queue using .remove method
// This would remove the first element added to the queue, here Java
System.out.println("remove element: " + queue.remove() );

// .element() returns the current element in the queue, here when "java"
// is removed
// the next most top element is .NET, so .NET would be printed.
System.out.println("retrieving element: " + queue.element()  );

// .poll() method retrieves and removes the head of this queue
// or return null if this queue is empty. Here .NET would be printed and
// then would
// be removed
// from the queue
System.out.println("remove and retrieve element, null if empty: "
+ queue.poll() );
System.out.println("After the polling method "+queue.element());

// .peek() just returns the current element in the queue, null if empty
// Here it will print Javascript as .NET is removed above
System.out.println("retrieve element, null is empty " + queue.peek()
);
PriorityQueue priorityQueue = (PriorityQueue)queue;
}
}

Monday, March 16, 2015

Java API - Predefined Packages

Package NameExample ClassesFunctionality (Purpose)
java.langSystem, String, Object, Thread, Exception etc.These classes are indispensable for every Java program. For this reason, even if this package is not imported, JVM automatically imports.
java.utilThese are called as utility (service) classes and are used very frequently in coding.
java.ioFileInputStream, FileOutputStream, FileReader, FileWriter, RandomAccessFile, BufferedReader, BufferedWriter etc.These classes are used in all I/O operations including keyboard input.
java.netURL, ServerSocket, Socket, DatagramPacket, DatagramSocket etc.Useful for writing socket programming (LAN communication).
java.appletAppletContext, Applet, AudioStub, AudioClip etcRequired for developing applets that participate on client-side in Internet (Web) programming.
java.awtButton, Choice, TextField, Frame, List, Checkbox etc.Essential for developing GUI applications.
java.awt.eventMouseListener, ActionListener, ActionEvent, WindowAdapter etc.Without these classes, it is impossible to handle events generated by GUI components
java.sqlDriverManager, Statement, Connection, ResultSet etcRequired for database access in JDBC applications.

Thursday, March 12, 2015

HashMap Example

package com.mapsample;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapDemo {

public static void main(String[] args) {

Hashtable<String, String> hashtableobj = new Hashtable<String, String>();
hashtableobj.put("Alive is ", "awesome");
hashtableobj.put("Love", "yourself");
hashtableobj.put("Clean", "World");
//hashtableobj.put(null,"Testing");

System.out.println("Hashtable object output :" + hashtableobj);

HashMap hashmapobj = new HashMap();
hashmapobj.put("Alive is ", "awesome");
hashmapobj.put("Love", "yourself");
hashmapobj.put("Clean", "World");
//hashmapobj.put(null,"Testing");
System.out.println("HashMap object output :" + hashmapobj);

Set keys = hashmapobj.keySet();
System.out.println(keys);
Iterator itr = keys.iterator();
while(itr.hasNext())
{
String key = itr.next().toString();
System.out.println("Key is "+key+" and value is "+hashmapobj.get(key));
}





// Create a hash map
/* HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));

// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double) hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + hm.get("Zara"));

TreeMap treeMap = new TreeMap();

treeMap.put("Zara", new Double(3434.34));
treeMap.put("Mahnaz", new Double(123.22));
treeMap.put("Ayan", new Double(1378.00));
treeMap.put("Daisy", new Double(99.22));
treeMap.put("Qadir", new Double(-19.08));
System.out.println(treeMap);


*/ }
}

Map

The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface.
A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.


The java.util.SortedMap interface is a subtype of the java.util.Map interface, with the addition that the elements stored in the map are sorted internally.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method TreeMap.descendingKeySet().

Set Overview

HashSet class

contains unique elements only.
Difference between List and Set:

List can contain duplicate elements whereas Set contains unique elements only. It makes no guarantees about the sequence of the elements when you iterate them.

LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet. Reinserting an element that is already in the LinkedHashSet does not change this order.


TreeSet also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a Collections.sort() on a List or array containing these elements. This order is determined either by their natural order (if they implement Comparable), or by a specific Comparator implementation.

Set Exmaple

package com.setsample;

import java.util.*;

public class SetDemo {

  public static void main(String args[]) {
     int count[] = {34, 22,10,60,30,22};
     Set<String> set = new HashSet<String>();
     try{
        set.add("BDG");
        set.add("CDF");
        set.add("ADE");
        set.add("FED");
        set.add("EDR");
        System.out.println(set);
       
        LinkedHashSet hashSet = new LinkedHashSet();
        hashSet.add("BDG");
        hashSet.add("CDF");
        hashSet.add("ADE");
        hashSet.add("FED");
        hashSet.add("ADE");
        hashSet.add("EDR");
        System.out.println("Set with duplicated "+hashSet);
       
        TreeSet sortedSet = new TreeSet<String>(set);
        TreeSet treeset = new TreeSet();
       
        treeset.add("DDDD");
        treeset.add("AAAAA");
        treeset.add("CCCC");
       
        Iterator itr = treeset.iterator();
        while(itr.hasNext())
        {
        if(itr.next().toString().startsWith("C"))
        System.out.println(itr.next());
        }
        System.out.println(treeset);
       
        System.out.println("The sorted list is:");
        System.out.println(sortedSet);

        System.out.println("The First element of the set is: "+
                          (Integer)sortedSet.first());
        System.out.println("The last element of the set is: "+
                        (Integer)sortedSet.last());
     }
     catch(Exception e){}
  }

Assignment on List and Set

There are few employees with below details:

Emp Id
Emp Name
Designation
Salary
Address
Qualification
Department
1
XXXX
SSE
50000
1, 2nd st, NY
B.Tech
IT
2
AAAA
PM
100000
101, 22nd st, DS
M.Tech
ADMIN
3
BBBB
SE
25000
1, 23rd  st, NY
BE
IT
4
YYYY
GM
120000
123, 2nd st, NY
MBA
SALES
5
CCCC
DM
150000
2121, 2nd st, NY
MBA
OPERATION
2
AAAA
PM
100000
101, 22nd st, DS
M.Tech
ADMIN

1. Add this to list and Sort it Alphabetical order. Remove if there is any duplicate. display the index of the employee "BBBB". Dont use Set.

2. The same example use set to sort it and to remove duplicates.

Collection overview


Wednesday, March 11, 2015

ArrayList, Linked List, Vector

Array List:
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.

Linked List:;
Java LinkedList class can contain duplicate elements.
Java LinkedList class maintains insertion order.
Java LinkedList class is non synchronized.
In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
Java LinkedList class can be used as list, stack or queue.
java LinkedList class in collection framework

1) Since Array is an index based data-structure searching or getting element from Array with index is pretty fast. Array provides O(1) performance for get(index) method but remove is costly in ArrayList as you need to rearrange all elements. On the Other hand LinkedList doesn't provide Random or index based access and you need to iterate over linked list to retrieve any element which is of order O(n).

2) Insertions  are easy and fast in LinkedList as compared to ArrayList because there is no risk of resizing array
and copying content to new array if array gets full which makes adding into ArrayList of O(n) in worst case, while adding is O(1) operation in LinkedList in Java. ArrayList also needs to update its index if you insert something anywhere except at the end of array.

3) Removal is like insertions better in LinkedList than ArrayList.


Vector implements a dynamic array. It is similar to ArrayList, but with spme differences:
  • Vector is synchronized.
  • Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program.

ListExample

Arrays:
Arrays are strongly typed. Hence only same type of elements can stored. (Ex. if “A” is an array, here we can store only integer or string or bool etc..).
Since strongly typed, boxing and unboxing never happens.
These are fixed in size and will not grow dynamically runtime.
To store and to retrieve we should use integral index.
Array don’t support Add() and Remove() functions.

ArrayList:
ArrayList are not strongly typed(Loosely typed).
Since Loosely typed, boxing and unboxing happens which results in performance problem.
They can grow dynamically while runtime.
ArrayList provide sufficient methods to work with like Add().



package com.listsample;

import java.util.*;

public class ListExample {

public static void main(String args[]) {

// Creating an empty array list

List list = new ArrayList();
Thread test3 = new Thread();
// Adding items to arrayList

list.add(2);

list.add(3);

list.add(6); // it will add Item3 to the third position of

// array list

list.add("DDD");

// Display the contents of the array list

System.out.println("The arraylist contains the following elements: "

+ list);

/*for (int i = 0; i < list.size(); i++) {

Integer iVal = Integer.valueOf(list.get(i).toString());
System.out.println("Index: " + i + " - Item: " + iVal);

}
// hasNext(): returns true if there are more elements
// next(): returns the next element

System.out.println("Retrieving items using iterator");
Iterator itr = list.iterator();

while (itr.hasNext()) {
String str = itr.next().toString();
System.out.println(str);
if (str.equals("AAA"))
itr.remove();
}
*/ // Generics - to restrict the collection object to specific data type

ArrayList<String> list1 = new ArrayList<String>();

list1.add("aaaa");
list1.add("2");

System.out.println("Availabiliy of the element " +list1.contains("bbb"));


ArrayList<String> list2 = new ArrayList<String>();
System.out.println("Before adding theelemets : "+list2.isEmpty());
list2.add("bbbb");
list2.add("aaaa");
list2.add("cccc");
list2.add("2");
list2.add("cccc");

ArrayList<String> list3 = new ArrayList<String>();
list3.addAll(list1);
list3.addAll(list2);

Collections.synchronizedList(list3);

System.out.println("The contents of list3 are : "+list3);

System.out.println("String list "+list2.toString());
System.out.println("Position of the element "+list2.indexOf("cccc")+" the position of the duplicate "+list2.lastIndexOf("cccc"));

System.out.println("After adding the elements: "+list2.isEmpty());

System.out.println("Comparing the lists: "+list1.containsAll(list2));

Iterator<String> itr1 = list1.iterator();

while (itr1.hasNext()) {
String s = itr1.next();
System.out.println(s);
}

String[] arr = new String[3];
arr[0] = "3";
arr[1]="3";
arr[2] = "4";

String[] arr1 = new String[3];
arr1[0] = "3";
arr1[1]="3";
arr1[2] = "4";
String s="AAA";
String s1= "AAA";

if(s.equals(s1))
{
System.out.println("I m here");
}
System.out.println("Array elements: "+Arrays.toString(arr));
}


}

Tuesday, March 10, 2015

Eclipse short cuts

§  Ctrl + Space : hitting Ctrl + Space when you are in the middle of typing will show you all members and methods that begin with your text.
§  Ctrl + 1 : If you have an error in a line, Ctrl + 1 will show you potential options to fix it, like importing a class, or adding an argument to a method or fixing the method signature
§  Ctrl + Shift + R : Shows the Open Resource dialog. Type to filter, and jump directly between classes. I love this shortcut, and use and abuse it!
§  Ctrl + Shift + O : Organizes Imports, and gets rid of unused imports.
§  Ctrl + O : Shows the methods and properties of a class.
§  Ctrl + T : Opens the Type Heirarchy. Shows all super classes as well as sub classes / implementing types in your class path.
§  Ctrl + / : Comment / Uncomment code. Single or multiple lines, depending on what you have selected.
§  Alt + Shift + R : It renames anything from variables to methods to even classes, renaming the class files if necessary.
§  Alt + Shift + M : Super useful method to break up a larger method into smaller chunks.
§  Alt + Shift + Up / Down : If you hit up, it selects the next biggest code block, down selects the next smallest.
§  Alt + Shift + T : Brings up the Refactor menu
§  Alt + Shift + S : Shows the Source menu. This includes menu options like Comment related, and the ever useful Override / Implement Methods, Generate Getters and Setters, and much more.
§  Alt + Shift + X : Pulls up the Run menu, and shows what key you have to press to run a particular type.
§  Alt + Up / Down : Moves a block of lines up or down.
§  Ctrl + D :   deletes the current line the cursor is on.
§  Ctrl + L : Jump to a Line number
§  Ctrl + Shift + T : Display available types.
§  Alt + Shift + Up / Down : Duplicate selected lines above or below.

§  Ctrl + Shift + L : Show the list of shortcuts.