Chapter 1 Java Programming Basics
Java Programming Basics 1
Java Basics 1: Types, Classes
and Operators
Java Programming Basics 2
The Java Compiler
◼ Java is a compiled language.
◼ Programs are compiled into byte-code executable files, which are
executed through the Java virtual machine (JVM).
❑ The JVM reads each instruction and executes that instruction.
◼ A programmer defines a Java program in advance and saves that
program in a text file known as source code.
◼ For Java, source code is conventionally stored in a file named with the
.java suffix (e.g., [Link]) and the byte-code file is stored in a file
named with a .class suffix, which is produced by the Java compiler.
Java Programming Basics 3
An Example Program
Java Programming Basics 4
C & Java
#include <stdio.h>
int main() public class Hello {
{ public static void main(String[] args)
printf("Hello World"); {
return 0; [Link]("Hello world");
} }
}
Java Programming Basics 5
Components of a Java Program
◼ In Java, executable statements are placed in functions, known as
methods (方法), that belong to class (類) definitions.
◼ The static method named main is the first method to be executed
when running a Java program.
◼ Any set of statements between the braces “{” and “}” define a
program block.
Java Programming Basics 6
Comments
◼ Inline comment
// This is an inline comment
◼ Block comment: Multiline comment
/*
* This is a block comment.
*/
Java Programming Basics 7
Identifiers
◼ The name of a class, method, or variable in Java is called an
identifier, which can be any string of characters as long as it
begins with a letter and consists of letters.
◼ Exceptions:
Java Programming Basics 8
class & method
◼ Class name ◼ Method name
◼ Good ◼ Good
❑ Hello ❑ main
❑ NoteBook ❑ goodMorning
❑ VRPlayer ❑ playVR
◼ Not Good ◼ Not Good
❑ hello ❑ Main
❑ Good123 ❑ good123
❑ Note_Book ❑ good_morning
❑ _World ❑ _playVR
Java Programming Basics 9
Base Types (Primitive Types)
◼ Java has several base types, which are basic ways of storing data.
◼ An identifier variable can be declared to hold any base type and it
can later be reassigned to hold another value of the same type.
Java Programming Basics 10
Java Programming Basics 11
◼ Initial Value
❑ All numeric type: zero
❑ Boolean: False
❑ Character: null
Java Programming Basics 12
Java String type
◼ In Java, String is not a primitive data type but rather a class, specifically
[Link].
❑ This means that String variables are objects, not direct values like primitive types such as
int or boolean.
◼ A String represents a sequence of characters
◼ Character array (char array)
Java Programming Basics 13
◼ The String class provides a rich set of methods for various operations,
including:
❑ length(): Returns the number of characters in the string.
❑ toUpperCase(), toLowerCase(): Converts the string to uppercase or lowercase.
❑ trim(): Removes leading and trailing whitespace.
❑ replace(): Replaces occurrences of a character or substring.
❑ substring(): Extracts a portion of the string.
❑ equals(): Compares strings.
Java Programming Basics 14
Exercises
1. Traversing the array (遍歷數組)
2. Bubble Sort (冒泡排序)
Java Programming Basics 15
1. Traversing the array
public class Main {
public static void main(String[] args) {
int[] ns = { 1, 4, 9, 16, 25 };
for (int i=0; i<[Link]; i++) {
int n = ns[i];
[Link](n);
}
}
}
Java Programming Basics 16
2 Bubble Sort
import [Link];
public class Main {
public static void main(String[] args) {
int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - i - 1; j++) {
if (ns[j] > ns[j+1]) {
// swap ns[j] with ns[j+1]:
int tmp = ns[j];
ns[j] = ns[j+1];
ns[j+1] = tmp;
}
}
}
[Link]([Link](ns));
}
}
Java Programming Basics 17
Classes and Objects (對象)
◼ Every object is an instance of a class, which serves as the type of
the object, defining the data which the object stores and the methods
for accessing and modifying that data. The critical members of a class
in Java are the following:
❑ Instance variables, which are also called fields, represent the data associated
with an object of a class. Instance variables must have a type, which can either
be a base type (such as int, float, or double) or any class type.
Java Programming Basics 18
Example
◼ Object-oriented programming is a programming method that maps
the real world to a computer model through the way of objects.
Real world Computer model Java code
Person class class Person { }
Li instance / Li Person li = new
Person()
Hong instance / hong Person hong = new
Person()
Wang instance / wang Person wang = new
Person()
Java Programming Basics 19
class Person {
public String name;
public int age;
}
Person hong = new Person();
[Link] = "Xiao Hong";
[Link] = 15;
Java Programming Basics 20
◼ Methods in Java are blocks of code that can be called to perform actions.
Methods can accept parameters as arguments, and their behavior may
depend on the object upon which they are invoked and the values of any
parameters that are passed.
◼ A method that returns information to the caller without changing any instance
variables is known as an accessor method
◼ update method is one that may change one or more instance variables when
called.
Java Programming Basics 21
Example of C--check the number even or odd
#include<stdio.h>
int main()
{
// This variable is to store the input number
int num;
printf("Enter an integer: ");
scanf("%d",&num);
// Modulus (%) returns remainder
if ( num%2 == 0 )
printf("%d is an even number", num);
else
printf("%d is an odd number", num);
return 0;
}
Java Programming Basics 22
Java Example
field
◼ This class includes one instance variable, named count, which
will have a default value of zero, unless we otherwise initialize it.
◼ The class includes two special methods known as constructors,
one accessor method, and three update methods.
Java Programming Basics 23
Creating and Using Objects
◼ Classes are known as reference types in Java, and a variable of
that type is known as a reference variable.
◼ A reference variable is capable of storing the location (i.e., memory
address) of an object from the declared class.
❑ So we might assign it to reference an existing instance or a newly constructed
instance.
❑ A reference variable can also store a special value, null, that represents the
lack of an object.
Java Programming Basics 24
◼ In Java, a new object is created by using the new operator followed by a call
to a constructor for the desired class.
◼ A constructor (構造函數) is a method that always shares the same name
as its class. The new operator returns a reference to the newly created
instance; the returned reference is typically assigned to a variable for further
use.
Java Programming Basics 25
Defining Constructors
◼ Constructor cannot be static, abstract, or final.
It can be public, protected, private
◼ The name of the constructor must be identical to the name of
the class it construct
◼ We don’t specify a return type for a constructor
Java Programming Basics 26
◼ A class can have many constructors, but each have a different
signature (parameter lists)
◼ If no constructor are explicitly defined, Java provides an implicit default
constructor for the class, having zero arguments and leaving all
instance variables initialized to their default value
◼ If a class define one or more nondefault constructors, no default
constructor will be provided
◼ Usually if you define a constructor with some parameters, a constructor
with trivial body { } will also be defined.
Java Programming Basics 27
Continued Example
◼ Here, a new Counter is constructed at line 4, with its reference assigned to the
variable c. That relies on a form of the constructor, Counter( ), that takes no
arguments between the parentheses.
Java Programming Basics 28
The Dot Operator
◼ One of the primary uses of an object reference variable is to access
the members of the class for this object, an instance of its class.
◼ This access is performed with the dot (“.”) operator.
◼ We call a method associated with an object by using the reference
variable name, following that by the dot operator and then the
method name and its parameters.
Java Programming Basics 29
Defining Classes
◼ A class definition is a block of code, delimited by braces “{” and
“}” , within which is included declarations of instance variables and
methods that are the members of the class.
◼ Immediately before the definition of a class, instance variable, or
method in Java, keywords known as modifiers can be placed to
convey additional stipulations about that definition.
Java Programming Basics 30
General structure of a class
modifier class Example {
fields;
constructors;
methods;
[main method;]
}
◼ modifier: public,protected,private,abstract,
static(method,variable),final(method, variable)
Java Programming Basics 31
Access Control Modifiers
◼ The public class modifier designates that all classes may access the
defined aspect.
◼ The protected class modifier designates that access to the defined
aspect is only granted to classes that are designated as subclasses of
the given class through inheritance or in the same package.
◼ The private class modifier designates that access to a defined member
of a class be granted only to code within that class.
Java Programming Basics 32
The Static Modifier
◼ When a variable or method of a class is declared as static, it is
associated with the class as a whole, rather than with each individual
instance of that class.
◼ Static variables are used to store “globe” information for a class. They
exist even if no instance of their class exists
◼ Static method is invoked using the name of the class as a qualifier,
e.g. [Link](2)
Java Programming Basics 33
◼ In a Java program, we deal with objects.
◼ The abstraction of objects is a class.
◼ For a class, if you want to use its members (methods),
you must first instantiate the object and then access
these members through a reference to the object.
◼ But the members decorated with static can be accessed
directly by adding "." to the class name.
Java Programming Basics 34
The abstract modifier
◼ A method of a class may be declared as abstract, in which case its
signature is provided but without an implementation of the method
body
◼ A class with one or more abstract methods must also be formally
declared as abstract, because it is essentially incomplete
◼ Any subclass of a class with abstract methods is expected to provide
a concrete implementation for each abstract method
Java Programming Basics 35
◼ public class Person {
public void run();
}
◼ Compile Error!
◼ public class Person {
public abstract void run();
}
◼ Compile Error!
◼ abstract class Person {
public abstract void run();
}
Java Programming Basics 36
The final modifier
◼ A variable that is declared with the final modifier can be initialized as
part of that declaration, but can never again be assigned a new value. If
it is a base type, then it is a constant
static final int Englis = 80;
◼ If a reference variable is final, then it will always refer to the same object
◼ A final method cannot be overridden by a subclass, and a final class
cannot even be subclassed
Java Programming Basics 37
Parameters
◼ A method’s parameters are defined in a comma-separated list enclosed in
parentheses after the name of the method.
❑ A parameter consists of two parts, the parameter type and the parameter name.
❑ If a method has no parameters, then only an empty pair of parentheses is used.
◼ All parameters in Java are passed by value, that is, any time we pass a
parameter to a method, a copy of that parameter is made for use within
the method body.
❑ So if we pass an int variable to a method, then that variable’s integer value is copied.
❑ The method can change the copy but not the original.
❑ If we pass an object reference as a parameter to a method, then the reference is
copied as well.
Java Programming Basics 38
Syntax
◼ class: [modifier] class ClassName {…}
◼ variables: [modifier] type identifier1[[=initialValue1],
identifier2[=initialValue1],…];
◼ methods: [modifier] returnType methodName(type1 param1, …,
typen paramn){…}
◼ Default modifier: modifier designates that access to a defined
member of a class be granted only to code in the same package
Java Programming Basics 39
◼ Minimization disclosure principle: Java manipulate the
object through the methods, not through the variables.
Java Programming Basics 40
Example:
public class Main {
public static void main(String[] args) {
Person ming = new Person();
[Link]("Xiao Ming"); // set name
[Link](12); // set age
[Link]([Link]() + ", " + [Link]());
}
}
class Person {
private String name;
private int age;
public String getName() {
return [Link];
}
Java Programming Basics 41
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return [Link];
}
public void setAge(int age) {
if (age < 0 || age > 100) {
throw new IllegalArgumentException("invalid age value");
}
[Link] = age;
}
}
Java Programming Basics 42
Example:
// private method
public class Main {
public static void main(String[] args) {
Person ming = new Person();
[Link](2008);
[Link]([Link]());
}
}
class Person {
private String name;
private int birth;
public void setBirth(int birth) {
[Link] = birth;
}
Java Programming Basics 43
public int getAge() {
return calcAge(2019); // invoke private method
}
// private method:
private int calcAge(int currentYear) {
return currentYear - [Link];
}
}
Java Programming Basics 44
The Keyword this
◼ Within the body of a method in Java, the keyword this is automatically
defined as a reference to the instance upon which the method was
invoked. There are three common uses:
1. To store the reference in a variable, or send it as a parameter to another
method that expects an instance of that type as an argument.
public double getBalance() {
return [Link];
}
Java Programming Basics 45
2. To differentiate between an instance variable and a local variable with the same name.
3. To allow one constructor body to invoke another constructor body.
public Counter(){
this(0);
}
Java Programming Basics 46
The main method
public static void main (String[] args)
{
//main method body
}
Java Programming Basics 47
Wrapper Types
◼ There are many data structures and algorithms in Java’s libraries
that are specifically designed so that they only work with object
types (not primitives).
◼ To get around this obstacle, Java defines a wrapper class for
each base type.
❑ Java provides additional support for implicitly converting
between base types and their wrapper types through a process
known as automatic boxing and unboxing.
Java Programming Basics 48
Example Wrapper Types
Java Programming Basics 49
◼ [Link](“2013”)
Change string “2013” to base type int 2013
Java Programming Basics 50
Signatures
◼ If there are several methods with the same name defined for a class,
then the Java runtime system uses the one that matches the actual
number of parameters sent as arguments, as well as their respective
types.
◼ A method’s name combined with the number and types of its
parameters is called a method’s signature, for it takes all of these
parts to determine the actual method to perform for a certain method
call.
◼ A reference variable v can be viewed as a “pointer” to some object o.
Java Programming Basics 51
Expressions and Operators
◼ Existing values can be combined into expressions using special
symbols and keywords known as operators.
◼ The semantics of an operator depends upon the type of its
operands.
◼ For example, when a and b are numbers, the syntax a + b
indicates addition, while if a and b are strings, the operator +
indicates concatenation.
Java Programming Basics 52
Arithmetic Operators
◼ Java supports the following arithmetic operators:
◼ If both operands have type int, then the result is an int; if one or both
operands have type float, the result is a float.
◼ Integer division has its result truncated.
Java Programming Basics 53
Increment and Decrement Ops
◼ Java provides the plus-one increment (++) and decrement (−−)
operators.
❑ If such an operator is used in front of a variable reference, then 1 is added to (or
subtracted from) the variable and its value is read into the expression.
❑ If it is used after a variable reference, then the value is first read and then the
variable is incremented or decremented by 1.
Java Programming Basics 54
Logical Operators
◼ Java supports the following operators for numerical values, which
result in Boolean values:
◼ Boolean values also have the following operators:
◼ The && and || operators short circuit, in that they do not
evaluate the second operand if the result can be determined based
on the value of the first operand.
Java Programming Basics 55
Bitwise Operators
◼ Java provides the following bitwise operators for integers and
booleans:
Java Programming Basics 56
Examples
[Link] ^:
0^0 0
0^1 1
1^0 1
1^1 0
2. ~00000001 : 11111110
Java Programming Basics 57
3. 6 << 2 = 24
0000 0000 0000 0000 0000 0000 0000 0110 -> 6
0000 0000 0000 0000 0000 0000 0001 1000 -> 6 << 2 = 24
4. 12 >> 2 = 3
0000 0000 0000 0000 0000 0000 0000 1100 -> 12
0000 0000 0000 0000 0000 0000 0000 0011 -> 12 >> 2 = 3
Java Programming Basics 58
5. -12 >> 2 = -3 (right shift of negative numbers)
1000 0000 0000 0000 0000 0000 0000 1100 ->-12
1111 1111 1111 1111 1111 1111 1111 0011 -> ~
1111 1111 1111 1111 1111 1111 1111 0100 -> +1
1111 1111 1111 1111 1111 1111 1111 1101 -> >> 2
1000 0000 0000 0000 0000 0000 0000 0010 ->~
1000 0000 0000 0000 0000 0000 0000 0011 ->+1
Java Programming Basics 59
6. 12 >>> 2 = 3
0000 0000 0000 0000 0000 0000 0000 1100 -> 12 0000
0000 0000 0000 0000 0000 0000 0000 0011 -> 12 >>> 2
=3
7. -12 >>> 2 = 1073741821
1111 1111 1111 1111 1111 1111 1111 0100 -> -12
0011 1111 1111 1111 1111 1111 1111 1101 -> -12 >> 2
= 1073741821
8. 3&5=1
0000 0000 0000 0000 0000 0000 0000 0011 -> 3
0000 0000 0000 0000 0000 0000 0000 0101 -> 5
0000 0000 0000 0000 0000 0000 0000 0001 -> 3 & 5 = 1
Java Programming Basics 60
Operator Precedence (優先級)
Java Programming Basics 61
Casting (類型轉換)
◼ Casting is an operation that allows us to change the type of a value.
◼ We can take a value of one type and cast it into an equivalent value of
another type.
◼ There are two forms of casting in Java: explicit casting and implicit
casting.
Java Programming Basics 62
Explicit Casting
◼ Java supports an explicit casting syntax with the following form:
(type) exp
◼ Here “type” is the type that we would like the expression exp to have.
◼ This syntax may only be used to cast from one primitive type to another
primitive type, or from one reference type to another reference type.
◼ Examples:
Java Programming Basics 63
Implicit Casting
◼ There are cases where Java will perform an implicit cast based upon the
context of an expression.
◼ You can perform a widening cast between primitive types (such as from
an int to a double), without explicit use of the casting operator.
◼ However, if attempting to do an implicit narrowing cast, a compiler error
results.
Java Programming Basics 64
Enum Types (列舉、枚舉)
public enum Day {MON, TUE, WED, THU, FRI, SAT, SUN} //enum
type definition
Day today; // a variable of enum type
today = [Link]; //assign a value to the variable
Java Programming Basics 65
Java Basics 2: I/O Methods and
Control Flow
66 Java Programming Basics
If Statements
◼ The syntax of a simple if statement is as follows:
◼ booleanExpression is a boolean expression and trueBody
and falseBody are each either a single statement or a
block of statements enclosed in braces (“{” and “}”).
Java Programming Basics 67
Compound if Statements
◼ There is also a way to group a number of boolean tests, as follows:
Java Programming Basics 68
Switch Statements
◼ Java provides for multiple-value control flow using the switch statement.
◼ The switch statement evaluates an integer, string, or enum
expression and causes control flow to jump to the code location labeled
with the value of this expression.
◼ If there is no matching label, then control flow jumps to the location
labeled “default.”
◼ This is the only explicit jump performed by the switch statement,
however, so flow of control “falls through” to the next case if the code for
a case is not ended with a break statement
Java Programming Basics 69
Switch Example
Java Programming Basics 70
Break and Continue
◼ Java supports a break statement that immediately
terminate a while, or loop or switch when executed within
its body.
◼ Java also supports a continue statement that causes the
current iteration of a loop body to stop, but with
subsequent passes of the loop proceeding as expected.
Java Programming Basics 71
While Loops
◼ The simplest kind of loop in Java is a while loop.
◼ Such a loop tests that a certain condition is satisfied and will
perform the body of the loop each time this condition is
evaluated to be true.
◼ The syntax for such a conditional test before a loop body is
executed is as follows:
while (booleanExpression)
loopBody
Java Programming Basics 72
Do-While Loops
◼ Java has another form of the while loop that allows the boolean
condition to be checked at the end of each pass of the loop rather
than before each pass.
◼ This form is known as a do-while loop, and has syntax shown below:
do
loopBody
while (booleanExpression)
Java Programming Basics 73
For Loops
◼ The traditional for-loop syntax consists of four sections—an
initialization, a boolean condition, an increment statement, and the
body—although any of those can be empty.
◼ The structure is as follows:
for (initialization; booleanCondition; increment)
loopBody
◼ Meaning:
Java Programming Basics 74
Example For Loops
◼ Compute the sum of an array of doubles:
◼ Compute the maximum in an array of doubles:
Java Programming Basics 75
For-Each Loops
◼ Since looping through elements of a collection is such a common
construct, Java provides a shorthand notation for such loops, called
the for-each loop.
◼ The syntax for such a loop is as follows:
for (elementType name : container)
loopBody
Java Programming Basics 76
For-Each Loop Example
◼ Computing a sum of an array of doubles:
◼ When using a for-each loop, there is no explicit use of array
indices.
◼ The loop variable represents one particular element of the
array.
Java Programming Basics 77
Simple Output
◼ Java provides a built-in static object, called [Link], that
performs output to the “standard output” device, with the following
methods:
Java Programming Basics 78
Simple Input
◼ There is also a special object, [Link], for performing input from the Java console
window.
◼ A simple way of reading input with this object is to use it to create a Scanner object,
using the expression
new Scanner([Link])
◼ Example:
Java Programming Basics 79
Java Packages
◼ Every stand alone public class defined in Java must be given in a
separate file
◼ Java allows a group of related type definitions (classes and enums) to be
grouped into what is known as a package
◼ Package: names are lowcased.
package packageName; //their source code must all be
//located in a directory named packageName
Java Programming Basics 80
◼ package pkg1[.pkg2[.pkg3…]];
◼ A java package is a group of similar types of classes, interfaces
and sub-packages.
◼ Package in java can be categorized in two form, built-in package
and user-defined package.
Java Programming Basics 81
Advantage of Java Package
◼ Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
❑ Organize classes or interfaces with similar or related functions in the same
package to facilitate the search and use of classes.
◼ Java package provides access protection
❑ Packages also limit access rights, and only classes with package access
rights can access classes in a certain package.
Java Programming Basics 82
◼ Java package removes naming collision
❑ Like folders, packages are also stored in a tree-like directory. The names
of classes in the same package are different, and the names of classes in
different packages can be the same. When calling classes with the same
class name in two different packages at the same time, the package name
should be added to distinguish them. Thus, packages can avoid name
collisions.
Java Programming Basics 83
package [Link];
public class Test{
...
}
◼ Its path should be saved like net/java/util/[Link]
Java Programming Basics 84
// File name : [Link]
package vehicle;
public class Car {
…
}
// File name : [Link]
package vehicle;
public class Truck {
…
}
Java Programming Basics 85
// The first non-comment line is the package statement
package [Link];
/* The import statement brings in classes from other packages*/
import [Link];
import [Link];
// class definition
public class MyClass {
…
}
import [Link];
Java Programming Basics 86
◼ Public definitions within a file that does not have an explicit package
declaration are placed into what is known as the default package
◼ Classes within the same package have access to any of each others’
members have public, protected, or default visibility (anything but
private).
Use: [Link]
Example: [Link] input=new [Link]([Link])
Java Programming Basics 87
◼ Import: to include external classes or entire packages in the current file
import [Link];
import packageName.*;
Example: import [Link];
Scanner input = new Scanner([Link]);
◼ If there is a name conflict between definitions in two different packages
being imported, full name (include the packageName. ) needs to be
used.
Java Programming Basics 88
import
import [Link]; //refer to a class outside
//of the current package
import packageName.* //import a whole package
Java Programming Basics 89
Commonly used java packages
◼ [Link]
Java Programming Basics 90
◼ [Link]: Contains language support classes(e.g classed
which defines primitive data types, math operations). This
package is automatically imported.
◼ Provides classes that are fundamental to the design of the
Java programming language.
❑ The most important classes are Object, which is the root of the class
hierarchy
❑ Class: instances of which represent classes at run time.
◼ [Link]
Java Programming Basics 91
◼ [Link]: Contains classed for supporting input / output
operations.
◼ [Link]: Contains utility classes which implement data
structures like Linked List, Dictionary and support, for Date /
Time operations.
Java Programming Basics 92
◼ [Link]: Contain classes for implementing the components for
graphical user interfaces (like button , menus etc).
◼ [Link]: package provides classes for performing arbitrary-
precision integer arithmetic and arbitrary-precision decimal
arithmetic
Java Programming Basics 93
[Link] Methods
◼ The Scanner class reads the input stream and divides it into
tokens, which are strings of characters separated by delimiters.
Java Programming Basics 94
Sample Program
Java Programming Basics 95
Sample Program
Java Programming Basics 96
Sample Program
Java Programming Basics 97
Exercise:
Write a Java class, Flower, that has three instance variables of type String, int,
and float, which respectively represent the name of the flower, its number, and
price. Your class must include a constructor method that initializes each
variable to an appropriate value, and your class should include methods for
setting the value of each type, and getting the value of each type.
Java Programming Basics 98
Sample code:
public class Flower {
// instance fields
private String name;
private int numbers;
private float price;
// constructors
public Flower(){ };
public Flower(String n, int p, float r) {
name = n;
numbers = p;
price = r;
}
Java Programming Basics 99
// Setters
public void setName(String n) { name = n;}
public void setNumbers(int p) { numbers = p;}
public void setPrice(float r) { price = r;}
// getters
public String getName() { return name;}
public int getNumbers() { return numbers;}
public float getPrice() { rturn price;}
Java Programming Basics 100
//main method
public static void main (String[] args){
Flower li = new Flower();
.
.
.
Java Programming Basics 101