Lesson 2: Java basics

Anatomy of a Java program

A Java program would consist of basic parts, for example the main method. Every java program has to have it in order to get the program complied, but what do we write in the java file?Basically, it is going to include:

Variables

Statements

Input/output

Loops (for and while)

Decision statements (if else)

File input and output

Comments and other methods

Here is an example:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */     comments
package javaexample;
import java.util.Scanner;  // import library 
public class JavaExample {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int num1,num2,sum;  //variables
        Scanner in=new Scanner(System.in); 
        System.out.println("Please input two integer numbers!"); 
        num1=in.nextInt(); num2=in.nextInt(); //read two integer numbers
        sum=num1+num2; //add them up
        System.out.println("The sum of the two numbers you entered is "+ sum); //output the sum
    }
}

Basically what this program does is taking two integer numbers in and add them up to print out the sum of them.

Data Type

Every variable we define must be declared with a data type, as java is known as a strict data typing language. And you can not change the type of the date stored in the variable.

Primitive data type

Characters:   char letter=’B’;

Boolean: isTrue=false;  (isTrue can be true as well!)

Integers byte,short,int, and long;

Rational numbers: float, double;

Like the previous example, we define two variables as int(Integer) in order to find the sum of them. You will get an error if you try to input rational numbers, but if you define them as float, you won’t get the error when you input two integers.

Exercise

1 Play with the previous example to see what happen if you try to input two rational numbers.

2 Define the two variables as float or double, see what happen if you try to input two integer numbers.

3 Create a simple calculator that enables you to do addition, subtraction, multiplication and division between any two real numbers.

Strings

String is technically not a primitive data type.

A sequence/array characters can be stored in a string variable.

For instance, we can say

String aString=”Hello World”; but not char achar=”Hello World”

Remember that a char variable can only store one character.

Exercise

1 Instead of printing out “Hello World “ directly, try to print out a string variable that stores the value of “Hello World”.

Arrays

Imagining that you are shopping in a supermarket, and you want to write a program that create a list of the goods. You have to store the name of the product as well as the price in some variables. It is okay if you have only a few items when you only need to create a few variables to store them. But what if you have hundreds or thousands of items to deal with?

Then you need a array.

An array uses one variable name for multiple values, and this is how we define an array.

data type[] variable name= new data type[size];

the data type on the left hand side has to be the same as the data type on the right hand side.

For instance, you can create arrays like

    String[] Name=new String[1000];
    float[] price=new float[1000];

To store the names and prices of 1001(why?) items. Note that an array can only store the data type that it is declared with.

Array must be declared with the size. And it is accessed with an index value(Integers)starting from 0. As a array always has a fixed size, if you want to access the array with an index value which is larger than the size of array, you will get an “out of bounds” exception.

Here is an example(it is used to calculate the total price as well as the average of the items in the shopping list, and this version is not good enough. You will learn a better approach when you get to the loop part)

package shoppinglist;

import java.util.Scanner;

public class ShoppingList {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        float[] price=new float[6]; 
        float total,average;
        System.out.println("Please input the prices of 6 items.");
        price[0]=in.nextFloat();
        price[1]=in.nextFloat();
        price[2]=in.nextFloat();
        price[3]=in.nextFloat();
        price[4]=in.nextFloat();
        price[5]=in.nextFloat();
        total=price[0]+price[1]+price[2]+price[3]+price[4]+price[5];
        average=total/6;
        System.out.println("The total price of the items is "+total);
        System.out.println("The average price of the items is "+average);        
       // System.out.println(price[11]);                
   }  
}

I have also included a line that it is trying to print the element of index 11 in the price array. You can uncomment it and see what it does when running.

Exercise

  1. Amend the example and make it do the calculation for ten items.
  2. Write a program that asks for your home address line by line then prints it out in the same order as you enter your address.