1. Due tipi di commenti
Dovremmo aggiungere alcune parole a quanto detto sopra.
In Java puoi scrivere comandi, ma puoi anche aggiungere commenti a quei comandi direttamente nel codice. Il compilatore ignora completamente i commenti. Quando il programma viene eseguito, tutti i commenti vengono omessi.
Ecco un esempio:
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");
}
}
Abbiamo aggiunto il commento 'Ora mostreremo la frase…'. L'inizio del commento è indicato da una coppia di simboli ( /*
) e la fine da ( */
). Quando il programma viene compilato, il compilatore omette tutto tra i simboli /*
e*/
Puoi scrivere quello che vuoi all'interno di un commento.
Di solito, i commenti nel codice riguardano parti del codice difficili da comprendere. Alcuni commenti consistono in dozzine di stringhe: queste sono spesso scritte prima dei metodi per descrivere le sfumature del loro funzionamento.
C'è un altro modo per aggiungere un commento al codice. È possibile utilizzare due barre ( //
).
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");
}
}
Qui, il codice che inizia con //
e fino alla fine della riga con //
è considerato un commento. In altre parole, non esiste una seconda coppia di simboli utilizzati per "completare il commento".
2. Commenti dalla vita dei programmatori
A proposito, alcuni commenti sono davvero interessanti.
// 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.
Sì, alcuni commenti sono molto divertenti.
GO TO FULL VERSION