Lec01 Introduction To Java11
Lec01 Introduction To Java11
1
Why Java?
Java is the primary language for developing
Android applications.
Java is used to develop Web, cloud, and
server applications (use Servlet, JSP, Spring,
etc.).
Java can also be used to develop GUI
desktop applications (use Swing, JavaFX,
etc.).
2
JDK and IDE for TCP1201
Compiler: JDK 8
IDE:
Notepad++
Visual Studio Code for Java
Install the Coding Pack for Java – Windows
Install the Coding Pack for Java – macOS
3
A Simple Java Program
Listing 1.1
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
4
Creating, Compiling, and
Running Programs
5
Compiling Java Source Code
With Java, you write the program once, and compile the
source program into bytecode.
The bytecode can then run on any computer with a Java
Virtual Machine (JVM) installed, regardless of Windows,
Mac, Android, or Linux.
Java Virtual Machine is a software that interprets Java
bytecode.
6
Companion
Website Compiling and Running Java
from the Command Prompt
To compile a Java file:
javac Welcome.java
To run a Java class:
java Welcome
7
Class Name & File Name
Every Java program must have at least one class. By
convention, class names start with an uppercase letter. In
this example, the class name is Welcome.
A public class in Java must be declared in a file with a
name same as the class name. If the public class name is
Welcome, then the file name should be Welcome.java.
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
8
Main Method
Line 2 defines the main method. In order to run a
class, the class must contain the main method.
The program is executed from the main method.
9
Reading User Input from Console
Three steps to read user input:
1. Import package java.util.Scanner.
import java.util.Scanner;
2. Create a Scanner object
Scanner input = new Scanner(System.in);
3. Use method next to obtain to a value.
String name = input.next();
int num = input.nextInt();
double price = input.nextDouble();
Study ComputeAverage.java.
ComputeAverage
10
Import a Java Package
Java provides large collections of useful classes that are
grouped into packages.
A package groups related classes. For example, the
Scanner class is provided by the java.util package.
To import java.util package:
No performance difference
11
Primitive Types
Java’s data types are divided into primitive types and
reference types.
Primitive types: int, boolean, byte, char, short, long, float
and double.
A primitive-type variable stores one value of its declared
type. For example, a variable of type int stores one integer
value.
When another value is assigned to that variable, the new
value replaces the old value. The old value is lost.
12
References Types
Reference types: All non-primitive types, such as String,
array, and objects (classes).
A reference type stores the location of an object or array.
When another object is assigned to a reference variable,
the variable stores the location of the new object (we say
the variable references to the new object). The old object
is not lost. If there is no more variable references to the
old object, it will be automatically garbage-collected
(destroyed to free up memory) by JVM.
A reference variable has null value if it is not initialized.
13
Comparing Objects of Reference Types
For primitive types, we can compare their
variables using '==', '<', or '>'.
For reference types, we cannot compare their
variables using '==', '<', or '>'.
We shall use equals() method or
compareTo() method for comparing
reference types.
14
The String Type
String message = "Welcome to Java";
System.out.println ("Length of " + message + "
= " + message.length());
15
Comparing Strings
Since String is a class, we have to use
equals() or compareTo() method to
compare strings.
Study OrderTwoCities.java.
Method Description
OrderTwoCities
16
Strings Are Immutable
A String object is immutable meaning its contents cannot be changed.
Does the following code change the contents of the string?
String s = "Java"; // Create a String object.
s = "HTML"; // Create another String object.
Since String is immutable, rapidly changing the content of a String
object will cause memory wastage and reduce performance.
If you want to rapidly append, insert, or delete contents in a string,
use StringBuilder class for better efficiency and saving memory.
17
Arrays
In Java, arrays are created through dynamic memory allocation.
To initialize an array (does not require new operator):
double[] myList = {5.6, 1.2, 3.4};
To declare and create an array (require new operator):
double[] myList = new double[10];
Declare only results in null:
double[] myList; // null
To find the length (size) of an array:
myList.length
To sort an array:
java.util.Arrays.sort (myList);
To convert an array into a string:
java.util.Arrays.toString (myList);
18
Array Example
Create an array of 5 random integers, sort it, then print it
in one line.
import java.util.Arrays;;
import java.util.Random;
Study TestArrayList.java.
TestArrayList
20
Differences and Similarities between
Arrays and ArrayList
Operation Array ArrayList
21
For-each Loop
For-each loops traverses a complete array sequentially without
using an index variable.
For example, the following code displays all elements in array
myList:
for (String element: myList) // for-each loop
System.out.println (element);
22
For-each Loop cont.
IMPORTANT: You still have to use normal 'for'
loop with an index variable if you wish to
perform any of the following tasks:
– Change the elements of primitive type in an array or
list.
– Traverse the array or list in a different order
(alternative, step, or reversed).
23
Defining Methods
A method or function is a collection of
statements that are grouped together to perform
an operation.
Define a method Invoke a method
24
Pass By Value
Java uses pass by value to pass arguments to a method.
There are important differences between passing a variable of
primitive type, and passing a variable of reference type (array
or object).
For a parameter of a primitive type, the actual value of the
variable is copied and passed. Changes to the parameter in
the method does not affect the value of the variable outside
the method.
For a parameter of an reference type (array or class), the
location of the variable is copied and passed to the method.
Changes to the parameter in the method body affects the
original data outside the method.
25
Pass By Value Example
public class TestPassArgument {
public static void main(String[] args) {
int[] a = {1, 2};
change (a[0]); // pass an int.
System.out.println("After change: " + a[0]); // 1, why?
change (a); // pass an array.
System.out.println("After change: " + a[0]); // 10, why?
}
static void change (int n) { // primitive type
n *= 10;
}
static void change (int[] array) {// reference type
array[0] *= 10;
}
}
26
Remember This
A Java file name must follow the public class name.
Compile your Java file, but run your Java class.
Java does not support C++' style of passing argument by reference
which uses '&'. Java always passes argument by value.
Reference types are similar to pointers in C++, except that there is
no asterisk (*).
In Java, arrays and objects are always created through dynamic
memory allocation.
Always use equals() or compareTo() method to compare
variables of reference types (arrays, Strings, and objects).
27