Monday 21 April 2014

Speed test: String vs StringBuilder in JAVA

We compare String with StringBuilder, run this code and see yourself, example:


public class SpeedTest
{
    public static void main(String[] args)
    {
        final String SAMPLE = "The Quick Brown Fox Jumps Over The Lazy Dog.";
        final int COUNT = 5000;

        // string
        String str = "";
        long start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            str += SAMPLE;
        long strTotal = System.nanoTime() - start;
        if (str.length() == 123)
            System.exit(0);

        // StringBuilder
        StringBuilder builder = new StringBuilder(SAMPLE.length() * COUNT);
        start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            builder.append(SAMPLE);
        long sbTotal = System.nanoTime() - start;

        System.out.println("String total time: " + (strTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder total time: " + (sbTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder vs. String: " + (strTotal / sbTotal));
    }

}


If this little "code" helped you, please subscribe, like us on facebook, share it, or do whatever you want with it

Have a good one. M.L.

Friday 14 March 2014

PHP - Problem with "mysqli" - SQL Database

SQL works in phpmyadmin not in PHP



If your sql code works in phpmyadmin not in php probably main reason for that is in "mysqli" procedure.

"MYSQLi" don't work with "old" version's of PHP so you will not get any error everything will seem fine but nothing will happen.

You are probably connecting to database something like this:

$con=mysqli_connect("host","admin","password","name_of_database");

if (mysqli_connect_errno()) {
       echo "Error, we can't connect to database: " . mysqli_connect_error();
} else {
$sql="INSERT INTO userTable (username, password) VALUES ('$username', '$password');
}

if (!mysqli_query($con,$sql)) {
    echo "Error!";
} else {
    echo "Ok!";    
}
mysqli_close($con);  // we need to close connection to database...

And something is wrong but you don't know what?

Try the same code just with "mysql" function and it will work, so you will need to write something like this:

$sql="INSERT INTO userTable (username, password) VALUES ('$username', '$password');

mysql_connect("host", "admin", "password") or die(mysql_error()); 

mysql_select_db("name_of_database") or die(mysql_error()); 

$data = mysql_query($sql) or die(mysql_error());

 mysql_close();

When I write my code like this, magic happen, my user is inserted to database...

Notice!
"or die(mysql_error())" will make your server to "die" so you will get error and everything will stop if you need to continue just remove that and everything will be ok.

If this little "tutorial" helped you, please subscribe, like us on facebook, share it, or do whatever you want with it. :)

Have a good one. M.L.



Saturday 8 February 2014

Do you know how simple is programming? Try it yourself. AutoIT

You don't need to be IT expert to write a program, you can write your own programs with this script language:

 

AutoIT



There are a lot of complicated programming languages​​, but there are also simple language that everyone can use, one of them is AutoIT script language.

He is very simple and easy to learn. You can write simple and complicated programs for whatever you need.

How to start with AutoIT? You need to do 1. and 3. step on this link. After that you are ready to write your own programs.

I will show you how to make program to open your CD drive and close it in a loop every 1 minute. :D
We all wanted in some point to be a hackers, this is a closest you can be a hacker without knowing anything about programing.

So how to start? You can do like this, go to your desktop or folder you want to make programs and click right click, from menu select "New" then select AutoIT script. Name it like "CD Drive" or something like that. After you name it, you need to right click on it and click on Edit Script, by default if you just open it i will run script and nothing will be executed because you don't have any code on script.

So we click on Edit Script and now you see Script Editor, all you need to do now is to write your code and use your imagination. :)
We are building CD script, so what do we need? Script gonna be in a loop because we want that CD open's every 1 minute. So how to make a loop?

You can do a loop very easy and intuitive like this:
While 1=1

Wait! What? :D Yes this is a loop, if you think about it loop will do code while condition is correct, in our example 1 is always equal to 1 so our loop will do this always! :)

So how will the loop know where is the end of our code? We need to add this:
WEnd

W - represents while loop and End - end of the loop so every simple for now. :D

Hmm we want to do this loop every 60 second so we need to pause or "sleep" our program for 1 minute, how we gonna do that? Just add this:    sleep(time in millisecond)
So we need to our program sleeps for 60 second, 1 second has 1000 millisecond so we just add sleep method:
while 1=1

sleep(60000)
WEnd

We have our loop who will execute code in every minute in just 3 line of code's :D How cool is that? :)
Now we need to open a CD drive, you can say hmm that is hard, hmm no! Programing is simple because all you need to do is to call method who will do something that we need, so we need method to get CD Drive.

$var = DriveGetDrive( "CDROM" ) 

In this variable called "$var" we get all CD drives on computer, if you think what is this "$" sign means, that is AutoIT thing to say what is variable, you don't need to know anything about that...

So we have all drives in one variable, now we need to open it, so we need to iterate through all cd drive's and open it. We will do it like this:
If not @error Then
For $i = 1 to $var[0]
    CDTray($var[$i] , "open")
Next
EndIf

We first ask is there some kind of error in calling CD Drive's? If not we use for loop to iterate through all CD drives, so if we have 3 drives, with for we go from 1 to 3, we now use 1drive call method to open it: CDTray($var[$i] , "open")When we are finished with first drive we call method Next it will give us next drive, so for loop will now do same thing with second drive, after second is finished we call Next and call it for third drive. So with that 5 lines of codes we open all CD drives on computer. Our code look like this now:

While 1=1

$var = DriveGetDrive( "CDROM" )
If not @error Then
For $i = 1 to $var[0]
    CDTray($var[$i] , "open")
Next
EndIf

sleep(60000)
WEnd

And we finish it :D If you want to close it and after a few second you can use that same code but change "open" to "close" for operation and add sleep between open and close about 20-30 second and you are good. :D

Now we need to create executive program that we can send someone to make a joke with him. :)
In Script Editor menu you have Tools tab, open it and click "Build". That will call AutoIT function to make our program become executive or .exe file. If you don't have any mistakes with your code in your folder or desktop where did you create this script will be file NameOfTheScript.exe and all you need to do now is to zip it or rar it and send it to someone you want to go insane. :P

You can run it on your computer as well, if you want to stop it just use Ctrl+Alt+Delete and kill the program... :) 

This is a tutorial how to make CD Room open's with 10 lines of code and you don't need to be programer to do that. 
If you want to learn more try to read AutoIT documentation or just leave comment bellow and we will make new tutorial how to do similar crazy stuff with AutoIT... :)

If you like this post please like us on Facebook, subscribe, share it, do whatever you want with it... :)
Have a good one. M.L.


Sunday 2 February 2014

Best algorithms for sorting arrays - Java

Bubble sort, Insertion sort and Selection sort



Which one you will use depends on what do you need. Bubble sort is a simplest algorithm, it will do the job but he will be slow, if you need something faster try Selection Sort and Insertion Sort.

They use different methods of sorting if you want to know how they works read it on this links:

My example of implementation this 3 algorithm's, I add speed test so you will see results which one is the best.
Notice: If you are using algorithms for different things, test it in all 3 algorithms it can give different results.


public class Example {

    public static void insertion_sort (int array[]) {
        long start = System.nanoTime();
        for (int i = 1; i < array.length; i++) {
            int j = i;
            int B = array[i];
            while ((j > 0) && (array[j-1] > B)) {
                array[j] = array[j-1];
                j--;
            }
            array[j] = B;
        }
        long total = System.nanoTime() - start;
        System.out.println("Time needed for sorting: "
                + (total / 1000000.0));
    }

    public static void selection_sort (int array[]) {
        long start = System.nanoTime();
        for (int x = 0; x < array.length; x++) {
            int index_of_min = x;
            for (int y = x; y < array.length; y++) {
                if (array[index_of_min] < array[y]) {
                    index_of_min = y;
                }
            }
            int temp = array[x];
            array[x] = array[index_of_min];
            array[index_of_min] = temp;
        }
        long total = System.nanoTime() - start;
        System.out.println("
Time needed for sorting: "
                + (total / 1000000.0));
    }


    public static void bubble_sort( int a[] ) {
        long start = System.nanoTime();
        int i, j,t=0;
        for (i = 0; i < a.length; i++) {
            for (j = 1; j < (a.length-i); j++) {
                if (a[j-1] > a[j]){
                    t = a[j-1];
                    a[j-1] = a[j];
                    a[j] = t;
                }
            }
        }
        long total = System.nanoTime() - start;
        System.out.println("
Time needed for sorting: "
                + (total / 1000000.0));
    }
   
   
    public static void main (String [] args) {
        int i;
        int array[] = {12,9,3,5,7,9,11,17,22,15,4,99,120,1,3,10};
        System.out.println();
        bubble_sort(array);
        System.out.print("After bubble sort
algorithm:\n");
        for(i = 0; i <array.length; i++)
        System.out.print(array[i]+"  ");
        System.out.println();
       
        int p;
        int array2[] = {12,9,3,5,7,9,11,17,22,15,4,99,120,1,3,10};
        System.out.println();
        selection_sort(array2);
        System.out.print("After selection sort algorithm:\n");
        for(p = 0; p < array2.length; p++)
        System.out.print(array2[p]+"  ");
        System.out.println();
       
        int c;
        int array3[] = {12,9,3,5,7,9,11,17,22,15,4,99,120,1,3,10};
        System.out.println();
        insertion_sort(array3);
        System.out.print("After insertion sort
algorithm:\n");
        for(c = 0; c < array3.length; c++)
        System.out.print(array3[c]+"  ");
        System.out.println();

    }
}


If you see this as useful please subscribe, like it, share it do whatever you want with it.
Have a good one. M.L.


Thursday 23 January 2014

Easy way to get money with Google Adsense

Google Adsense


I started writing blog last year just for fun, but after a while a see that my audience increases from day to day, I think how can I use that and then I find out for Google AdSense.

Google AdSense is great service for you to earn some extra money. If you have a blog or even your own site you can add AdSense. Trick is that you allow Google to add ads on your website and when someone click on it Google will pay you.

Everything you need to do is to write a post and sign up for AdSense. If Google recognize your potential you can start earning money from your home right now!



You may think that is hard, I need to write post every day, NO! You don't need to write a post every day you can write it every once a week like me. You can write about football, programing, future, past or anything and still earn money.

You don't worry about ads on your website because Google will add it for you for every person who comes on your website or blog. Google analyze person who comes on site and add ads specific to that person.

So if that person are looking for hotels and visit my post about hotel Google will add ads about hotels.
If you are looking for programming code for android Google will add ads about programing, you don't need to worry about that. You just need to relax clear your mind and write.

If you have some kind of adblock you can't see ads on my blog, if you see it you can think about what did you search last 10 days on internet, because ads will be about that.

Ads have different prices it depends from ads, they can be 0.02 cents up to 2.00 euro. You can track your income with easy adsense interface integrate in blog or website.

And to see that I don't write nonsense watch this youtube video about Google Adsense.





If you like this post please subscribe for more news or just like it share it, do whatever you want with it. Have a good one. M.L. :)


Friday 10 January 2014

Read Email in Java - Android

The easiest way to read email in Java


If you need to read email from Java app you will need mail library. Most famous library for reading email in java is javax.mail.jar and you can find it on this link. That work fine in simple Java app, but if you want to build Android app to read email you will have a big problem. 

There is a problem with mail.jar when you want to build Android app, some classes in mail.jar don't work and when you deploy your android app on phone you will get some error but code is fine. In order to solve that problem you need to use this jar files: activation.jar, additionnal.jar and mail.jar. Javax mail.jar include activation and additional jars but some classes in that jars aren't working in Android so you must download files from this link.

First you say what protocol you gonna use:
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");

Then you open a connection to your server:
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "mail@gmail.com", "password");

Open inbox with read_write mode:
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);

If you want you can see how much message you have in inbox:
inbox.getMessageCount();

Get message:
Message msg = inbox.getMessage(inbox.getMessageCount());
 
Write all address:
Address[] in = msg.getFrom();
for (Address address : in) {
    System.out.println("FROM:" + address.toString());
} 
 
Write content of message on console:
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
 
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());


You need to put all that in try block and the code will work from simple Java app to Android app.
If you have any questions or need help with coding post a comment bellow.
And if you like this post please share it. Have a good one.

Friday 3 January 2014

Component Based Development - CBD - Java EJB 3.1 - Example

Blog platform in EJB 3.1


Assignment!
We need to create EJB layer for a blog site.

Clients communicate with stateful session bean. It is necessary to implement the method for search blogs and method for setting up a new blog.
In the case of passivation of the stateful session bean , we need just before passivation to print a message on the console about session bean is going to be pasive.
Singleton bean keeps customer information (name , username , password ... ) and data on blogs ( text, date , number of like- s) in ArrayList.
Singleton is NOT instantiated immediately upon deployment, but by the first call. By instantiate initialize ArrayList in which data need to be stored.
If we call the method that is used to search, interceptor intercepts that method and he update statistics (number of views for each blog).
Call method to set up a new blog interceptor intercepts that method and he update statistics on the number of blogs set up during the day
The statistic data is stored in the same Singleton which are stored and other information .
All interceptor's is required to be implemented in a separate class.
It is necessary to implement a timer that starting from 1.1.2014 . Every day at 00:00 timer need to print on console how many visit blog's have that day.

Please share this post if you like it.

Singleton Class

import java.util.ArrayList;
import java.util.Date;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;

/**
 * Developed by codeMaker
 */

@Singleton
@LocalBean
public class Baza implements BazaLocal {

    public ArrayList<Klijent> listaKlijenata = new ArrayList<Klijent>();
    public ArrayList<Blog> listaBlogova = new ArrayList<Blog>();
   
    int brojPB = 0;
   
    public int getBrojPB() {
        return brojPB;
    }
    public void setBrojPB(int brojPB) {
        this.brojPB = brojPB;
    }

    public void setListaBlogova(ArrayList<Blog> listaBlogova) {
        this.listaBlogova = listaBlogova;
    }
    public void setListaKlijenata(ArrayList<Klijent> listaKlijenata) {
        this.listaKlijenata = listaKlijenata;
    }
    public ArrayList<Klijent> getListaKlijenata() {
        return listaKlijenata;
    }
    public ArrayList<Blog> getListaBlogova() {
        return listaBlogova;
    }
    public Baza() {
        // TODO Auto-generated constructor stub
        Klijent klijent = new Klijent("Niki", "Re", "user", "pass");
        listaKlijenata.add(klijent);
        Blog blog = new Blog("tekst", new Date());
        listaBlogova.add(blog);
    }
}


SingletonLocal interface

import java.util.ArrayList;
import javax.ejb.Local;

@Local
public interface BazaLocal {
    ArrayList<Klijent> getListaKlijenata();
    ArrayList<Blog> getListaBlogova();
    void setListaBlogova(ArrayList<Blog> lista);
    void setListaKlijenata(ArrayList<Klijent> lista);
    int getBrojPB();
    void setBrojPB(int brojPB);
}


Klijent class

import java.util.ArrayList;

public class Klijent {

    public String ime;
    public String prezime;
    public String username;
    public String pass;
   
    public ArrayList<Blog> listaBlogova;
   
    public Klijent(String ime, String prezime, String username, String pass) {
        this.ime = ime;
        this.prezime = prezime;
        this.username = username;
        this.pass = pass;
        listaBlogova = new ArrayList<Blog>();
    }

    public String getIme() {
        return ime;
    }
    public void setIme(String ime) {
        this.ime = ime;
    }
    public String getPrezime() {
        return prezime;
    }
    public void setPrezime(String prezime) {
        this.prezime = prezime;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public ArrayList<Blog> getListaBlogova() {
        return listaBlogova;
    }
    public void setListaBlogova(ArrayList<Blog> listaBlogova) {
        this.listaBlogova = listaBlogova;
    }      
}



Blog class

import java.util.Date;

public class Blog {
  
    public String tekst;
    public Date datum;
    public int brojLajkova;
    public int brojPregleda;
   
    public Blog(String tekst, Date datum) {
        this.tekst = tekst;
        this.datum = datum;
        brojLajkova = 0;
        brojPregleda = 0;
    }
    public String getTekst() {
        return tekst;
    }
    public void setTekst(String tekst) {
        this.tekst = tekst;
    }
    public Date getDatum() {
        return datum;
    }
    public void setDatum(Date datum) {
        this.datum = datum;
    }
    public int getBrojLajkova() {
        return brojLajkova;
    }
    public void setBrojLajkova(int brojLajkova) {
        this.brojLajkova = brojLajkova;
    }
    public int getBrojPregleda() {
        return brojPregleda;
    }
    public void setBrojPregleda(int brojPregleda) {
        this.brojPregleda = brojPregleda;
    }


Stateful bean Blogovanje - Clients communicate with him

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.PrePassivate;
import javax.ejb.Stateful;
import javax.interceptor.Interceptors;

@Stateful
@LocalBean
public class Blogovanje implements BlogovanjeRemote {
   
    @EJB BazaLocal baza;
   
    public Blogovanje() {
        

    }
   
    @Interceptors(PretragaInterceptor.class)
    public String pretraga(String upit) {
        List<Blog> lista = baza.getListaBlogova();
        for (Blog b : lista) {
            String tekst = b.getTekst();
            if (tekst.equalsIgnoreCase(upit)) {
                return "Blog je pronadjen!";
            }
        }
        return "Blog nije pronadjen.";
    }
   
    @Interceptors(PretragaInterceptor.class)
    public String postaviBlog(String username, String pass, String tekstBloga) {
       
        int uspjeh = 0;
        ArrayList<Klijent> lista = baza.getListaKlijenata();
        for(Klijent k : lista) {
            String user = k.getUsername();
            String p = k.getPass();
            if((username.equalsIgnoreCase(user)) && (pass.equalsIgnoreCase(p))) {
                Blog b = new Blog(tekstBloga, new Date());
                ArrayList<Blog> listaBlogova = baza.getListaBlogova();
                listaBlogova.add(b);
                baza.setListaBlogova(listaBlogova);
                k.getListaBlogova().add(b);
                uspjeh++;
            }
        }
        baza.setListaKlijenata(lista);
        if (uspjeh > 0) {
            return "Uspeh";
        } else {
            return "Nismo uspjeli da postavimo blog, user i pass ne odgovaraju!";
        }
    }
   
    @PrePassivate
    public void prijePasiviziranja() {
        System.out.println("Jagoda u supermarketu.");
    }
}


BlogovanjeRemote interface - For session bean
Methods in this class will be visible for clients

import javax.ejb.Remote;

@Remote
public interface BlogovanjeRemote {
    String pretraga(String upit);
    String postaviBlog(String username, String pass, String tekstBloga);
}



Interceptors in one class you can build it in seperate classes.

import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class PretragaInterceptor {
   
    @EJB BazaLocal baza;
   
    @AroundInvoke
    public Object brojPregledaStatistika(InvocationContext ic) throws Exception {
       
        String imeMetoda = ic.getMethod().getName();
       
        if (imeMetoda.equalsIgnoreCase("pretraga")) {
        Object [] listaO = ic.getParameters();
        String upit = (String) listaO[0];
       
        List<Blog> lista = baza.getListaBlogova();
        for (Blog b : lista) {
            String tekst = b.getTekst();
            if (tekst.equalsIgnoreCase(upit)) {
                b.setBrojPregleda(b.getBrojPregleda() + 1);
            }
        }
       
        return ic.proceed();
        }
       
        if (imeMetoda.equalsIgnoreCase("postaviBlog")) {
           
            Object [] listaO = ic.getParameters();
            String username = (String) listaO[0];
            String pass = (String) listaO[1];
           
            ArrayList<Klijent> lista = baza.getListaKlijenata();
            for(Klijent k : lista) {
                String user = k.getUsername();
                String p = k.getPass();
                if((username.equalsIgnoreCase(user)) && (pass.equalsIgnoreCase(p))) {
                    baza.setBrojPB(baza.getBrojPB() + 1);
                }
            }
            return ic.proceed();
        }
        return ic.proceed();
    }   
}


Timer class

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerService;

@Startup
@Singleton
@LocalBean
public class IspisTimer {

    @EJB BazaLocal baza;
    @Resource TimerService ts;
   
    @Timeout
    public void ispsi() {
        System.out.println("Danas je postavljeno: " + baza.getBrojPB() + " blogova!");
        baza.setBrojPB(0);
    }
   
    @PostConstruct
    public void startuj(){
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date date = null;
        try {
            date = sdf.parse("31-12-2013 23:59");
        } catch (Exception e) {    }
        ts.createTimer(date, 86400000, null);
    }
}



And Klijent app, so we can test it.

import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import binovi.Blogovanje;
import binovi.BlogovanjeRemote;

public class Klijent {

    static Context initialContext;

    public static void main(String[] args) {
        try {
            Context context = getInitialContext();
            String name = getLookUpName();
            BlogovanjeRemote bean = (BlogovanjeRemote) context.lookup(name);
            System.out.println();
            System.out.println(bean.postaviBlog("user", "pass", "text"));
            System.out.println(bean.postaviBlog("ssa2", "agawa", "text"));
            System.out.println(bean.pretraga("text"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getLookUpName() {

        String appName = "";
        String moduleName = "Blogovanje";
        String distinctName = "";
        String beanName = Blogovanje.class.getSimpleName();
        String interfaceName = BlogovanjeRemote.class.getName();

        String name = "ejb:" + appName + "/" + moduleName + "/" + distinctName
                + "/" + beanName + "!" + interfaceName+"?stateful";

        System.out.println(name);

        return name;
    }

    public static Context getInitialContext() {
           if (initialContext == null) {
            try {
                final Hashtable jndiProperties = new Hashtable();
                jndiProperties.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.ejb.client.naming");
                initialContext = new InitialContext(jndiProperties);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return initialContext;
    }
}


If you have any questions or need help with coding post a comment bellow.
Please share this post if you like it.

Thursday 2 January 2014

Fast screen capture in Java - Example

 Read pixels from screen in Java


If you want to fast read pixels from screen you will need Java class called Robot.
The main purpose of class Robot is to generate native system inputs (mouse, keyboard inputs) for the purpose of test automation. 

If you need to read pixels from screen you can use Robot method called getPixelColor(int x, int y) x and y represents coordinates of pixels you want to grab. Method getPixelColor(...) returns object Color so if you need to now RGB you must use color.getBlue(), color.getGreen(), color.getRed();

This method is good if you want to read 2-3 pixels but if you need to reed a 10x10 pixels from screen i don't recommend using it. Main reason is because getPixelColor is slow, first you read pixel that you create object Color and then you can work with that pixel.

If you want to read 10x10 pixels from screen or more you can use Robot's method called createScreenCapture(Rectangle r); that method returns BufferedImage. First you may think why is he taking Rectangle and returns a image? Method createScreenCapture(...) need to know from which coordinates he must start (x,y) and how much weight and height go right and down.

So you get something like this:
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(new Rectangle(100, 100, 10, 10));

So you can easy capture 10x10 pixels from screen in one line of code, if you want to use getPixelColor in a loop to do that you will need 2 or 3 second for that. (that's a lot!!!)

When you have BufferedImage you can easy save it like "bmp":
ImageIO.write(image, "bmp", new File("Image.bmp"));

If you want to work with pixels you get in BufferedImage you can do it like this:
boolean fail = false;
for (int x = 0; !fail  && x < image.getHeight();  x++) {
                for (int y = 0; !fail  &&  y <
image.getWidth(); y++) {
                    if ( image.getRGB(x, y) != color.getRGB() ) {
                        System.out.println("Pixels are different stop!");
                        fail = true;
                        }
                    }
           }

}
color.getRGB() returns just one color if you need to check are two pictures the same you can use:
if ( image.getRGB(x, y) != image2.getRGB(x, y) 
So if pixels on x, y position on image and image2 are different we stop and write message for that, if we don't get that message fail will stay on false and we can after all this add this:
if (!fail) {
  System.out.println("Pictures are equal!");
}

Robot is powerful class, you can click mouse, keyboard or read pixels from screen.
If you want to learn more about Robot class you can read Java documentation on this link.

If you have any questions or need help with coding post a comment bellow.
And if you like this post please share it. :)