Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, January 28, 2014

Java Programming Terms

 Functional Interface

Its new term in JavaSE 8 for interfaces having just one method e.g. Runnable, ActionListener, Comparator, all are the examples of functional interfaces. Previous name was Single Abstract Method Type (SAM).

Anonymous Inner Classes

Its on the spot implementation of interface without explicitly requiring a name. Usually implementation of interfaces is done by classes and each class does have name but anonymous inner class does not have any name

Lambda Expressions

Short hand or concise notation for implementing functional interfaces than anonymous inner classes.

Immutable and Mutable Objects

Immutable objects are those objects which can not be changed after its creation. String is most famous example of immutable object. There are many pros of immutable objects like they can not be corrupted by multiple threads in concurrent application, least overhead for GC

Guarded Blocks

Its a code block waiting for a certain condition to be true for its execution. It happens in multi threading programs when different threads do different task and they coordinate each other by setting certain conditions / variables.

Generic Type

Generic Type is a generic class or interface that is parametrized over types.

Generic Type Declaration

 Definition of a class with type variables is know as Generic Type Declaration. This type variable can be used anywhere within a class.

The Diamond

In Java SE 7, we can replace the type arguments required to invoke a generic class, with empty set of type arguments (<>) as long as the compiler can determine or infer the type arguments from the content. This pair of angle brackets is known as "the diamond".

Box integerBox = new Box<>();
 
Raw Type
A Generic Class or interface without type arguments is known as raw type. e.g. List is a generic type but simple List is a raw type. We can assign generic types to raw types but assignment of raw type to generic type will give warnings and will be checked at runtime.
 

Updating...

Friday, December 20, 2013

Create a KeyStore to save Secret Key

Secret key is used to encrypt and decrypt the strings like "password" and other secret information. KeyStore is the most secure place to keep secret key. 

Here are the main steps to create new key store and saving a secret key:
  • Get instance of KeyStore using KeyStore.getInstance method. It takes the name of the keystore
  • Once instance of KeyStore is available, load it as empty keyStore
  • Generate the secretKey and save it to keystore for future purposes.
    private final String KEYSTORE_TYPE = "JCEKS";
    private final String KEYSTORE_NAME = "CareKeyStore";
    private final String SECRET_KEY_NAME = "secretKeyAlias";
    private final String KEY_ALGO = "AES";

    private String final pwd ="mypass";

    KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
    ks.load (null,pwd.toCharArray());
    KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGO);
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();
    KeyStore.ProtectionParameter protParam =
                            new KeyStore.PasswordProtection(pwd.toCharArray());
    KeyStore.SecretKeyEntry skEntry =
                            new KeyStore.SecretKeyEntry(secretKey);
    ks.setEntry(SECRET_KEY_NAME, skEntry, protParam);
    java.io.FileOutputStream fos = null;
    try {
           fos = new java.io.FileOutputStream(KEYSTORE_NAME);
           ks.store(fos, pwd.toCharArray());
                       
     }catch(Exception ex){
           logger.error(null,ex);
                       
      }finally {
            if (fos != null) {
                  fos.close();
            }
      }






          

Thursday, February 24, 2011

Learning IOS Programming for Java Developers - Memory Management in Setters and Getters Of Object

Encapsulation is one of the basic building block in Object Oriented paradigm. Encapsulation in Java is achieve by restricting user to directly access the fields of Object and in order to access those fields, setters and getters are written. Objective C is also an object oriented programming language and also provides encapsulation by providing setters and getters to access the object data. Here is the sample class which contains two fields. One is an object and second one is of basic data type.
@interface TestClass : NSObject
{
NSString *name;
int id;
}

- (void) setName : (NSString *) newName;
- (NSString *) name;

- (void) setId : (int) newId;
- (int) id;

"setName" and "name" is setter and getter of "name" field. Similarly "setId" and "id" id setter and getter of "id" field.

Here is the implementation part of class
@implementation TestClass
{
- (void) setName : (NSString *) newName
{
[newName retain];
[name release];
name = newName;
}

- (NSString *) name
{
return name;
}
- (void) setId : (int) newId
{
id = newId;
}

- (int) id
{
return id;
}


}

setName needs your special intention for memory management point of view. First you send message "retain" to parameter, then you release old field by sending message "release" to name pointer. Then you assign new value to name pointer. These three steps are critical because if you change the order like you release old one and then retain new parameter, if both are same, then by sending release message will free the memory and new parameter will also be freed because that was same as old one. By sending retain message to parameter, you actually gain ownership of it and its reference count increases. Since you have also ownership of old one, so you will have to release it otherwise you will lose reference and there will be memory leak. Now as a java developer i can think that if "name" field is null, then sending release message may give something like NullPointerException but in Objective C, sending a message to null is safe and it will not throw any error and will keep executing next line.
Now last thing which is missing is that how to release fields which are retained before releasing object memroy, so for that you will have to overwrite a special method of NSObject "dealloc". This method is called when you send release message to an object and its reference count is 0. In this method you will have to release all those objects which you have retained. Sample implementation for above class is given below:
- (void) dealloc
{
[name release];
[super dealloc];
}


Wednesday, February 23, 2011

How to Learn IOS Programming having experience In Java language

I am creating this post to help those which are working in java programming language and want to explore or work in IOS. I am working in Java for last eight years and now exploring IOS programming so will share my experiences through this post.

Thursday, June 12, 2008

Implementing Equals and HashCode

In my last blog i described how we can compare two java objects of same class by overriding equals method. In this blog i will explain best practices regarding implementing of equals method.
Whenever, we go for overriding of equals method, one question comes to our mind is, on which basis we will have to say that two objects are same. First answer comes to mind is that we should compare objects on the basis of primary key which is also used to distinguish the records in the database. Primary keys are good candidate to compare objects if we assign primary keys ourself not by database. When primary key is assigned by database like auto number, objects don't have primary key until they are persisted in the database so before persistent of objects, how we should compare the objects. Good practice is always compare objects on the basis of business key which uniquely describes objects. Suppose we have a class of Person with attributes (id, name, ssn,address) . In this class we have two unique attributes one is id and second one is ssn. id is used to distinguish the objects in the database and is assigned when objects are persisted, then only choice is SSN which we can use to compare different person because each person has his own SSN (Social Security Number). So best practice is always compare objects on business keys rather than on database keys.
Second best practice is whenever you go for overriding of equals method. also override "int hashCode()" method. This method returns hash of objects. Implementing hasCode facilitates us when we use objects as keys in HashTable. If we don't override hashCode method, each object created with new operator will always has different hash values irrespective of fact whether they are same or not. Suppose I have a class of Customer with attributes (id, name, ssn, address) and i create two objects with new operation having the same dataset. Although logically they are same but physically they are two different objects that's y they have differnt hashCode. So best practice is that if two objects are equals, then those two objects should always have same hashCode. Overriding of hashCode will also facilitate us when we save objects in sets. Sets store only one instance of an object at a time, so if we have two customer objects with same attributes, then only one instance of customer must be saved in sets. It is only possible by overriding of hashcode method.
Now question is how to generate hashCode for an object. Answer is same as for equals method. Always generate hashCode from business keys. In above example of Customer objects, we should generate hashCode of Customer from SSN. java has provided methods which generate hashCode for all primitive data types and for String. hashCode for primitive data types are generated by using wrappers of primitive data types e.g. for int we can generate hashCode by following code:

Integer i = new Integer(5);
int code = i.hashCode();

Similary we can get hashCode of other primitive datatypes by using respective wrapper classes.

So in this blog we have come to Two Best Practices regarding comparison of objects:
- One is always compare objects in equal method on the basis of business keys.
- Second is whenever override equals method, also override hashCode method and generate hash for objects on the basis of same business key as used in equals method.

Saturday, May 3, 2008

Comparison of Objects with equals

== relational operator is used to compare basic data types in java e.g. if we want to compare two integers, we will do it as follows:

int a = 5;
int b = 5;
if (a == b)
System.out.println("equal");
else
System.out.println("not equal");

Output of above java code will be "equal". but this "==" operator works only with basic data types, even it will not work if we use wrapper classes of basic data types e.g.

Integer a = new Integer(5);
Integer b = new Integer(5);
if (a == b)
System.out.println("equal");
else
System.out.println("not equal");


Output of above code will be "not equal". Why "==" operator does not applicable for objects is that because it compares two references of object not contents of objects. Now for comparison of contents of objects there is "equals" method in each object e.g. if we change above comparison of wrapper classes with this code, it will work correctly:

Integer a = new Integer(5);
Integer b = new Integer(5);
if (a.equals(b))

System.out.println("equal");
else
System.out.println("not equal");

Output of above code will be "equal" This "equals" work fine for wrapper classes but does not run correctly for custom classes because it compares two object references by default just like "==" operator. To change behaviour of "equals" we will have to override it in our classes. Suppose i have a class "Book" which has attributes like name, isbn, author, publisher. Now uniqueness of book is checked using isbn number so to compare two books, override "equals" method and in that implementation check the "isbn" of book. Code Structure is given below:

public class Book{
private String isbn;
private String name;
private String author;

public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

@Override
public boolean equals(Object obj) {
Book book = (Book)obj;
if (this.isbn.equals(book.getIsbn()))
return true;

return false;
}

public static void main(String args[]) {
Book b1 = new Book();
b1.setName("Java");
b1.setAuthor("Amer");
b1.setIsbn("12334");
Book b2 = new Book();
b2.setName("Java");
b2.setAuthor("Amer");
b2.setIsbn("12334");
if (b1.equals(b2))
System.out.println("equal");
else
System.out.println(" not equal");
}
}

output of above code will be equal. even if name or author of two are different because my implementation of "equals" just checks for "isbn".

In my later post, i will exlain best practices related to overriding of "equals" method.

Friday, April 25, 2008

Object Oriented Programming vs Non Object Programming

Often people are confused about real benefits which are provided by OOP. I am trying to remove their confusion in this episode of blog. Every innovation in this world is related to solution of a problem. There is a problem, then we try to find out solution of that problem. So we have to work in two spaces. one is Problem-space in which we concentrate on problem only. and second one is Solution-space in which we develop solution. When we develop solution through computer, we have to think in terms of machine which happened in assembly language. It is impossible for one to get a sense of problem while reading an assembly program. So there is a big gap between problem and solution. People have to develop different artifacts to bridge this gap. After assembly, some other languages came like C, prolog and others , which provided some abstraction on machine but still there was a big gap e.g. prolog concentrates on reasoning and facts. After that OOP made its position, which really reduced the gap between problem-space and solution-space. What we understand and see in problem, we can easily map to a solution which provides us good sense of problem. I explain it with an example e.g. we are developing a solution for a library. Now everyone knows that library has some books and students draw books from library for some time and then return to library. Now if we think on problem, we will come to know that everything in library is relating to three entities Book, Students, and Library itself. Now when we develop solution of this in OOP, we will map these entities to classes and by taking a general look on it, one can easily understand what's going on in the solution and to what things this solution is related.
In short it is the OOP which reduced the gap between problem-space and soluton-space.