Archive for the ‘Java’ Category

Integrating Twitter via Java

Thursday, February 11th, 2010

This you want to integrate to Twitter from Java you can use the following library JTwitter.

Try out the twitter integration with the following coding:


package de.vogella.twitter.test;

import java.util.List;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.Twitter.User;

public class TwitterTest {
	private static final String user ="your-user";
	private static final String pw ="your-password";

	public static void main(String[] args) {
		// Make a Twitter object
		Twitter twitter = new Twitter(user ,pw );
		// Print Lars Vogel status
		System.out.println(twitter.getStatus("vogella"));
		// Set my status
		twitter.setStatus("@vogella messing with Twitter in Java");
		List<User> followers = twitter.getFollowers();
		for (User user : followers) {
			System.out.println(user.getName());
		}
	}
}

Another Java Twitter Library is Twitter4J.

 

How can I use a Java jar file in a Grails application?

Wednesday, February 10th, 2010

After banging my head against the wall in trying to find out how I can use Java class in a Grails application I found out that the solution is embarrassing simple.

Just create a jar file from your Java classes and put the jar file into the folder “jar” of your Grails application.

You also have to add the correct import statement to your Groovy file. E.g. if you want to use class “MyJavaClass” in package “de.vogella.test” you have to add “import de.vogella.test.MyJavaClass” to your Groovy class.

You also need to re-start the grails server.

To learn more about Grails see Grails Tutorial

 

Disassemble Java class files via javap

Monday, November 16th, 2009

Today I received the question how someone could see the Java code for a Java class file. You can disassemble the Java byte code via the command line tool javap.

Lets assume you have this tiny Java class Test.java

package test;

public class Test {

	int number = 5;

	public void sayHello() {
		System.out.println("Hello");
	}
}

Compile this class via javac Test. javaand you receive Java.class

If you you run javap Test you receive the attributes and method signatures.

C:\temp\javaptest>javap Test
Compiled from "Test.java"
public class test.Test extends java.lang.Object{
    int number;
    public test.Test();
    public void sayHello();
}

If you you run javap -C Test you receive the byte-code


C:\temp\javaptest>javap -c Test
Compiled from "Test.java"
public class test.Test extends java.lang.Object{
int number;

public test.Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   aload_0
   5:   iconst_5
   6:   putfield        #2; //Field number:I
   9:   return

public void sayHello();
  Code:
   0:   getstatic       #3; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   ldc     #4; //String Hello
   5:   invokevirtual   #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   8:   return

}

To get the full Java source code you can use the tool jad.

16.11.2008 Updated entry based on comments from Eric and Phil. Thanks!

 

Collection of Java related Podcasts

Thursday, August 6th, 2009

The following is a list of my favorite Java and Java related Podcasts. Please feel free to suggest additional Java podcasts.

While this blog entry will not be edited I’m planning to keep an updated list of these Java Podcasts on Java Podcasts Overview.

Java Podcasts:

Javaposse

Most likely the best known Java podcast is Javaposse which can be found on http://javaposse.com/.In this podcast Tor Norbye, Carl Quinn, Dick Wall and Joe Nuxoll discuss the news around Java and the Java Virtual Machine and perform interviews with the key player in the Java world. They also cover news about Scala.

This podcast is in english.

Eclipse live

Eclipse related web seminars and podcasts can be found on http://live.eclipse.org/ .

Theses podcasts are (mainly) in english.

Javahispano

Spanish podcast around Java technology and Java news can be found http://feeds.javahispano.org/JHPodcasts

This podcast is in spanish.

Les cast codeurs

French podcast around Java technology and Java news can be found at http://lescastcodeurs.com/.

This podcast is in french.

Java related (covering also other topics)

Software Engineering Radio

Software Engineering Radio performs interesting interviews with the technical stars from different programming areas (including Java technology). They also have sessions there they explain on a starter level technology for example “what is database”.

http://www.se-radio.net/

This podcast is in english.

IBM Developerworks

IBM developerworks features mainly interviews about all kinds of topics including lots of Java and JVM related informations.

http://www.ibm.com/developerworks/podcast/

This podcast is in english.

 

Using Collections.sort and Comparator in Java

Tuesday, August 4th, 2009

Sorting a collection in Java is easy, just use Collections.sort(Collection) to sort your values. For example:

package de.vogella.algorithms.sort.standardjava;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Simple {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(5);
		list.add(4);
		list.add(3);
		list.add(7);
		list.add(2);
		list.add(1);
		Collections.sort(list);
		for (Integer integer : list) {
			System.out.println(integer);
		}
	}
}

This is possible because Integer implements the Comparable interface. This interface defines the method compare which performs pairwise comparison of the elements and returns -1 if the element is smaller then the compared element, 0 if it is equal and 1 if it is larger.

But what if what to sort differently, e.g. for example in different order. Well, you could just use Collection.reverse(). Or you define your own class with implements the interface Comparator.

package de.vogella.algorithms.sort.standardjava;

import java.util.Comparator;

public class MyIntComparable implements Comparator<Integer>{

	@Override
	public int compare(Integer o1, Integer o2) {
		return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
	}
}
package de.vogella.algorithms.sort.standardjava;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Simple2 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(4);
		list.add(3);
		list.add(7);
		list.add(2);
		list.add(1);
		Collections.sort(list, new MyIntComparable());
		for (Integer integer : list) {
			System.out.println(integer);
		}
	}
}

The nice thing about this approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dataOfBirth you could define different implementations of Comparator and sort the objects according to your needs.

 

Java Performance with Strings and StringBuilder

Sunday, July 19th, 2009

Strings are very frequently used in Java programs. This blog post tries to explain what a programmer needs to consider from a performance point of view. It will also explain in what situations you should use StringBuilder instead of String.

Strings in Java are immutable. If you look at the source code of String you find that java.lang.String has the following properties.

/** The value is used for character storage. */
    private final char value[];

 /** The offset is the first index of the storage that is used. */
    private final int offset;

 /** The count is the number of characters in the String. */
    private final int count;

The array is used to store the values of this String.

As Strings are immutable they can be freely shared. This property is utilized in the method substring(). The method substring will use a reference to the same String and only change the offset and the lenght value for the String. The same string is in this case used several times.

Therefore using substring requires only a constant amount of time (and almost no additional memory) and can be freely used.

The operation concat() (which is called by the + operator) combines two Strings. This method has to copy the characters of the two Strings and therefore takes time and extra space which is propotional to the length of the two strings .

The object StringBuilder has a more effectly way of concatenate Strings. It works similar to the class ArrayList by allocating a predefined array for storing the characters and keeps track of the used space. Every time the space is exceeded then it will extend the available capacity).

Does this means that you always have to use StringBuilder if you are concatening strings?

No. Of course if in your program you combine only a few times String the runtime overhead is normally not relevant for the overall performance.

But of course if you combine frequently strings in your program you should switch to StringBuilder.