1. To typer kommentarer

Vi bør legge til noen ord til det som ble sagt ovenfor.

I Java kan du skrive kommandoer, men du kan også legge til kommentarer til disse kommandoene rett i koden. Kompilatoren ignorerer kommentarene fullstendig. Når programmet kjøres, er alle kommentarene utelatt.

Her er et eksempel:

public class Home
{
   public static void main (String[] args)
   {
      /*
      Now we'll display the phrase 'Amigo is the Best'
      */
      System.out.print("Amigo ");
      System.out.print("is the ");
      System.out.print("Best");
   }
}

Vi la til kommentaren "Nå viser vi uttrykket...". Begynnelsen av kommentaren er indikert med et par symboler ( /*), og slutten – med ( */). Når programmet er kompilert utelater kompilatoren alt mellom symbolene /*og*/

Du kan skrive hva du vil i en kommentar.

Vanligvis handler kommentarer i kode om deler av koden som er vanskelig å forstå. Noen kommentarer består av dusinvis av strenger: disse er ofte skrevet før metoder for å beskrive nyanser i hvordan de fungerer.

Det er en annen måte å legge til en kommentar i koden. Du kan bruke to skråstreker fremover ( //).

public class Home
{
   public static void main (String[] args)
   {
      System.out.print("Amigo ");
      System.out.print("is the "); // This is also a comment
      System.out.print("Best");
   }
}

Her regnes koden som starter med //og opp til slutten av linjen med en kommentar. //Med andre ord, det er ingen andre symbolpar som brukes for å "fullføre kommentaren".


2. Kommentarer fra programmerernes liv

Noen kommentarer er forresten veldig interessante.

// I'm not responsible for this code. I was forced to write it against my will.
// Dear, future me. Please forgive me for this code.
// If I see something like this once more, I'll have a complete mental breakdown at work.
// If this condition is ever satisfied, please inform me for a reward. Phone: xxx-xxx-xxx.
//
// Dear programmer:
//
// When you finish 'optimizing' this subroutine
// and realize what a huge mistake it was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 42
//
// When I wrote this, only God and I understood what I was doing
// Now only God knows.
// Sometimes it seems that the compiler is just ignoring all my comments
// I dedicate all my code and my work to my wife Darlene,
// who will have to provide for me, our three kids, and the dog when
// it gets released to the public.
// Magic. Don't touch.

Ja, noen kommentarer er veldig morsomme.