Git Getting Started

Configure the configuration file for git:

git config --global user.name "YOUR NAME"
git config --global user.email "YOUR EMAIL ADDRESS"

I am currently working with my github account and we can work with over HTTPS or SSH.

For connecting over SSH we need to generate ssh keys:
I have been working with windows cmd but it doesn’t support ssh-keygen so I would be switching to git bash.

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# Creates a new ssh key, using the provided email as a label
Generating public/private rsa key pair.

When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.
Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]

At the prompt, type a secure passphrase. For more information, see "Working with SSH key passphrases".

Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

 

So after following the above steps we would have generated the keys to be used to connect over SSH. Now we need to add the keys to our account.

Private key needs to be added to the ssh agent.

If you are using Git Bash, turn on ssh-agent:
# start the ssh-agent in the background
eval "$(ssh-agent -s)"
Agent pid 59566

If you are using another terminal prompt, such as Git for Windows, turn on ssh-agent:
# start the ssh-agent in the background
eval $(ssh-agent -s)
Agent pid 59566

Add the ssh key to the ssh-agent
$ ssh-add ~/.ssh/id_rsa

 

Public key needs to be added to the github account

# Copies the contents of the id_rsa.pub file to your clipboard
$ clip < ~/.ssh/id_rsa.pub

Add the public key to the github account.
Github -> Settings -> SSH & GPG keys -> New SSH key -> Fill name of key -> Paste key -> Click Add key  

 

Test the Github connection

ssh -T git@github.com
# Attempts to ssh to GitHub

If you see your username everything is fine and running

Github post for the above process of connecting over ssh.

Connecting over https we just don’t need to do much, we might have to configure proxy with git config –http.proxy

Some interesting post about git which I have come across Post-1

Java Generics

Java Genrics was introduced in Java 5.

Java Generics provide compile-time type checking and remove risk of ClassCastException

// Compile Time type checking provided by generics
List list1 = new ArrayList(); // In java 7 we can intialize with List list1 = new ArrayList<>(); 
list1.add("abc");
//list1.add(new Integer(5)); //throws compiler error

 

Java Generic Classes, Interfaces & Methods:

Java Generic Classes

public class GenericsType<T> {
	private T t;	
	public T get(){
		return this.t;
	}	
	public void set(T t1){
		this.t=t1;
	}	
	public static void main(String args[]){
		GenericsType<String> type = new GenericsType<>();
		type.set("Pankaj"); //valid
		
		GenericsType type1 = new GenericsType(); //raw type
		type1.set("Pankaj"); //valid
		type1.set(10); //valid and autoboxing support
	}
}

If we don’t provide the type at the time of creation, compiler will produce a warning that “GenericsType is a raw type. If we don’t provide type, the type becomes Object and hence it’s allowing both String and Integer objects but we should always try to avoid this because we will have to use type casting while working on raw type that can produce runtime errors.

 

Java Generic Interface

public interface Comparable<T> {
public int compareTo(T o);
}

 

Java Generic Method

//Java Generic Method
public static <T> boolean isEqual(GenericsType<T> g1, GenericsType<T> g2){
	return g1.get().equals(g2.get());
}

We can call the above method:
boolean isEqual = GenericsMethods.<String>isEqual(g1, g2);
boolean isEqual = GenericsMethods.isEqual(g1, g2); // Type Inference

 

Invoking a generic method as an ordinary method, without specifying a type between angle brackets is known as Type Inference. Compiler will infer the type that is needed.

 

Java Generics & Inheritance

MyClass<String> myClass1 = new MyClass<String>();
MyClass<Object> myClass2 = new MyClass<Object>();
//myClass2=myClass1; // Compilation Error since MyClass<String> is not a MyClass<Object>

Object obj = new Object();
obj = myClass1; // Valid MyClass<T> parent is Object

This is Valid
ArrayList<E> implements List<E> that extends Collection<E>, so ArrayList<String> is a subtype of List<String> and List<String> is subtype of Collection<String>.

interface MyList<E,T> extends List{
}

 

Java Generics Wildcards

Question mark (?) is the wildcard in generics and represent an unknown type. The wildcard can be used as the type of a parameter, field, or local variable and sometimes as a return type.

 

Java Generics Upper Bounded Wildcard: We use generics wildcard with extends keyword

public static double sum(List<? extends Number> list){
	double sum = 0;
	for(Number n : list){
		sum += n.doubleValue();
	}
	return sum;
}

Invocation:
List<Integer> ints = new ArrayList<>();
ints.add(3); ints.add(5); ints.add(10);
double sum = sum(ints);

Can be used as List doubless= new ArrayList<>();

 

Java Generics Unbounded Wildcard

public static void printData(List<?> list){
	for(Object obj : list){
		System.out.print(obj + "::");
	}
}

 

Java Generics Lower Bounded Wildcard : We use generics wildcard (?) with super keyword and lower bound class to achieve this.

public static void addIntegers(List<? super Integer> list){
	list.add(new Integer(50));
}

 

Java Generics Type Erasure

Generics in Java was added to provide type-checking at compile time and it has no use at run time, so java compiler uses type erasure feature to remove all the generics type checking code in byte code and insert type-casting if necessary. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

 

Java Generics Concept:

1)
List<Number> numbers = new ArrayList<Integer>(); // Invalid can cause ClassCastException

2)
We can’t create generic array? or write code as 
List<Integer>[] array = new ArrayList<Integer>[10]; // Invalid
because Java Generics Type Erasure


 

Links to refer to: Post 1 , Post 2;

Java Collections Questions

I)  http://www.javatpoint.com/java-collections-interview-questions

Few Questions from it:

1) What is the difference between Collection and Collections?

Collection is an interface whereas Collections is a class.

Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

Both are present in java.util package and  part of java collections framework.

2) What is the difference between Comparable and Comparator?

No. Comparable Comparator
1) Comparable provides only one sort of sequence. Comparator provides multiple sort of sequences.
2) It provides one method named compareTo(). It provides one method named compare().
3) It is found in java.lang package. it is found in java.util package.
4) If we implement Comparable interface, actual class is modified. Actual class is not modified.

 

3) What is the advantage of generic collection?

If we use generic class, we don’t need typecasting. It is typesafe and checked at compile time.

 

4) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.

No. Iterator ListIterator
1) Iterator traverses the elements in forward direction only. ListIterator traverses the elements in backward and forward directions both.
2) Iterator can be used in List, Set and Queue. ListIterator can be used in List only.

 

II) http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

1) What is Collection ? What is a Collections Framework ? What are the benefits of Java Collections Framework ?

Collection : A collection (also called as container) is an object  that groups multiple elements into a single unit.

Collections Framework : Collections framework provides unified architecture for manipulating and representing collections.

Benefits of Collections Framework :

1. Improves program quality and speed
2. Increases the chances of reusability of software
3. Decreases programming effort.

2) What is the root interface in collection hierarchy ? 

Root interface in collection hierarchy is Collection interface . Few interviewer may argue that
Collection interface extends Iterable interface. So iterable should be the root interface. But you should reply iterable interface present in java.lang package not in java.util package.

3)  Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe).

4) Name the core Collection  interfaces ?

The list of core collection interfaces are : the important ones
Important : Collection , Set , Queue , List , Map
Other interface also in the list :  SortedSet, SortedMap , Deque, ListIterator etc.


5) What is an iterator ?

Iterator is an interface . It is found in java.util package. It provides methods to iterate over any Collection.

6) What is the difference between Iterator and Enumeration ?

The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration doesn’t.
Hence , using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read only interface as it can only traverse the objects and fetch it.


7)
Which methods you need to override to use any object as key in HashMap ?

To use any object as key in HashMap , it needs to implement equals() and hashCode() method .
8) How to reverse the List in Collections ?

There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.

Collections.reverse(listobject);

9) How to convert the array of strings into the list ?

Arrays class of java.util package contains the method asList() which accepts the array as parameter.
So,

String[]  wordArray =  {“Love Yourself”  , “Alive is Awesome” , “Be in present”};
List wordList =  Arrays.asList(wordArray);

10) What is the difference between ArrayList and Vector ?

1). Vector is synchronized while ArrayList is not .
2). Vector is slow while ArrayList is fast .
3). Every time when needed, Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%.11) What is the difference between HashMap and Hashtable ?

1) HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
2) HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe.

12) What is the difference between peek(),poll() and remove() method of the Queue interface ?

Both poll() and remove() method is used to remove head object of the Queue. The main difference lies when the Queue is empty().
If Queue is empty then poll() method will return null . While in similar case , remove() method will throw NoSuchElementException .
peek() method retrieves but does not remove the head of the Queue. If queue is empty then peek() method also returns null.

13) What is the difference between HashSet and TreeSet ?

1)  HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
2) HashSet can store null object while TreeSet can not store null object.

14)  What is the difference between HashMap and ConcurrentHashMap ?

1) HashMap is not synchronized while ConcurrentHashMap is synchronized.
2) HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .

15) Arrange the following in the ascending order (performance):
HashMap , Hashtable , ConcurrentHashMap and Collections.SynchronizedMap Hashtable  <  Collections.SynchronizedMap  <  ConcurrentHashMap  <  HashMap

16) What is the difference between LinkedList and ArrayList in Java ?

1) LinkedList is the doubly linked list implementation of list interface , while , ArrayList is the resizable array implementation of list interface.
2) LinkedList can be traversed in the reverse direction using descendingIterator() method  provided by the Java Api developers , while , we need to implement our own method to traverse ArrayList in the reverse direction

17) Why Map interface does not extend the Collection interface in Java Collections Framework ?

Map interface is not compatible with the Collection interface.
Explanation : Since Map requires key as well as value , for example , if we want to add key-value pair then we will use put(Object key , Object value) . So there are two parameters required to add element to the HashMap object  . In Collection interface add(Object o) has only one parameter.
The other reasons are Map supports valueSet , keySet as well as other appropriate methods which have just different views from the Collection interface.

18)When to use ArrayList and when to use LinkedList in application?

ArrayList has constant time search operation O(1) .Hence, ArrayList is preferred when there are more get() or search operation .

Insertion , Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.

 

Post to look into : http://www.journaldev.com/1330/java-collections-interview-questions-and-answers

Java Memory Management

Java Heap Vs Stack Memory

Java Heap Space:

  • Java Heap space is used by java runtime to allocate memory to Objects and JRE classes.
  • Whenever we create any object, it’s always created in the Heap space.
  • Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference.
  • Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory:

  • Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method.
  • Stack memory is always referenced in LIFO (Last-In-First-Out) order.
  • Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.
  • Stack memory size is very less compared to Heap memory.

 

Difference btw Stack & Heap Memory

  • We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
  • When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
  • Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  • Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  • Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc.
  • Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

 

Detailed Explanation at this post.

Java Concepts

1) Java is Pass by Value and Not Pass by Reference

What is pass by value vs pass by reference ?

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.

Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

In java variables are just the reference to the objects, we get confused that we are passing the reference so java is pass by reference. However we are passing a copy of the reference and hence it’s pass by value.

Detailed Explanation at this post.

 

Java Swing Musings

To prevent window from resizing:

frame.setResizable(false)

 

Manage two radio buttons so that only 1 is selectable at a time:

Use ButtonGroup
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);

 

In my application I have move the user from one screen to next on button click. I am wondering how to do it in Swing. There are couple of good posts I have come across for this Post1, Post2.

97kgp

 

Adding Border around a container: Set an EmptyBorder around your JPanel.

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

OR

JPanel containerPanel = new JPanel();
containerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
containerPanel.setLayout(new BorderLayout());

 

Setting a background color same as container color

list.setBackground(panel.getBackground());

 

Anytime we modify the GUI in Swing we need to call:

frame.revalidate()
frame.repaint()


Why use of multiple JFrames in a Swing Application is a bad practice: Post

 

Right now I am searching how to update a JList with some contents, I wud be fetching from remote server.

 

 

 

Java Swing getting started with Eclipse (WindowBuilder)

I have to design a user interface for CKAN search, for desktop application. I am planning to use Java Swing for it.

To get started I would be using Eclipse IDE, I have installed WindowBuilder Eclipse Plugin for designing my user interface (https://eclipse.org/windowbuilder/).

Steps to install WindowBuilder on Eclipse (I am on version Mars 4.5).

Help -> Install new software -> Work with : Mars- http://download.eclipse.org/releases/mars -> General Purpose Tools

Here I have installed :
Swing Designer
SWT Designer
SWT Designer Core
WindowBuilder Core
WindowBuilder Core UI
WindowBuilder Java Core
WindowBuilder XML Core

 

To get started with WindowBuilder I found this post on stackoverflow

1) How can I make and run a simple window with WindowBuilder?

Go to File -> New -> Other. The "select a wizard" window pops up.

Double click in WindowBuilder folder and then to Swing Designer subfolder.

Click to the Application Window and then click Next.

Give a Name for your new window and then click Finish. The Source code of the new Window pops up.

Press Run (the "Play" icon of the toolbar) to run your newly created window.

2) How can I access the WindowBuilder Core from my Eclipse and show up the toolbar with buttons and textboxes e.t.c.?

To access the core WindowBuilder you have to switch to the Design View of your newly created window. To do that, just press the Design tab at the end of the window tab. You will see the core WindowBuilder Toolbar (or "Palette") and you will be able from here to drag-n-drop the controls you want into you window.

Links:
WindowBuilder: http://help.eclipse.org/kepler/index.jsp?topic=%2Forg.eclipse.wb.doc.user%2Fhtml%2Findex.html,

CKAN Musings

It seems I need to write a CKAN search interface to integrate with a Java tool. I am wondering which api client library to use for it.

Two options right now are python library or a java library itself.

I have begin testing with Jackan (http://opendatatrentino.github.io/jackan/index.html) which is java ckan library. It seems to be easy to work with. Let me test it capabilities further. Jackan API docs http://opendatatrentino.github.io/jackan/0.4/javadoc/index.html.