Difference between revisions of "Your First Java Program"

From CompSciWiki
Jump to: navigation, search
(added solutions link)
(Other Conventions: added section for other conventions)
 
(11 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{1010Chapter|Introduction=In chapter 2, you learned what programming is. This chapter will cover the basics of Java programming and give you enough information to write your first Java program.
+
{{1010Topic | Introduction=Every programming language has a unique syntax and structure. This section will introduce you to the anatomy of a Java program.|Overview=In this section, you will learn about the basic building blocks that make up a Java program. You do not need to understand everything that is covered in this section. The point of this section is to give you a basic understanding of how a Java program is structured. Topics, such as methods and variables, will be covered in later sections. |Chapter_TOC=[[Java Fundamentals]]}}
}}
+
__NOTOC__
+
  
==[[Anatomy of a Java Program]]==
+
=A Simple Example of a Java Program=
  
==[[Comments]]==
+
<pre>
 +
public class JavaProgram
 +
{
 +
  public static void main(String args[])
 +
  {
 +
    System.out.println("This is what a Java program looks like");
 +
  }
 +
}
 +
</pre>
  
==[[Output using System.out.]]==
+
=Classes=
 +
The first line is called the class header. A class groups together the components of an object. Do not worry about what an object is right now; they will be covered in COMP1020. For now, just think of a class as a container for the rest of your code. After the class header, we write an opening curly brace (<code>{</code>), followed by some methods or variables, and then a closing curly brace (<code>}</code>). When you create a new program, you will first declare a class. The rest of your code will then be contained inside of the two braces.
  
==[[Input using JOptionPane]]==
+
In the above example, JavaProgram is the name of the class. When you save a Java file it must be named ''classname''.java (where ''classname'' is the name of the class). In the example, we would save the file as JavaProgram.java
  
==[[Variables and Literals]]==
 
  
==[[Common Primitive Variables]]==
+
=Methods and the Main Method=
 +
A method is a block of code that performs a certain task. To declare a method, we write a method header followed by an opening curly brace, some code called the method body, followed by a closing curly brace.
  
==[[Arithmetic Operators]]==
+
Below is an example of a method. This method performs the task of printing a message to the screen and returning <code>1</code> to the caller.
 +
<pre>
 +
public int printMessage(String message)
 +
{
 +
  System.out.println(message);
  
==[[Strings]]==
+
  return 1;
 +
}
 +
</pre>
 +
Now, we will explain the components of a method header.
 +
*Scope: The keyword ''public'' allows other classes to call our method. Alternatively, we could have used the keyword ''private'' to deny other classes access to our method.
 +
*Return type: When our method completes it can return data to the caller (the statement that called our method). We must declare the type of data that our method returns. In the ''printMessage'' method, we used the keyword ''int'' to declare that our method returns data of type integer. If we do not want our method to return anything we can use the keyword ''void''.
 +
*Name: We must give our method a unique name. The name of the method shown above is ''printMessage''.
 +
*Parameters: We can pass data to a method. The data that we pass to a method are called parameters. Parameters are declared inside of round brackets. Each parameter must have a type and a name (just like when we declare a variable). If we do not want to have any parameters, we just put a set of round brackets with nothing inside.
  
==[[Increment and Decrement Operators]]==
+
== The Main Method ==
  
==[[Casting]]==
+
The main method header has the following form:
  
==[[Named Constants]]==
+
<pre>
 +
public static void main(String args[])
 +
{
 +
   
 +
}
 +
</pre>
  
==[[Your_First_Java_Program_Review_Questions_and_Exercises|Review Questions and Exercises]]==
+
The main method is a special method in Java, and every Java program must have one. This is because the program starts running on the first line of the main method.
  
==[[Solutions]]==
+
The main method must be declared inside of a class. After the header of the main method (and all other Java methods), we write opening and closing curly braces (just like when we define a class).
  
{{Category:COMP 1010}}
+
The meaning of '''static''' will be discussed in a later chapter.
 +
 
 +
 
 +
=Statements=
 +
An instruction in Java is called a statement. A statement is a single line of code that performs a task. All statements must end with a semicolon. In the first example program, the following statement prints "This is what a Java program looks like" to the screen:
 +
<pre>
 +
System.out.println("This is what a Java program looks like");
 +
</pre>
 +
 
 +
 
 +
=Packages and the import Statement=
 +
A package is used to group a set of classes together. When you create a new class it will be placed in the default package. However, you cannot access classes outside of your package without importing them, such as the classes that come with Java. The import statement will allow you to use classes that are in another package.
 +
 
 +
 
 +
The general syntax of an import statement is:
 +
<pre>
 +
import example.package.class;
 +
</pre>
 +
 
 +
Where ''example.package'' is the name of the package you want to import, and ''class'' is a class within that package.
 +
 
 +
 
 +
This is an example of how to import a specific class.
 +
<pre>
 +
import javax.swing.JOptionPane;
 +
</pre>
 +
Here we import the JOptionPane class which is part of the javax.swing package. Now our program will be able to use JOptionPane.
 +
 
 +
 
 +
We can specify that we want to include all the classes of a package by using the <code>*</code> symbol as demonstrated below.
 +
<pre>
 +
import javax.swing.*
 +
</pre>
 +
 
 +
This will import all classes from the '''javax.swing''' package.
 +
 
 +
import statements should be placed at the very beginning of the file (above the class header).
 +
 
 +
 
 +
=Case Sensitivity=
 +
Java is a case sensitive programming language. This means that it distinguishes between letters that are typed in upper case and letters that are typed in lower case. For example, if you type '''Main''', this is not the same as typing '''main'''.
 +
 
 +
 
 +
=Naming Guidelines=
 +
How you name your classes, variables, and methods is largely a matter of convention. Here we will discuss some of these conventions.
 +
 
 +
==Class Naming==
 +
A class name should be a noun that starts with a capital letter. The first letter of each word should also be capitalized.
 +
<pre>
 +
public class Tetris
 +
</pre>
 +
<pre>
 +
public class DayPlanner
 +
</pre>
 +
 
 +
==Method Naming==
 +
A [[Calling Methods|method]] name should be a verb phrase that indicates what the method does. The first letter of each word (except the first word) should be capitalized.
 +
<pre>
 +
public void rotate()
 +
</pre>
 +
<pre>
 +
public int getCurrentPosition()
 +
</pre>
 +
 
 +
==Constant Naming==
 +
A [[Named Constants|constant]] name should be a noun phrase with all capital letters with an underscore between words.
 +
<pre>
 +
public static final double PI = 3.14159265l;
 +
</pre>
 +
<pre>
 +
public static final int MELTING_POINT = 0;
 +
</pre>
 +
 
 +
==Variable Naming==
 +
A [[Variables and Literals|variable]] name should be a noun phrase. The first letter of each word after the first should be capitalized.
 +
<pre>
 +
int day;
 +
</pre>
 +
<pre>
 +
String firstName;
 +
</pre>
 +
<pre>
 +
double distanceToTheMoon;
 +
</pre>
 +
 
 +
==Other Conventions==
 +
A complete list of the conventions used in COMP 1010 is available on the [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 course website].

Latest revision as of 13:58, 2 December 2007

COMP 1010 Home > Java Fundamentals


Introduction

Every programming language has a unique syntax and structure. This section will introduce you to the anatomy of a Java program.

   

{{{Body}}}

A Simple Example of a Java Program

public class JavaProgram
{
  public static void main(String args[]) 
  {
    System.out.println("This is what a Java program looks like");
  }
}

Classes

The first line is called the class header. A class groups together the components of an object. Do not worry about what an object is right now; they will be covered in COMP1020. For now, just think of a class as a container for the rest of your code. After the class header, we write an opening curly brace ({), followed by some methods or variables, and then a closing curly brace (}). When you create a new program, you will first declare a class. The rest of your code will then be contained inside of the two braces.

In the above example, JavaProgram is the name of the class. When you save a Java file it must be named classname.java (where classname is the name of the class). In the example, we would save the file as JavaProgram.java


Methods and the Main Method

A method is a block of code that performs a certain task. To declare a method, we write a method header followed by an opening curly brace, some code called the method body, followed by a closing curly brace.

Below is an example of a method. This method performs the task of printing a message to the screen and returning 1 to the caller.

public int printMessage(String message)
{
  System.out.println(message);

  return 1;
}

Now, we will explain the components of a method header.

  • Scope: The keyword public allows other classes to call our method. Alternatively, we could have used the keyword private to deny other classes access to our method.
  • Return type: When our method completes it can return data to the caller (the statement that called our method). We must declare the type of data that our method returns. In the printMessage method, we used the keyword int to declare that our method returns data of type integer. If we do not want our method to return anything we can use the keyword void.
  • Name: We must give our method a unique name. The name of the method shown above is printMessage.
  • Parameters: We can pass data to a method. The data that we pass to a method are called parameters. Parameters are declared inside of round brackets. Each parameter must have a type and a name (just like when we declare a variable). If we do not want to have any parameters, we just put a set of round brackets with nothing inside.

The Main Method

The main method header has the following form:

public static void main(String args[]) 
{
    
}

The main method is a special method in Java, and every Java program must have one. This is because the program starts running on the first line of the main method.

The main method must be declared inside of a class. After the header of the main method (and all other Java methods), we write opening and closing curly braces (just like when we define a class).

The meaning of static will be discussed in a later chapter.


Statements

An instruction in Java is called a statement. A statement is a single line of code that performs a task. All statements must end with a semicolon. In the first example program, the following statement prints "This is what a Java program looks like" to the screen:

System.out.println("This is what a Java program looks like");


Packages and the import Statement

A package is used to group a set of classes together. When you create a new class it will be placed in the default package. However, you cannot access classes outside of your package without importing them, such as the classes that come with Java. The import statement will allow you to use classes that are in another package.


The general syntax of an import statement is:

import example.package.class;

Where example.package is the name of the package you want to import, and class is a class within that package.


This is an example of how to import a specific class.

import javax.swing.JOptionPane;

Here we import the JOptionPane class which is part of the javax.swing package. Now our program will be able to use JOptionPane.


We can specify that we want to include all the classes of a package by using the * symbol as demonstrated below.

import javax.swing.*

This will import all classes from the javax.swing package.

import statements should be placed at the very beginning of the file (above the class header).


Case Sensitivity

Java is a case sensitive programming language. This means that it distinguishes between letters that are typed in upper case and letters that are typed in lower case. For example, if you type Main, this is not the same as typing main.


Naming Guidelines

How you name your classes, variables, and methods is largely a matter of convention. Here we will discuss some of these conventions.

Class Naming

A class name should be a noun that starts with a capital letter. The first letter of each word should also be capitalized.

public class Tetris
public class DayPlanner

Method Naming

A method name should be a verb phrase that indicates what the method does. The first letter of each word (except the first word) should be capitalized.

public void rotate()
public int getCurrentPosition()

Constant Naming

A constant name should be a noun phrase with all capital letters with an underscore between words.

public static final double PI = 3.14159265l;
public static final int MELTING_POINT = 0;

Variable Naming

A variable name should be a noun phrase. The first letter of each word after the first should be capitalized.

int day;
String firstName;
double distanceToTheMoon;

Other Conventions

A complete list of the conventions used in COMP 1010 is available on the course website.