0% found this document useful (0 votes)
3 views

01 IntroToJava

Uploaded by

ronald.greaves
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

01 IntroToJava

Uploaded by

ronald.greaves
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

INTRODUCTION TO JAVA

Introduction to Java .............................................................................................................................................. 1


A Bit About Java ................................................................................................................................................................... 1
To Write & Run a Java Program .................................................................................................................................... 1
JRE vs. JDK (SDK) ................................................................................................................................................................ 1
The Compilation Process ................................................................................................................................................. 2
Point to Note ......................................................................................................................................................................... 2
Anatomy of a Simple Java Program ............................................................................................................................. 3
Naming & Coding Conventions ..................................................................................................................................... 3
Arrays in Java .......................................................................................................................................................... 4
Declaration an Array Variable ....................................................................................................................................... 4
Creating an Array ................................................................................................................................................................ 5
Accessing Array Elements ............................................................................................................................................... 5
Multidimensional Arrays ................................................................................................................................................. 6
Useful to Know ..................................................................................................................................................................... 7
Input & Output in Java ......................................................................................................................................... 8
Screen Output ....................................................................................................................................................................... 8
Formatted Output ............................................................................................................................................................... 8
Console Input Using the Scanner Class ...................................................................................................................... 9
String Concatenation ......................................................................................................................................................... 9
Introduction to Java

A Bit About Java

Java was first developed in 1991 for small appliances. It is an object-oriented programming
language. It is platform independent which means you can a Java program on one platform (e.g.
Windows) and run it on another (e.g. Linux or Mac).

It can be used to create both web and desktop applications and the code itself looks similar to that
of the C++ language.

Like C++, Java provides a library of pre-defined functions which programmers may used in building
their programs. This library is called the Application Programming Interface (API) and contains
more than 2700 classes. Every Java program utilizes code in the Java API.

To Write & Run a Java Program

To write & run Java programs, you need:

 Text editor or Integrated Development Environment (IDE)


 Java Development Kit (JDK)

The JDK (Java Development Kit) contains the fundamental tools needed for compiling, running,
documenting and archiving Java code:

 a Java compiler (javac.exe is used for compiling)


 a Java Virtual Machine (java.exe is used for running Java programs)
 the Application Programming Interface (API).

All of the tools are command-line based.

JRE vs. JDK (SDK)

Note that JDK is an older name for the Java SDK (Software Development Kit).

 The Java Software Development Kit (SDK) contains three tools: a Java compiler, a Java
Virtual Machine, and the API. It can be used to create and run Java programs.

 The Java Runtime Environment (JRE) contains two tools: a Java Virtual Machine and the
API. Only used to run existing java programs. There is no compiler. `Therefore, it cannot
be used to create programs – only run existing ones.

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 1
The Compilation Process

The diagram below (by Dr Colin Depradine), outlines the steps in the compilation process.

Plain Text Editor or


Integrated Development

.java File

Java Compiler javac.exe

.class File (byte codes)

Java Virtual Machine java.exe


(Interpreter)

1. Code is developed in either a plain text editor or an IDE.

2. It is saved to a file with a .java extension.

3. The Java compiler (javac.exe) checks the code for syntax errors.

4. Upon successful compilations (i.e. no errors found) a .class file is produced.

5. This .class file is passed to the Java Virtual Machine (java.exe) for execution.

For more details about installing and running Java programs, ensure that you work through the
Running Java Programs handout.

Point to Note

 Java is case sensitive – even for file names.

 When naming files, they must have a .java extension. Example: HelloWorld.java

 When they are compiled, a .class file will be created. Example: HelloWorld.class

 Files names should match the name of the class which contains the main function.

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 2
Anatomy of a Simple Java Program

A java program is essentially a class definition with a function (method) called main. This main
method is the entry point for every Java program. The simple program below will output a “Hello
WORLD” message to the screen.

public class HelloWorld


{
public static void main( String args[] )
{
System.out.println("Hello WORLD”);
}
}

Your program may be composed of multiple class definitions. However, there can be only one which
contains the main method.

Note: no global variables are to be used. Everything needs to be in a class.

Naming & Coding Conventions

There are some naming and coding conventions which you will be expected to follow. The main
points are:

 All class names start with an uppercase letter.

 All method names start with a lowercase letter followed by uppercase for internal words.
This is also known as lower camel case.

Example: setBookTitle()

 Lower camel case is also to be used in naming fields.

 Constants are written entirely in uppercase letters. If the constant name is made up of
multiple words, they are separated by underscores.

Example: MAX_LIMIT

The points outlined above are only a sample. Please ensure that you go through the Naming
Conventions and Coding Conventions handouts for further details.

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 3
Arrays in Java

Recall:

 An array is a container that holds a fixed number of values all of the same type.
 Once created, the length of an array is fixed i.e. the size is static.
 Values in an array are stored in consecutive, back-to-back locations in the computer’s
memory.
 Each location or element in the array has the same data type, therefore they occupy the
same amount of space.
 Each element in an array can be referenced using a unique number called a subscript or
index, which indicates the element’s position in the array.
 All array subscripts are positive integers.
 The first element is always assigned subscript 0.
 The last subscript is always one less than the size of the array.
 Each element in an array is referenced using the array name and the element’s subscript.

Declaration an Array Variable

An array must be declared before it can be used. To declare an array, you need to specify the data
type, followed by square brackets and the array name.

Example: //declares an array of integers


int[] numArray;

//declares an array of strings


String[] stringArray;

You can also place the brackets after the array's name. However, note that this form is discouraged
as the brackets identify the type and should appear with the type description.

Example: //this form is discouraged


int numArray[];

Unlike C++, declaring an array in Java does not create it (i.e. does not allocate memory
space to it).

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 4
Creating an Array

One way to create an array is with the new operator.

Example: //allocate enough memory for 10 integers


numArray = new int[10];

If this statement is missing, then compilation fails and an error, like the following, is printed:

ArrayDemo.java:4: Variable numArray may not have been initialized.

Accessing Array Elements

Array elements may be accessed in a similar fashion to that of C++, using the array name and the
subscript.

Example: numArray[0] = 125; //set value of first element to 125


numArray[1] = 150; //set value of second element to 150

//display values stored in first and second elements


System.out.println("Element at index 0: " + numArray[0]);
System.out.println("Element at index 1: " + numArray[1]);

Alternatively, you can create and initialize an array at the same time as follows:
//this array will be set to a size of 6
int[] anArray = {
100, 200, 300,
400, 500, 600,
};

Note that in this case, the length of the array is determined by the number of values
provided. The size of the array will be fixed once set.

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 5
Multidimensional Arrays
Multidimensional arrays (an array of arrays) may be declared by using two or more sets of brackets.
Example 1: float[][] prices = new float[3][4];

prices[0][0] = 3.75;
prices[0][1] = 2.56;
prices[2][2] = 4.19;
prices[0][3] = 1.99;

 The code above creates a 2-dimensional array which has 3 rows and 4 columns.
 Each position in the 2-D array will hold a floating point value.
 Elements are accessed using the format: array-name[row-index][column-index].
 Every element will be initialized to the default value of 0.0.
 The 2-D array conceptually looks like the diagram below:

0 1 2 3

0 3.75 2.56 0.0 1.99

1 0.0 0.0 0.0 0.0

2 0.0 0.0 4.19 0.0

Example 2: String[][] greatGuys = { Output:


{“Fred”, “Barney”, “Dino”} Fred Flintstone
{“Flintstone”, “Rubble”} Barney Rubble
}; Dino

System.out.println(greatGuys[0][0] + greatGuys[1][0]);
System.out.println(greatGuys[0][1] + greatGuys[1][1]);
System.out.println(greatGuys[0][2]);

 The code above creates a 2-dimensional array which has 2 rows and 3 columns.
 Each position in the 2-D array will hold a String value.
 Elements are accessed using the format as outlined in Example 1.
 The 2-D array conceptually looks like the diagram below:

0 1 2

0 Fred Barney Dino

1 Flintstone Rubble

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 6
Useful to Know

It may be useful to know the following. Please look up further details on their usage. There are
many useful operations found in the java.util.Arrays class.

 There is a built-in length property which can be used to determine the size of an array.

System.out.println(myArray.length);

 arraycopy(): (found in the System class) can be used to copy data from one array to the
next. You can specify which subset of elements to copy.

public static void arraycopy(Object src, int srcPos,

Object dest, int destPos, int length)

src: array to copy from.

srcPos: starting position in the source array

dest: array to copy to.

destPos: starting position in the destination array.

length: number of array elements to copy.

 CopyOfRange(): copy from one array to the next but does not require the creation of a
destination array before calling the method.

 binarySearch()

 equals(): allows for comparison of two arrays.

 fill(): fills an array with a specific value.

 sort(): sort an array (ascending order).

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 7
Input & Output in Java

Screen Output

There are three common functions used to output data to the screen in Java:

 println: Output is displayed to the screen and then a carriage return. Any further output
will be done on the next line.
 print: Output is displayed to the screen. Any further output will be made on the same line.
There is no carriage return.
 printf: Provides the programmer with the ability to format output. Any further output will
be made on the same line unless a carriage return is specified in the formatting.

println() example print() example

System.out.println(“Java is ”); System.out.print(“Java is ”);


System.out.println(“awesome!”); System.out.println(“awesome!”);

Output: Output:
Java is Java is awesome!
Awesome!

Formatted Output

The printf method can be used to give output a specific format and works in a similar way to the
printf function found in the C++ language.

Format: System.out.printf(“format-string” [,arg1, arg2, ... ] );

Example: System.out.printf(“Cost of %s is $%6.2f”, item, price);

 The first argument of the function is always a format string (containing format specifiers)
followed by the values to be output in the format specified.
 The number of format specifiers and the number of arguments must match.

Note: The escape sequence \n may be used to indicate a line break. However, it is preferable to
use %n. What happens when \n is used may be system dependent but %n should always mean a
new line on any system.

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 8
Console Input Using the Scanner Class

Java includes a Scanner class which allows for simple keyboard input.

//You will need to import the Scanner class


import java.util.Scanner;

//Create an object of the Scanner class


Scanner myScanner = new Scanner(System.in);

You can now use methods in the Scanner class via your myScanner object to read data from the
keyboard. There are various methods for different types of data. A few are outlined below.

//Read an integer value from the keyboard


int intNum = myScanner.nextInt();

//Read a float value from the keyboard


float flNum = myScanner.nextFloat();

//Read a double value from the keyboard


double dblNum = myScanner.nextDouble();

//Read a boolean value from the keyboard


boolean answer = myScanner.nextBoolean();

//Read a single word from the keyboard


String word = myScanner.next();

//Read an entire line of text from the keyboard


String message = myScanner.nextLine();

String Concatenation

The concatenation operation can be used to connect two strings.

Example: String topic = “OOP”;


String message;
Message = topic + “ is awesome.”;
System.out.println(message);

Note: System.out.println(“100” + 42);


Output: 10042 {concatenation}

System.out.println(100 + 42);
Output: 142 {addition}

COMP2160 – Object-oriented Programming


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 9

You might also like