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

Lec01 Introduction To Java11

The document provides an introduction to Java programming including: - Java can be used to develop Android apps, web apps, and desktop apps. - The JDK and IDEs like Notepad++ and Visual Studio Code are used for Java development. - A simple Java program prints "Welcome to Java!" to illustrate a class with a main method. - Java code is compiled to bytecode that can run on any system with a JVM.

Uploaded by

Abdulaziz Gamal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Lec01 Introduction To Java11

The document provides an introduction to Java programming including: - Java can be used to develop Android apps, web apps, and desktop apps. - The JDK and IDEs like Notepad++ and Visual Studio Code are used for Java development. - A simple Java program prints "Welcome to Java!" to illustrate a class with a main method. - Java code is compiled to bytecode that can run on any system with a JVM.

Uploaded by

Abdulaziz Gamal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter 1 Introduction to Java

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!");
}
}

Note: Clicking the green button displays the source code


with interactive animation. You can also run the code in
Welcome
a browser. Internet connection is needed for this button.

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

 To check javac version:


 javac -version
 To check java version
 java -version

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.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
print a message to the
console

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:

import java.util.Scanner; // specific/explicit import

import java.util.* ; // wildcard or implicit import

 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());

 String is a predefined class in the Java library just like


the System class and Scanner class.
 Since String is a class, it is a reference type.

15
Comparing Strings
 Since String is a class, we have to use
equals() or compareTo() method to
compare strings.
 Study OrderTwoCities.java.
Method Description

equals(s1) Returns true if this string is equal to string s1.


equalsIgnoreCase(s1) Returns true if this string is equal to string s1; it is case insensitive.
compareTo(s1) Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether
this string is greater than, equal to, or less than s1.
compareToIgnoreCase(s1) Same as compareTo except that the comparison is case insensitive.
startsWith(prefix) Returns true if this string starts with the specified prefix.
endsWith(suffix) Returns true if this string ends with the specified suffix.

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.

After executing String s = "Java"; After executing s = "HTML";

s : String s : String This string object is


now unreferenced
String object for "Java" String object for "Java"

Contents cannot be changed : String

String object for "HTML"

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;

public class TestArray {


public static void main (String[] args) {
int[] myList = new int[5];
Random r = new Random();
for (int i = 0; i < myList.length; i++)
myList[i] = r.nextInt(100); // range 0-99
Arrays.sort(myList);
System.out.println (Arrays.toString(myList));
}
}
19
The ArrayList Class
 Array’s size is fixed once the array is created. As such,
array is inflexible when the data size is unknown during
the array creation or increases a lot during runtime. The
array could be too small to accommodate the data.
 The ArrayList class is a resizable array that can grow its
size automatically to accommodate more data.
 To create an ArrayList object to store strings:
ArrayList<String> cities = new ArrayList<>();

 Study TestArrayList.java.
TestArrayList

20
Differences and Similarities between
Arrays and ArrayList
Operation Array ArrayList

Creating an array/ArrayList String[] a = new String[10] ArrayList<String> list = new ArrayList<>();


Accessing an element a[index] list.get(index);
Updating an element a[index] = "London"; list.set(index, "London");
Returning size a.length list.size();
Adding a new element list.add("London");
Inserting a new element list.add(index, "London");
Removing an element list.remove(index);
Removing an element list.remove(Object);
Removing all elements list.clear();

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);

  for (int i = 0; i < myList.length; i++) // normal for loop


System.out.println (myList[i]);

 In general, the syntax is


for (elementType element: arrayOrList) {
// Process the 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

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

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

You might also like