Java
Java intro
Java basics
Java variables
Java conditionals
Java loops
Java arrays
Java OOP 1
Java OOP 2
Java interfaces
Java Strings
Java user input
Java exceptions
Java packages
Java rand numbers
Java GUI's
Java GUI layout
Java events
Java applets
Java graphics
Java sounds
Java summary

Programming

Programming intro

Markup

First webpage guide HTML
XHTML

Style & Layout

CSS

Browser scripting

Javascript
VBScript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

Java basics

This lesson focuses on:

The fundamental elements of a Java program

The source code of every Java program has to have a few fundamental elements.

Every Java program should have:

Printing text

To print text in a Java program, you can use either the System.out.print() method to print a single line of text or the System.out.println() method to print a single line of text followed by a line break.

Syntax:

System.out.print("textToPrint");

System.out.println("textToPrint");

Example:

class PrintText{

public static void main(String[] args){
 
 	System.out.println("Here is some text");
        System.out.print("Here is some more text");      

   }

}

Output:

Here is some text
Here is some more text

The above code uses the System.out.println() method to print out one line of text followed by a line break, and then the System.out.print() method to print out another line of text.

NOTE: Every line of code in a Java program must end with a semicolon. If you don't end a line of code with a semicolon, an error will be generated!

Including comments in Java code

Comments in Java are declared so that code would be easier to understand and to navigate. Comments are not seen within code and can be placed anywhere within it. You can have single line comments and multi line comments.

Single line comments

Single line comments in Java are declared with two / symbols.

Example:

class PrintText{

public static void main(String[] args){

	//print a single line of text
        //followed by a line break
 	System.out.println("Here is some text");

       	//print another line of text
        //with no line break afterwards
        System.out.print("Here is some more text");      

   }

}

Output:

Here is some text
Here is some more text

NOTE: Single line comments can span only a single line.

Multi line comments

Multi line comments in Java are declared with a starting /* and an ending */

Example:

/*
This is a multi-line comment

This program will print
two lines of text 

This multi-line comment
contains seven lines
*/

class PrintText{

public static void main(String[] args){

 	System.out.println("Here is some text");
        System.out.print("Here is some more text");      

   }

}

Output:

Here is some text
Here is some more text

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments