Skip to content

Tag: Java

Third JEG meeting

JEG #3

We had our third JEG (Java Education Group?) meeting today about Java certifications. We changed our approach and now we are just solving certification questions in group. As we are without projector today we used just my laptop. Today our host was Joselito who solved some section 1 questions.

Joselito’s slides are also available to download here.

More photos in this album.

Was a great meeting, next week another one.

Second certification meeting

Students holding Netbeans CDs

We are meeting every Thursday to talk about Java and certifications (and sometimes about local projects at an operational level). In this moment we are talking about the firsts sections of SCJA and solving mock exams in group.

Our approach is, each week a certification topic, each topic and different person talking. Meetings are free and anyone can join. I’m trying to keep those meeting linked with CEJUG and take we all to the monthly CEJUG meetings.

JEG second meeting

So next Thursday I’ll not talk. Those slides I used aren’t finished yet so I’ll not share them now, but as soon as possible I’ll do that. More photos here.

Java assertion to prevent time travelers

cc broken pocket watches
Creative Commons photo by jekemp

public class PreventTimeTravelers {
    public static void main(String args[]){
        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();
        assert endTime >= startTime: "We came back in time!";
    }
}

Please do not execute this code in a time machine.

NumberFormatException Example

NumberFormatException: Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

An simple example:

public class SummationExample {
    public static void main(String args[]){
        int sum = 0;
        for(String arg: args){
            System.out.println("+" + arg);
            sum += Integer.parseInt(arg);
        }
        System.out.println("= " + sum);
    }
}

$ javac SummationExample.java
$ java SummationExample 1 2 3 4 5
+1
+2
+3
+4
+5
= 15

but

$ java SummationExample 1 2 3 4 five
+1
+2
+3
+4
+five
Exception in thread “main” java.lang.NumberFormatException: For input string: “five”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
at SummationExample.main(SummationExample.java:6)

So

public class SummationExample {
    public static void main(String args[]){
        int sum = 0;
        for(String arg: args){
            try {
                sum += Integer.parseInt(arg);
                System.out.println("+" + arg);
            } catch (NumberFormatException e) {
                // nothing
            }
        }
        System.out.println("= " + sum);
    }
}

now

$ javac BetterSummationExample.java
$ java BetterSummationExample 1 2 3 4 5
+1
+2
+3
+4
+5
= 15

and also

$ java BetterSummationExample 1 2 3 4 five
+1
+2
+3
+4
= 10

Java Duke animated gif waving

JRuby simple example

JRuby is a Java implementation of the Ruby interpreter, with an tightly integrated with Java. In this examples you will call swing components.

On Ubuntu you can get it installing the package jruby (a meta package for jruby1.0 or jruby0.9 packages).

To test it save this code as test.rb and invocate it with the jruby interpreter:

require 'java'

frame = javax.swing.JFrame.new()
frame.getContentPane().add(javax.swing.JLabel.new('Hello, JRuby World!'))
frame.setDefaultCloseOperation(javax.swing.JFrame::EXIT_ON_CLOSE)
frame.pack()
frame.set_visible(true)

$ jruby1.0 test.rb

Hello JRuby World

ps: We did not define a close method, so to close this windows you’ll need to kill its process or press Ctrl+C in your terminal.

Concurso de Blogagem NetBeans IDE 6.1 Beta

Typewriter
Creative Commons Image
Está cada vez mais fácil colaborar com projetos livres.Quem diria que você poderia blogar sobre um projeto livre e ainda ganhar dinheiro e brindes? Esse é o Concurso de Blogagem do Netbeans IDE 6.1 Beta. Blogando você disputa:

  • 10 chances de ganhar um vale-compras American Express no valor de U$ 500,00.
  • 100 chances de ganhar camisetas do Netbeans.

Tudo que você tem que fazer é:

  1. Baixar o Netbeans 6.1 Beta (ou o último release) e experimentar.
  2. Blogue sobre isso.
  3. Envie a URL do seu blog e post.
  4. Faça isso antes de 18 de Abril de 2008!

Os posts enviados seram julgados e serão escolhidos 10 vencedores para ganhar os vale-compras. Os 100 melhores posts ganham camisetas do Netbeans.

Basicamente é isso mas há informações mais detalhadas na página de regras do concurso. Se você estiver com preguiça de ler eu fiz esse perguntas e respostas.

Perguntas e Respostas

O que é esse Netbeans 6.1 Beta?

Netbeans é uma IDE (ambiente de desenvolvimento integrado), um programa que lhe ajuda a construir programas. É multiplataforma (você pode usar no Linux, Windows, Opensolaris, etc), tem suporte há várias linguagens (Java, C/C++, Ruby, PHP etc), disponível em diversos idiomas (a comunidade de tradução para português é uma das mais ativas) e livre (disponível em licenças GPL e CDDL). Para saber mais dê uma olhada na página de características do Netbeans.

Eu posso fazer um post em português?

Sim. Você também pode postar em inglês, espanhol, russo, francês, chinês simplificado, japonês e polonês.

É sorteio?

Não. Os melhores posts serão julgados e classificados. Se seu post estiver entre os 100 melhores você ganha uma camiseta do Netbeans, se estiver entre os 10 melhores, quinhentas doletas. 😉

E eu vou falar do que nesse post?

Teste o Netbeans 6.1 Beta, procure as novidades em relação ao Netbeans 6.0.1, mostre como fazer certas coisas, tire screenshots. Enfim, seja criativo!

Você pode dar uma olhada na lista de características e novidades no Netbeans e se inspirar.

Mas eu não tenho um blog?

Já pensou em criar seu próprio blog? Eu sugiro que dê uma olhada no wordpress.com onde você pode hospedar seu blog de graça usando um ótimo motor de blogs.

Eu posso pegar o post bacana de alguém e submeter dizendo que é meu?

O que é que você acha? ¬_¬
Não, não pode.

E se eu pegar um post bacana de alguém, em outra lingua e submeter dizendo que é um post original meu? Pode?

Não. Claro que não. Você vai ser desclassificado se fizer isso.

Boa blogagem pra você.

Simple Java Chronometer

A very simple Java chronometer code (inspired in the chronometer code in Opale project) you can use for simples measures.

In the main method there’s a example of use.

public final class Chronometer{
    private long begin, end;

    public void start(){
        begin = System.currentTimeMillis();
    }

    public void stop(){
        end = System.currentTimeMillis();
    }

    public long getTime() {
        return end-begin;
    }

    public long getMilliseconds() {
        return end-begin;
    }

    public double getSeconds() {
        return (end - begin) / 1000.0;
    }

    public double getMinutes() {
        return (end - begin) / 60000.0;
    }

    public double getHours() {
        return (end - begin) / 3600000.0;
    }

    public static void main(String[] arg) {
        Chronometer ch = new Chronometer();
        
        ch.start();
        for (int i = 1;i<10000000;i++) {}
        ch.stop();
        System.out.println(ch.getTime());
        
        ch.start();
        for (int i = 10000000;i>0;i--) {}
        ch.stop();
        System.out.println(ch.getTime());
    }
}

Compiling and running this code gives you something like:

191
12

Maybe you got surprised with this. The first loop, with 10 millions of steps is slower than the second, also with 10 millions of steps.

Why?

Some processors (like x86) have an zero-flag in their ALU. Using it is faster perform the question i≠0 than i<K (for a K≠0). In a loop with 10 millions iterations this difference can be perceptible. And this is not just for Java. You can try those loops in others language and see this behavior.

Think twice next time you write a big loop. 🙂

Slides for Java Students Group

These are the slides for the presentation this Thursday at the first meeting of Java Students Group (JEG) at UFC. Is about Sun certifications in general and also a brief look over SCJA.

As usually, you can download the slides as ODT or PDF. 😉

See you there.

Updated: Thanks for your presence. Let’s try it again soon.

Público no encontro do JEG

You can find more photos here.

Java, listing system properties

This code prints out your system properties.

import java.util.Properties;

public class PropertiesLister{
   public static void main (String args[]){
       Properties props = System.getProperties();
       props.list(System.out);
   }
}

In the machine I’m writing right now:

— listing properties —
java.runtime.name=Java(TM) SE Runtime Environment
sun.boot.library.path=/usr/lib/jvm/java-6-sun-1.6.0.00/jre/…
java.vm.version=1.6.0-b105
java.vm.vendor=Sun Microsystems Inc.
java.vendor.url=http://java.sun.com/
path.separator=:
java.vm.name=Java HotSpot(TM) Server VM
file.encoding.pkg=sun.io
user.country=BR
sun.java.launcher=SUN_STANDARD
sun.os.patch.level=unknown
java.vm.specification.name=Java Virtual Machine Specification
user.dir=/tmp
java.runtime.version=1.6.0-b105
java.awt.graphicsenv=sun.awt.X11GraphicsEnvironment
java.endorsed.dirs=/usr/lib/jvm/java-6-sun-1.6.0.00/jre/…
os.arch=i386
java.io.tmpdir=/tmp
line.separator=

java.vm.specification.vendor=Sun Microsystems Inc.
os.name=Linux
sun.jnu.encoding=UTF-8
java.library.path=/usr/lib/jvm/java-6-sun-1.6.0.00/jre/…
java.specification.name=Java Platform API Specification
java.class.version=50.0
sun.management.compiler=HotSpot Server Compiler
os.version=2.6.20-16-generic
user.home=/home/export/silveira
user.timezone=
java.awt.printerjob=sun.print.PSPrinterJob
file.encoding=UTF-8
java.specification.version=1.6
user.name=silveira
java.class.path=.
java.vm.specification.version=1.0
sun.arch.data.model=32
java.home=/usr/lib/jvm/java-6-sun-1.6.0.00/jre
java.specification.vendor=Sun Microsystems Inc.
user.language=pt
java.vm.info=mixed mode
java.version=1.6.0
java.ext.dirs=/usr/lib/jvm/java-6-sun-1.6.0.00/jre/…
sun.boot.class.path=/usr/lib/jvm/java-6-sun-1.6.0.00/jre/…
java.vendor=Sun Microsystems Inc.
file.separator=/
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport…
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.cpu.isalist=

Try out at your home. 🙂