Thursday 31 January 2013

Input-stream to File Generation in Java

Input-stream to File Generation in Java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Convert_InputStream_toFile
{
public static void main(String args[])
{
try
{
File f=new File("outFile.java");
InputStream inputStream= new FileInputStream("InputStreamToFile.java");
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
}
}

RequestBuilder in Gwt

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;

String url="http://restro.example.com/download?id=0.1212123455&name=raja";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try
{
Request request = builder.sendRequest("", new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
Window.alert("Request Builder Failed");
}
public void onResponseReceived(Request request, Response response)
{
Window.alert("Request Builder passed"+response.getStatusCode());
}
});
} catch (RequestException e)
{
e.printStackTrace();
}

Wednesday 30 January 2013

HashMap keys and values into ArrayList in java

HashMap hm;
// ...add hm values here...

ArrayList keys = new ArrayList(hm.keySet());
ArrayList values = new ArrayList(hm.values());
ArrayList all = new ArrayList();
all.addAll(hm.keySet());
all.addAll(hm.values());

Tuesday 29 January 2013

GWT SuggestBox Enable and Disable

import com.google.gwt.user.client.DOM;

//pass in your own TextBox when you construct the SB:
TextBox tb = new TextBox();
SuggestBox sb = new SuggestBox(oracle, tb);

// and disable the TextBox it can effect to SuggestBox
tb.setEnabled(false);

// and enable the TextBox it can effect to SuggestBox
tb.setEnabled(true);


public static void setEnabled(SuggestBox sb,boolean enabled)
{
DOM.setElementPropertyBoolean(sb.getElement(), "disabled", !enabled);
}

 
 
 

Thursday 10 January 2013

Android : How To Check If Device Has Camera

In Android, you can use PackageManager , hasSystemFeature() method to check if a device has camera, gps or other features.

See full example of using PackageManager in an activity class.


package com.mkyong.android;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

public class FlashLightActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);

Context context = this;
PackageManager packageManager = context.getPackageManager();

// if device support camera?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
//yes
Log.i("camera", "This device has camera!");
}else{
//no
Log.i("camera", "This device has no camera!");
}

}
}



Camera flashlight example
You may interest on this example – How to turn on/off camera LED/flashlight in Android.

How To Send Email In Android

In Android, you can use Intent.ACTION_SEND to call an existing email client to send an Email.

See following code snippets :


	Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"youremail@yahoo.com"});
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));



P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Run & test on real device only.
If you run this on emulator, you will hit error message : “No application can perform this action“. This code only work on real device.

1. Android Layout


File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textViewPhoneNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextTo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" >

<requestFocus />

</EditText>

<TextView
android:id="@+id/textViewSubject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subject : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextSubject"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</EditText>

<TextView
android:id="@+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:inputType="textMultiLine"
android:lines="5" />

<Button
android:id="@+id/buttonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />

</LinearLayout>




2. Activity


Full activity class to send an Email. Read the onClick() method, it should be self-explanatory.


package com.mkyong.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SendEmailActivity extends Activity {

Button buttonSend;
EditText textTo;
EditText textSubject;
EditText textMessage;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);

buttonSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
String message = textMessage.getText().toString();

Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
//email.putExtra(Intent.EXTRA_CC, new String[]{ to});
//email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);

//need this to prompts email client only
email.setType("message/rfc822");

startActivity(Intent.createChooser(email, "Choose an Email client :"));

}
});
}
}



3. Demo


See default scree, fill in the detail, and click on the “send” button.
Android-Send-Email-Example-1

It will prompts your existing Email client to select.
Android-Send-Email-Example-2

In this case, i selected Gmail, and all previous filled in detail will be populated to Gmail client automatically.
Android-Send-Email-Example-3

Note
Android does not provide API to send Email directly, you have to call the existing Email client to send Email.

Download Source Code


Download it – Android-Send-Email-Example.zip (16 KB)

How To Send SMS Message In Android

In Android, you can use SmsManager API or device’s Built-in SMS application to send a SMS message. In this tutorial, we show you two basic examples to send SMS message :

  1. SmsManager API


    	SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);



  2. Built-in SMS application


    	Intent sendIntent = new Intent(Intent.ACTION_VIEW);
    sendIntent.putExtra("sms_body", "default content");
    sendIntent.setType("vnd.android-dir/mms-sms");
    startActivity(sendIntent);




Of course, both need SEND_SMS permission.


<uses-permission android:name="android.permission.SEND_SMS" />



P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Note
The Built-in SMS application solution is the easiest way, because you let device handle everything for you.

1. SmsManager Example


Android layout file to textboxes (phone no, sms message) and button to send the SMS message.

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textViewPhoneNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Phone Number : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextPhoneNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:phoneNumber="true" >
</EditText>

<TextView
android:id="@+id/textViewSMS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter SMS Message : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:lines="5"
android:gravity="top" />

<Button
android:id="@+id/buttonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />

</LinearLayout>



File : SendSMSActivity.java – Activity to send SMS via SmsManager.


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSMSActivity extends Activity {

Button buttonSend;
EditText textPhoneNo;
EditText textSMS;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonSend = (Button) findViewById(R.id.buttonSend);
textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
textSMS = (EditText) findViewById(R.id.editTextSMS);

buttonSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String phoneNo = textPhoneNo.getText().toString();
String sms = textSMS.getText().toString();

try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}

}
});
}
}



File : AndroidManifest.xml , need SEND_SMS permission.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mkyong.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="android.permission.SEND_SMS" />

<application
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".SendSMSActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



See demo :
android-send-sms-message-example


2. Built-in SMS application Example


This example is using the device’s build-in SMS application to send out the SMS message.

File : res/layout/main.xml – A button only.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
android:id="@+id/buttonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />

</LinearLayout>



File : SendSMSActivity.java – Activity class to use build-in SMS intent to send out the SMS message.


package com.mkyong.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SendSMSActivity extends Activity {

Button buttonSend;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonSend = (Button) findViewById(R.id.buttonSend);

buttonSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

try {

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}



See demo :
android-send-sms-message-example2

android-send-sms-message-example2-1

Download Source Code


Download it – 1. Android-Send-SMS-Example.zip (16 KB)


How To Open An URL In Android’s Web Browser

Here’s a code snippet to show you how to use “android.content.Intent” to open an specify URL in Android’s web browser.


	button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.mkyong.com"));
startActivity(intent);

}

});



Note
For full example, please refer to this – Android button example.

How To Set Default Activity For Android Application

In Android, you can configure the starting activity (default activity) of your application via following “intent-filter” in “AndroidManifest.xml“.

See following code snippet to configure a activity class “logoActivity” as the default activity.

File : AndroidManifest.xml


        <activity
android:label="Logo"
android:name=".logoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>



For example, let said you have two activities class, and you want to set the “ListMobileActivity” activity as the starting activity of your application.

File : AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mkyong.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="List of Mobile OS"
android:name=".ListMobileActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="List of Fruits"
android:name=".ListFruitActivity" >
</activity>
</application>

</manifest>



On the other hand, If you want to set the “ListFruitActivity” activity as your starting activity, just cut and paste the “intent-filter” like following :

File : AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mkyong.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="List of Mobile OS"
android:name=".ListMobileActivity" >
</activity>
<activity
android:label="List of Fruits"
android:name=".ListFruitActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


Java Comparable and Comparator Example to sort Objects

Java provides some inbuilt methods to sort primitive types array or Wrapper classes array or list. Here we will first learn how we can sort an array/list of primitive types and wrapper classes and then we will use java.lang.Comparable and java.util.Comparator interfaces to sort array/list of custom classes.

Let’s see how we can sort primitive types or Object array and list with a simple program.









JavaObjectSorting.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36


package com.journaldev.sort;


import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;


public class JavaObjectSorting {


    /**

     * This class shows how to sort primitive arrays,

     * Wrapper classes Object Arrays

     * @param args

     */

    public static void main(String[] args) {

        //sort primitives array like int array

        int[] intArr = {5,9,1,10};

        Arrays.sort(intArr);

        System.out.println(Arrays.toString(intArr));

        

        //sorting String array

        String[] strArr = {"A", "C", "B", "Z", "E"};

        Arrays.sort(strArr);

        System.out.println(Arrays.toString(intArr));

        

        //sorting list of objects of Wrapper classes

        List<String> strList = new ArrayList<String>();

        strList.add("A");

        strList.add("C");

        strList.add("B");

        strList.add("Z");

        strList.add("E");

        Collections.sort(strList);

        for(String str: strList) System.out.print(" "+str);

    }

}




Output of the above program is:










1

2

3


[1, 5, 9, 10]

[1, 5, 9, 10]

 A B C E Z




Now let’s try to sort an array of a custom class we have.









Employee.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40


package com.journaldev.sort;


public class Employee {


    private int id;

    private String name;

    private int age;

    private long salary;


    public int getId() {

        return id;

    }


    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    public long getSalary() {

        return salary;

    }


    public Employee(int id, String name, int age, int salary) {

        this.id = id;

        this.name = name;

        this.age = age;

        this.salary = salary;

    }


    @Override

    //this is overriden to print the user friendly information about the Employee

    public String toString() {

        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +

                this.salary + "]";

    }


}




Here is the code I used to sort the array of Employee objects.










1

2

3

4

5

6

7

8

9


//sorting custom object array

Employee[] empArr = new Employee[4];

empArr[0] = new Employee(10, "Mikey", 25, 10000);

empArr[1] = new Employee(20, "Arun", 29, 20000);

empArr[2] = new Employee(5, "Lisa", 35, 5000);

empArr[3] = new Employee(1, "Pankaj", 32, 50000);

//sorting employees array using Comparable interface implementation

Arrays.sort(empArr);

System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));




When I tried to run this, it throws following runtime exception.










1

2

3

4

5

6


Exception in thread "main" java.lang.ClassCastException: com.journaldev.sort.Employee cannot be cast to java.lang.Comparable

    at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)

    at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)

    at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)

    at java.util.Arrays.sort(Arrays.java:472)

    at com.journaldev.sort.JavaSorting.main(JavaSorting.java:41)




Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj)method which is used by sorting methods, you can check any Wrapper, String or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.

After implementing Comparable interface in Employee class, here is the resulting Employee class.









Employee.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50


package com.journaldev.sort;


import java.util.Comparator;


public class Employee implements Comparable<Employee> {


    private int id;

    private String name;

    private int age;

    private long salary;


    public int getId() {

        return id;

    }


    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    public long getSalary() {

        return salary;

    }


    public Employee(int id, String name, int age, int salary) {

        this.id = id;

        this.name = name;

        this.age = age;

        this.salary = salary;

    }


    @Override

    public int compareTo(Employee emp) {

        //let's sort the employee based on id in ascending order

        //returns a negative integer, zero, or a positive integer as this employee id

        //is less than, equal to, or greater than the specified object.

        return (this.id - emp.id);

    }


    @Override

    //this is required to print the user friendly information about the Employee

    public String toString() {

        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +

                this.salary + "]";

    }


}




Now when we execute the above snippet for Arrays sorting of Employees and print it, here is the output.










1

2


Default Sorting of Employees list:

[[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]




As you can see that Employees array is sorted by id in ascending order.

But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Comparator interface becauseComparable.compareTo(Object o) method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.

Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.

Here is how we can create different Comparator implementation in the Employee class.










1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32


/**

     * Comparator to sort employees list or array in order of Salary

     */

    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return (int) (e1.getSalary() - e2.getSalary());

        }

    };


    /**

     * Comparator to sort employees list or array in order of Age

     */

    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getAge() - e2.getAge();

        }

    };


    /**

     * Comparator to sort employees list or array in order of Name

     */

    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getName().compareTo(e2.getName());

        }

    };




We can use these comparator to pass as argument to sort function of Arrays and Collections classes.










1

2

3

4

5

6

7

8

9


//sort employees array using Comparator by Salary

Arrays.sort(empArr, Employee.SalaryComparator);

System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Age

Arrays.sort(empArr, Employee.AgeComparator);

System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Name

Arrays.sort(empArr, Employee.NameComparator);

System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));




Here is the output of the above code snippet:










1

2

3

4

5

6


Employees list sorted by Salary:

[[id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000]]

Employees list sorted by Age:

[[id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000]]

Employees list sorted by Name:

[[id=20, name=Arun, age=29, salary=20000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000]]




So now we know that if we want to sort any custom object array/list, we need to implement Comparable to provide default sorting and we should implement Comparator to provide specific sorting.

We can also create separate class that implements Comparator interface and then use it.

Here is the final classes we have explaining java Comparable and Comparator.









Employee.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82


package com.journaldev.sort;


import java.util.Comparator;


public class Employee implements Comparable<Employee> {


    private int id;

    private String name;

    private int age;

    private long salary;


    public int getId() {

        return id;

    }


    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    public long getSalary() {

        return salary;

    }


    public Employee(int id, String name, int age, int salary) {

        this.id = id;

        this.name = name;

        this.age = age;

        this.salary = salary;

    }


    @Override

    public int compareTo(Employee emp) {

        //let's sort the employee based on id in ascending order

        //returns a negative integer, zero, or a positive integer as this employee id

        //is less than, equal to, or greater than the specified object.

        return (this.id - emp.id);

    }


    @Override

    //this is required to print the user friendly information about the Employee

    public String toString() {

        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +

                this.salary + "]";

    }


    /**

     * Comparator to sort employees list or array in order of Salary

     */

    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return (int) (e1.getSalary() - e2.getSalary());

        }

    };


    /**

     * Comparator to sort employees list or array in order of Age

     */

    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getAge() - e2.getAge();

        }

    };


    /**

     * Comparator to sort employees list or array in order of Name

     */

    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getName().compareTo(e2.getName());

        }

    };

}




Here is the separate class implementation of Comparator interface that will compare two Employees object first on their id and if they are same then on name.









EmployeeComparatorByIdAndName.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14


package com.journaldev.sort;


import java.util.Comparator;


public class EmployeeComparatorByIdAndName implements Comparator<Employee> {


    @Override

    public int compare(Employee o1, Employee o2) {

        int flag = o1.getId() - o2.getId();

        if(flag==0) flag = o1.getName().compareTo(o2.getName());

        return flag;

    }


}




Here is the test class where we are using different ways to sort Objects in java.









JavaObjectSorting.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43


package com.journaldev.sort;


import java.util.Arrays;


public class JavaObjectSorting {


    /**

     * This class shows how to sort custom objects array/list

     * implementing Comparable and Comparator interfaces

     * @param args

     */

    public static void main(String[] args) {


        //sorting custom object array

        Employee[] empArr = new Employee[4];

        empArr[0] = new Employee(10, "Mikey", 25, 10000);

        empArr[1] = new Employee(20, "Arun", 29, 20000);

        empArr[2] = new Employee(5, "Lisa", 35, 5000);

        empArr[3] = new Employee(1, "Pankaj", 32, 50000);

        

        //sorting employees array using Comparable interface implementation

        Arrays.sort(empArr);

        System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));

        

        //sort employees array using Comparator by Salary

        Arrays.sort(empArr, Employee.SalaryComparator);

        System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));

        

        //sort employees array using Comparator by Age

        Arrays.sort(empArr, Employee.AgeComparator);

        System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));

        

        //sort employees array using Comparator by Name

        Arrays.sort(empArr, Employee.NameComparator);

        System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));

        

        //Employees list sorted by ID and then name using Comparator class

        empArr[0] = new Employee(1, "Mikey", 25, 10000);

        Arrays.sort(empArr, new EmployeeComparatorByIdAndName());

        System.out.println("Employees list sorted by ID and Name:\n"+Arrays.toString(empArr));

    }


}




Here is the output of the above program:










1

2

3

4

5

6

7

8

9

10


Default Sorting of Employees list:

[[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]

Employees list sorted by Salary:

[[id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000]]

Employees list sorted by Age:

[[id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000]]

Employees list sorted by Name:

[[id=20, name=Arun, age=29, salary=20000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000]]

Employees list sorted by ID and Name:

[[id=1, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000]]




The java.lang.Comparable and java.util.Comparator are powerful interfaces that can be used to provide sorting objects in java.

Java Object Sorting Example (Comparable And Comparator)

In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value.

1. Sort an Array


To sort an Array, use the Arrays.sort().


	String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; 

Arrays.sort(fruits);

int i=0;
for(String temp: fruits){
System.out.println("fruits " + ++i + " : " + temp);
}



Output


fruits 1 : Apple
fruits 2 : Banana
fruits 3 : Orange
fruits 4 : Pineapple




2. Sort an ArrayList


To sort an ArrayList, use the Collections.sort().


	List<String> fruits = new ArrayList<String>();

fruits.add("Pineapple");
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");

Collections.sort(fruits);

int i=0;
for(String temp: fruits){
System.out.println("fruits " + ++i + " : " + temp);
}



Output


fruits 1 : Apple
fruits 2 : Banana
fruits 3 : Orange
fruits 4 : Pineapple



3. Sort an Object with Comparable


How about a Java Object? Let create a Fruit class:


public class Fruit{

private String fruitName;
private String fruitDesc;
private int quantity;

public Fruit(String fruitName, String fruitDesc, int quantity) {
super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}

public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}



To sort it, you may think of Arrays.sort() again, see below example :


package com.mkyong.common.action;

import java.util.Arrays;

public class SortFruitObject{

public static void main(String args[]){

Fruit[] fruits = new Fruit[4];

Fruit pineappale = new Fruit("Pineapple", "Pineapple description",70);
Fruit apple = new Fruit("Apple", "Apple description",100);
Fruit orange = new Fruit("Orange", "Orange description",80);
Fruit banana = new Fruit("Banana", "Banana description",90);

fruits[0]=pineappale;
fruits[1]=apple;
fruits[2]=orange;
fruits[3]=banana;

Arrays.sort(fruits);

int i=0;
for(Fruit temp: fruits){
System.out.println("fruits " + ++i + " : " + temp.getFruitName() +
", Quantity : " + temp.getQuantity());
}

}
}



Nice try, but, what you expect the Arrays.sort() will do? You didn’t even mention what to sort in the Fruit class. So, it will hits the following error :


Exception in thread "main" java.lang.ClassCastException: 
com.mkyong.common.Fruit cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)



To sort an Object by its property, you have to make the Object implement the Comparable interface and override thecompareTo() method. Lets see the new Fruit class again.


public class Fruit implements Comparable<Fruit>{

private String fruitName;
private String fruitDesc;
private int quantity;

public Fruit(String fruitName, String fruitDesc, int quantity) {
super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}

public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

public int compareTo(Fruit compareFruit) {

int compareQuantity = ((Fruit) compareFruit).getQuantity();

//ascending order
return this.quantity - compareQuantity;

//descending order
//return compareQuantity - this.quantity;

}
}



The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order.
The compareTo() method is hard to explain, in integer sorting, just remember 

  1. this.quantity – compareQuantity is ascending order.

  2. compareQuantity – this.quantity is descending order.


To understand more about compareTo() method, read this Comparable documentation.


Run it again, now the Fruits array is sort by its quantity in ascending order.


fruits 1 : Pineapple, Quantity : 70
fruits 2 : Orange, Quantity : 80
fruits 3 : Banana, Quantity : 90
fruits 4 : Apple, Quantity : 100



4. Sort an Object with Comparator


How about sorting with Fruit’s “fruitName” or “Quantity”? The Comparable interface is only allow to sort a single property. To sort with multiple properties, you need Comparator. See the new updated Fruit class again :


import java.util.Comparator;

public class Fruit implements Comparable<Fruit>{

private String fruitName;
private String fruitDesc;
private int quantity;

public Fruit(String fruitName, String fruitDesc, int quantity) {
super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}

public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

public int compareTo(Fruit compareFruit) {

int compareQuantity = ((Fruit) compareFruit).getQuantity();

//ascending order
return this.quantity - compareQuantity;

//descending order
//return compareQuantity - this.quantity;

}

public static Comparator<Fruit> FruitNameComparator
= new Comparator<Fruit>() {

public int compare(Fruit fruit1, Fruit fruit2) {

String fruitName1 = fruit1.getFruitName().toUpperCase();
String fruitName2 = fruit2.getFruitName().toUpperCase();

//ascending order
return fruitName1.compareTo(fruitName2);

//descending order
//return fruitName2.compareTo(fruitName1);
}

};
}



The Fruit class contains a static FruitNameComparator method to compare the “fruitName”. Now the Fruit object is able to sort with either “quantity” or “fruitName” property. Run it again.

1. Sort Fruit array based on its “fruitName” property in ascending order.


Arrays.sort(fruits, Fruit.FruitNameComparator);



Output


fruits 1 : Apple, Quantity : 100
fruits 2 : Banana, Quantity : 90
fruits 3 : Orange, Quantity : 80
fruits 4 : Pineapple, Quantity : 70



2. Sort Fruit array based on its “quantity” property in ascending order.


Arrays.sort(fruits)



Output


fruits 1 : Pineapple, Quantity : 70
fruits 2 : Orange, Quantity : 80
fruits 3 : Banana, Quantity : 90
fruits 4 : Apple, Quantity : 100



The java.lang.Comparable and java.util.Comparator are powerful but take time to understand and make use of it, may be it’s due to the lacking of detail example.

My thoughts…


In future, Arrays class should provides more generic and handy method – Arrays.sort(Object, String, flag).

To sort a object array by its “fruitName” in ascending order.


Arrays.sort(fruits, fruitName, Arrays.ASCENDING);



To sort a object array by its “quantity” in ascending order.


Arrays.sort(fruits, quantity, Arrays.DESCENDING);


How many ways to create object in java?

There are different ways to create object in java as follows:--

1. Using new keyword
we can create the instance normally using new operator which is called as static instance creation.
Hello hello =  new Hello();

2.using Class.forName()
we can create the instance dynamically without using new operator as follow
Hello hello=(Hello)Class.forName("com.bikash.Hello").newInstance();
or
Class cls = Class.forName("com.bikash.Hello");
Hello hello = (Hello)cls.newInstance();

3.using clone().
clone() method can be used to copy of the existing object.
Hello hello=new Hello();
Hello hello1=(Hello)hello.clone();



4.using object deserialization.
deserializion is the process of creating the new object on the remote mechine from its serialize form.
ObjectInputStream ois =new ObjectInputStream();
Hello hello = (Hello)ois.readObject();

What is call by value and call by reference in java with example?

CALL BY VALUE:  

Look at first example:

class Hello
{

void disp(int i,int j)

{

i*=2;

j/=2;

}

}


class T7

{

public static void main(String as[])

{

int a=99;

int b=77;

System.out.println("before call");
System.out.println("a="+a);

System.out.println("b="+b);


Hello h=new Hello();

h.disp(a,b);

System.out.println("AFTER call");

System.out.println("a="+a);

System.out.println("b="+b);

 }

}


OUTPUT:

before call

a=99

b=77

AFTER call

a=99

b=77


When you pass a simple type to a method, it is passed by value. Thus what occurs to the parameter that receives the argument has no effect outside the method. Here the operation occur inside disp() have no effect on the values of a and b used in the call. Their values didn't change to 198 and 38.

CALL BY REFERENCE:

class Hello
{

int a,b;

Hello(int i,int j)

{

a=i;

b=j;

}

void disp(Hello o) //pass an object

{

o.a*=2;

o.b/=2;

}

}


class T6

{

public static void main(String as[])

{

Hello h=new Hello(15,20);

System.out.println("before call");

System.out.println("a="+h.a);

System.out.println("b="+h.b);

h.disp(h);

System.out.println("AFTER call");

System.out.println("a="+h.a);

System.out.println("b="+h.b);

}

      }

OUTPUT:

before call

a=15

b=20

AFTER call

a=30

b=10


When you pass an object to a method the situation change dramatically. Because objects are passed by Reference. When you creating a variable of a class type ,  you are only creating a reference to an object. change to the object inside the method do effect the object used as an argument. When object reference is passed to a method, the reference itself is passed by use of call-by-value.

Difference between HashSet and TreeSet?

HashSet

  •     In HashSet elements are unordered

  •     In HashSet you can add different types of object



TreeSet


  •     In TreeSet elements are in sorted ordered

  •     In TreeSet you can’t add different types of object; you can add only similar types of object.

What is String literal pool? How to create a String

There are two ways to create a String object in Java:

  • Using the new operator. For example,
    String str = new String("Hello");.

  • Using a string literal or constant expression). For example,
    String str="Hello"; (string literal) or
    String str="Hel" + "lo"; (string constant expression).


What is difference between these String's creations? In Java, the equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares the content of two objects rather than two objects' references. The == operator with reference types (i.e., Objects) evaluates as true if the references are identical - point to the same object. With value types (i.e., primitives) it evaluates as true if the value is identical. The equals method is to returntrue if two objects have identical content - however, the equals method in the java.lang.Object class - the default equals method if a class does not override it - returns trueonly if both references point to the same object.

Let's use the following example to see what difference between these creations of string:
public class DemoStringCreation {

public static void main (String args[]) {
String str1 = "Hello";
String str2 = "Hello";
System.out.println("str1 and str2 are created by using string literal.");
System.out.println(" str1 == str2 is " + (str1 == str2));
System.out.println(" str1.equals(str2) is " + str1.equals(str2));


String str3 = new String("Hello");
String str4 = new String("Hello");
System.out.println("str3 and str4 are created by using new operator.");
System.out.println(" str3 == str4 is " + (str3 == str4));
System.out.println(" str3.equals(str4) is " + str3.equals(str4));

String str5 = "Hel"+ "lo";
String str6 = "He" + "llo";
System.out.println("str5 and str6 are created by using string
constant expression.");
System.out.println(" str5 == str6 is " + (str5 == str6));
System.out.println(" str5.equals(str6) is " + str5.equals(str6));

String s = "lo";
String str7 = "Hel"+ s;
String str8 = "He" + "llo";
System.out.println("str7 is computed at runtime.");
System.out.println("str8 is created by using string constant
expression.");
System.out.println(" str7 == str8 is " + (str7 == str8));
System.out.println(" str7.equals(str8) is " + str7.equals(str8));

}
}

The output result is:
str1 and str2 are created by using string literal.
str1 == str2 is true
str1.equals(str2) is true
str3 and str4 are created by using new operator.
str3 == str4 is false
str3.equals(str4) is true
str5 and str6 are created by using string constant expression.
str5 == str6 is true
str5.equals(str6) is true
str7 is computed at runtime.
str8 is created by using string constant expression.
str7 == str8 is false
str7.equals(str8) is true

The creation of two strings with the same sequence of letters without the use of the newkeyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources.

String Literal Pool


String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "Hello";
System.out.print(str1 == str2);
}
}

The result is
true

Unfortunately, when you use
String a=new String("Hello");

String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = new String("Hello");
System.out.print(str1 == str2 + " ");
System.out.print(str1.equals(str2));
}
}

The result is
false true

 

A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. Thejava.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added. For example
public class Program
{
public static void main(String[] args)
{
// Create three strings in three different ways.
String s1 = "Hello";
String s2 = new StringBuffer("He").append("llo").toString();
String s3 = s2.intern();

// Determine which strings are equivalent using the ==
// operator
System.out.println("s1 == s2? " + (s1 == s2));
System.out.println("s1 == s3? " + (s1 == s3));
}
}

The output is
s1 == s2? false
s1 == s3? true

There is a table always maintaining a single reference to each unique String object in the global string literal pool ever created by an instance of the runtime in order to optimize space. That means that they always have a reference to String objects in string literal pool, therefore, the string objects in the string literal pool not eligible for garbage collection.

String Literals in the Java Language Specification Third Edition


Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions-are "interned" so as to share unique instances, using the method String.intern.

Thus, the test program consisting of the compilation unit:
package testPackage;
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other { static String hello = "Hello"; }

and the compilation unit:
package other;
public class Other { static String hello = "Hello"; }

produces the output:
true true true true false true

This example illustrates six points:

  • Literal strings within the same class in the same package represent references to the same String object.

  • Literal strings within different classes in the same package represent references to the same String object.

  • Literal strings within different classes in different packages likewise represent references to the same String object.

  • Strings computed by constant expressions are computed at compile time and then treated as if they were literals.

  • Strings computed by concatenation at run time are newly created and therefore distinct.


The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

Use SimpleDateFormat to convert format Date and Calender in java

Using SimpleDateFormat for custom date formatting and parsing

The default DateFormat instances returned by the static methods in the DateFormat class may be sufficient for many purposes, but clearly do not cover all possible valid or useful formats for dates. For example, notice that in Figure 2, none of the DateFormat-generated strings (numbers 2 – 9) match the format of the output of the Date class’s toString() method. This means that you cannot use the default DateFormat instances to parse the output of toString(), something that might be useful for things like parsing log data.

The SimpleDateFormat lets you build custom formats. Dates are constructed with a string that specifies a pattern for the dates to be formatted and/or parsed. From the SimpleDateFormatJavaDocs, the characters in Figure 7 can be used in date formats. Where appropriate, 4 or more of the character will be interpreted to mean that the long format of the element should be used, while fewer than 4 mean that a short format should be used.

































































































































SymbolMeaningTypeExample
GEraText“GG” -> “AD”
yYearNumber“yy” -> “03″
“yyyy” -> “2003″
MMonthText or Number“M” -> “7″
“M” -> “12″
“MM” -> “07″
“MMM” -> “Jul”
“MMMM” -> “December”
dDay in monthNumber“d” -> “3″
“dd” -> “03″
hHour (1-12, AM/PM)Number“h” -> “3″
“hh” -> “03″
HHour (0-23)Number“H” -> “15″
“HH” -> “15″
kHour (1-24)Number“k” -> “3″
“kk” -> “03″
KHour (0-11 AM/PM)Number“K” -> “15″
“KK” -> “15″
mMinuteNumber“m” -> “7″
“m” -> “15″
“mm” -> “15″
sSecondNumber“s” -> “15″
“ss” -> “15″
SMillisecond (0-999)Number“SSS” -> “007″
EDay in weekText“EEE” -> “Tue”
“EEEE” -> “Tuesday”
DDay in year (1-365 or 1-364)Number“D” -> “65″
“DDD” -> “065″
FDay of week in month (1-5)Number“F” -> “1″
wWeek in year (1-53)Number“w” -> “7″
WWeek in month (1-5)Number“W” -> “3″
aAM/PMText“a” -> “AM”
“aa” -> “AM”
zTime zoneText“z” -> “EST”
“zzz” -> “EST”
“zzzz” -> “Eastern Standard Time”
Excape for textDelimiter“‘hour’ h” -> “hour 9″
Single quoteLiteral“ss”SSS” -> “45’876″





1. Date() + SimpleDateFormat()




DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));



 2. Calender() + SimpleDateFormat()



DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));



Full example


Here is the full source code to show you the use of Date() and Calender() class to get and display the current date time.


package com.mkyong;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GetCurrentDateTime {
public static void main(String[] args) {

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));

//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

}
}


SQL Commands:

SQL commands are instructions used to communicate with the database to perform specific task that work with data. SQL commands can be used not only for searching the database but also to perform various other functions like, for example, you can create tables, add data to tables, or modify data, drop the table, set permissions for users. SQL commands are grouped into four major categories depending on their functionality:

  • Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and dropping the structure of database objects. The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.

  • Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving, modifying, and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.

  • Transaction Control Language (TCL) - These SQL commands are used for managing changes affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.

  • Data Control Language (DCL) - These SQL commands are used for providing security to database objects. These commands are GRANT and REVOKE.

Saturday 5 January 2013

String to Date Conversion in SQL with (STR_TO_DATE)

STR_TO_DATE(str,format) is the inverse of the DATE_FORMAT() function.
STR_TO_DATE() returns a DATETIME value.
Ex:
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');

--------------------------------------------------------------------------------------------

| STR_TO_DATE('04/31/2004', '%m/%d/%Y') |
------------------------------------------------------------------
2004-04-31          


The following specifiers may be used in the format string.
The '%' character is required before format specifier characters.         

       












































































































































SpecifierDescription
%aAbbreviated weekday name (Sun..Sat)
%bAbbreviated month name (Jan..Dec)
%cMonth, numeric (0..12)
%DDay of the month with English suffix (0th, 1st, 2nd, 3rd, ?-)
%dDay of the month, numeric (00..31)
%eDay of the month, numeric (0..31)
%fMicroseconds (000000..999999)
%HHour (00..23)
%hHour (01..12)
%IHour (01..12)
%iMinutes, numeric (00..59)
%jDay of year (001..366)
%kHour (0..23)
%lHour (1..12)
%MMonth name (January..December)
%mMonth, numeric (00..12)
%pAM or PM
%rTime, 12-hour (hh:mm:ss followed by AM or PM)
%SSeconds (00..59)
%sSeconds (00..59)
%TTime, 24-hour (hh:mm:ss)
%UWeek (00..53), where Sunday is the first day of the week
%uWeek (00..53), where Monday is the first day of the week
%VWeek (01..53), where Sunday is the first day of the week; used with %X
%vWeek (01..53), where Monday is the first day of the week; used with %x
%WWeekday name (Sunday..Saturday)
%wDay of the week (0=Sunday..6=Saturday)
%XYear for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%xYear for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%YYear, numeric, four digits
%yYear, numeric (two digits)
%%A literal '%' character
%xx, for any 'x' not listed above