Beginning Java

 

Syntax Notes

 

New Mexico High School Supercomputing Challenge

Summer Teacher Training Session – WNMU

June 18-23, 2000

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Create, Compile, and Run Your Program.. 4

The Program Template. 5

Direct Output to the Screen. 6

Comments. 7

Case Sensitivity and Whitespace. 8

Variables. 9

Variable Example. 10

Data Types. 11

Example Continued …... 12

Constants. 13

Identifiers. 14

Naming Conventions. 15

Arithmetic Operations. 16

Logical Statements. 17

If Statement 18

Else Clause. 19

Nested if Statement 20

Boolean Operators. 21

Else if Statement 22

Loops. 23

For Loop. 24

While Loop. 25\

Do Loop. 26

Arrays. 27

Array Example. 28

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Java – Quick Background

 

Created by Sun Microsystems ~ 1995

 

Can produce applications and applets

 

Java is not Javascript

 

Similar to C (C++) in syntax

 

Major differences between C++ and Java

 

Can get “Java” for free

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Create, Compile, and Run Your Program

 

To write your program use the text editor “pico”

 

mode:~> pico Example.java

 

To compile your program use the “javac” command (creates Example.class)

     

mode:~> javac Example.java

 

To run your program use the “java” command

     

mode:~> java Example

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


The Program Template

 

For a program named “ProgramName.java”, the minimum code is required:

 

class ProgramName

{

      public static void main(String args[])

      {

           

      }

}

 

 

“ProgramName” should be descriptive of what the program does.

The main program body goes between the inner pair of braces.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Direct Output to the Screen

 

Use the command “System.out.println();” and its variants.

 

     

class Hello

{

      public static void main(String args[])

      {

            System.out.println(“Hello World!”);

      }

}

 

 

 

class Add

{

      public static void main(String args[])

      {

            System.out.println(5+7);

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Comments

 

Comments are ignored by the compiler …

 

class ProgramName

{

      public static void main(String args[])

      {

            // Single line comments can appear alone

           

            /* or can span

            multiple lines like this

            message */

      }

}

 

 

Stop!!  Do Exercise 1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Case Sensitivity and Whitespace

 

Java is a Case Sensitive language!

 

Ex. Class != class (will get an error while compiling)

 

 

 

Compiler Ignores most whitespace. Better to structure into statements and code blocks for your benefit.

 

Use semicolons after statements! (not after “block headers” in general)

 

 

class Hello

{

      public static void main(String args[])

      {

            System.out.println(“Hello World!”);

     }

}

 

class Hello {public static void main(String args[]) {System.out.println(“Hello World!”);}}

 

The above programs do the same thing!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Variables

 

A name that stands for a data value. Rather than entering data directly into a program, a programmer can use variables to represent the data. This make the program more readable.

 

When the program is executed, the variables are replaced with real data. This makes it possible for the same program to process different sets of data, making the program more flexible.

 

 

General syntax:

 

data_type identifier; // reserves a named location in memory

 

(or)

 

data_type identifier=initial_value; // initializes memory location

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Variable Example

 

 

class Box // no variables

{

      public static void main(String args[])

      {

            System.out.print(“The volume is: ”);

            System.out.println(5*7*2);

      }

}

 

 

class Box // with variables

{

      public static void main(String args[])

      {

            int length=5;

            int width=7;

            int height=2;

            int volume;

 

            volume=length*width*height;

            System.out.println(“The volume is: ” + volume);

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Data Types

 

Integral types (whole numbers)

byte        (-128, 127)

short       (-32768, 32767)

int         (+- 2 billion)    Use This!

long        HUGE

 

Floating Point types (decimal numbers)

float       (+- 3E38 6-7 digits of accuracy)

double      (+- 1E308 15 digits of accuracy)       Use This!

 

Boolean type
boolean     (“true” or “false”)

 

Strings
String      (“Sequence_of_Characters”)

 

Character type
Char        (One Character)

 

 

 

Note: literal values are assumed to be either int or double!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Example Continued …

 

class Box // with more variables

{

      public static void main(String args[])

      {

            String s=”The volume is: ”;

            int length=5;

            int width=7;

            int height=2;

            int volume;

 

            volume=length*width*height;

            System.out.println(s + volume);

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Constants

 

Constants are variables (named locations in memory) where you do not want the data to be changed.

 

Use the final keyword before the variable declaration.

 

Ex.

 

final double PI=3.14159265359;

 

 

Compiler won’t allow the value to be changed during runtime.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Identifiers

 

First character must be: A-Z, a-z, _, $

 

All others include the former and 0-9

 

(Same with program name (except don’t use $))

 

 

Can’t use keywords!

 

abstract      boolean       break         byte          case          catch    char

class         const         continue      default       do            double   else

extends       false         final         finally       float         for      goto

if            implements    import        instanceof    int           interface

long          native        new           null          package       private  protected

public        return        short         static        strictfp      super    switch

synchronized  this          throw         transient     true          try      void

volatile      while

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Naming Conventions

 

Class (Program) Name – Descriptive words, capitalization on first letter of each word

 

Ex. BoxVolume

 

Variable Name – Descriptive words, capitalization on first letter of every word after the first word

 

Ex. boxVolume

 

Constant Name – All capital letters

 

Ex. PI

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Arithmetic Operations

 

 

5 basic operators:

 

+, -, *, /, %

 

Note: When “+” is used with a String it concatenates the arguments!

 

 

Order of operations apply.

 

()’s inside to outside

*, / left to right

+, - left to right

 

 

Increment and decrement operators ++ and –- respectively

Ex. j++; same as j=j+1; (similar with --)

 

Other shorthand operators +=, -=, *=, /=

Ex. j+=num; same as j=j+num;

 

 

 

Stop!!  Do Exercise 2

 

 

 

 

 

 

 

 

 

 

 


Logical Statements

 

Logical (conditional) statements allow you to make decisions about whether or not to execute a particular block of code based upon logical expressions

 

Logical expressions produce a true or false (Boolean) result.

 

Use relational operators: >   >=    ==    !=    <=    <

                 

Example:

 

 

class Bool

{

      public static void main (String args[])

      {

            boolean test;

            test = (75 < 50);

            System.out.println(test);

}

}

 

Output:

 

false

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


If Statement

 

General Syntax:

 

if (expression)

{

      //code to execute if expression is true

}

 

 

Example:

 

class Grade // This is preferred over the next program

{

      public static void main (String args[])

      {

            int grade = 75;

            if (grade >= 60)

            {

                  System.out.println(“You pass the class!”);

            }

      }

}

 

or

 

class Grade // The previous program is preferred

{

      public static void main (String args[])

      {

            int grade = 75;

            boolean pass;

 

            pass = (grade >= 60);

            if (pass)

            {

                  System.out.println(“You pass the class!”);

            }

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Else Clause

 

General Syntax

 

if (expression)

{

      // code to execute if expression is true

}

else

{

      // code to execute if expression is false

}

 

Example:

 

class Grade

{

      public static void main (String args[])

      {

            int grade = 43;

            if (grade >= 60)

            {

                  System.out.println(“You pass the class!”);

            }

            else

            {

                  System.out.println(“Sorry, you fail …”);

            }

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Nested if Statement

 

Example:

 

class Grade

{

      public static void main (String args[])

      {

int grade=85;

            if (grade >= 60)

            {

if (grade >= 80)

                  {

                        System.out.println(“Excellent Work!”);

                  }

                  else

                  {

                        System.out.println(“Satisfactory Work.”);

                  }

            }

            else

            {

                        System.out.println(“You fail the class …”);

            }

}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Boolean Operators

 

&& (and), || (or), ! (not)

 

Example

 

class Grade

{

      public static void main (String args[])

      {

            int grade=85;

            if ((grade >= 60) && (grade <= 80))

            {

                  System.out.println(“Satisfactory Work.”);

            }

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Else if Statement

 

class Grade

{

      public static void main (String args[])

      {

            int grade=73;

 

            if (grade >= 90)

            {

                  System.out.println(“A”);

            }

            else if (grade >= 80)

            {

                  System.out.println(“B”);

            }

            else if (grade >= 70)

            {

                  System.out.println(“C”);

            }

            else

            {

                  System.out.println(“Unsatisfactory”);

            }

      }

}

 

 

 

Stop!!  Do Exercise 3

 

 

 

 

 

 

 

 

 

 

 

 


Loops

 

Loops allow you to repeat a block of code as many times as you wish.

 

There are three types of loops – all which can be used to accomplish the same task.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


For Loop

 

 

General Syntax:

 

for (initialization_expression; loop_condition; increment expression)

{

      // code to repeat

}

 

example:

 

class SumUp

{

      public static void main (String args[])

      {

            int limit=20;

            int sum=0;

 

            for (int j=1; j<=limit; j++) // j++ shorthand for j=j+1

            {

                  sum+=j; // this is the same as sum=sum+j

            }

            System.out.println(“Sum of first 20 integers is: “ + sum);

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


While Loop

 

General Syntax:

 

while (condition)

{

      // code to repeat

}

 

example

 

class SumUp2

{

      public static void main (String args[])

      {

            int integer=1;

            int limit=20;

            int sum=0;

 

            while (integer <= limit)

            {

                  sum+=integer;

                  integer++;

            }

            System.out.println(“Sum of first 20 integers is: “ + sum);

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Do Loop

 

General Syntax:

 

do

{

      // code to repeat

} while (condition); // notice the semicolon!

 

example

 

class SumUp3

{

      public static void main (String args[])

      {

            int integer=1;

            int limit=20;

            int sum=0;

 

            do

            {

                  sum+=integer;

                  integer++;

            } while (integer <= 20);

            System.out.println(“Sum of first 20 integers is: “ + sum);

      }

}

 

 

Stop!!  Do Exercise 4

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Arrays

 

Memory Constructs which allow for storage of multiple values in a single contiguous unit.

 

Uses a single identifier (for the array) and an index number (for the value within an array).

 

0

1

2

3

4

79

84

52

87

66

 

                                                                                    “Bill_Exam”

 

 

Bill_Exam[0]=79, Bill_Exam[1]=84, Bill_Exam[2]=52 …

 

Arrays also have a length: Bill_Exam.length=5

 

Declaring Arrays: int Bill_Exam[]=new int[5]; // reserves memory space

                                                        Bill_Exam[0]=79;

                                                        Bill Exam[1]=84;

                                                                    Etc.

Note: Before elements are given specific values, the array is filled with all “zeros”.

 

                                  (or) int Bill_Exam[]={79,84,52,87,66};

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Array Example

 

 

class Grade

{

      public static void main(String args[]) // ?

      {

            int bill_grade[]={79,84,52,87,66};

            double fin_grade; // why not “final”

            int temp=0;

 

            for (int j=0; j < bill_grade.length; j++)

            {

                  temp+=bill_grade[j];

            }

            fin_grade=temp/bill_grade.length;

            System.out.println(“Bill\’s final grade is: “ + fin_grade);

      }

}

 

 

     

                                   

                 How would we do this program otherwise?

 

                         What are the benefits?

 

 

 

Stop!!  Do Exercise 5