A Simple Java Program public class FirstSample{ public static void mainString[] args Java is case sensitive The keyword public is called an access modifier The keyword class is th
Trang 1JAVA BASICS ADVANCED PROGRAMMING
Trang 2A Simple Java Program
public class FirstSample{
public static void main(String[] args)
Java is case sensitive
The keyword public is called an access modifier
The keyword class is there to remind you that
class
The main method in the source file is necessary in
order to execute the program
method println of an object System.out
Trang 3System.out.println("We will not use 'Hello world!'");
// is this too cute?
/*
This is the first sample program
Copyright (C) by Cay Horstmann and Gary Cornell
*/
public class FirstSample {
public static void main(String[] args) {
System.out.println("We will not use 'Hello, World!'"); }
}
Trang 4Compiling and executing the program
To actually run the program, a java interpreter called java
is required to execute the code
The java compiler creates a file called 'First.class' that
contains the byte codes
Trang 5Passing Command Line Arguments
class CommLineArg {
public static void main (String [] pargs) {
System.out.println("These are the arguments
passed to the main method.");
Trang 6Passing Command Line Arguments
Output
Trang 7 Begin with a digit
Be the same as a reserved word.
10$
Trang 8Legal Identifiers
Identifiers must start with a letter, a currency
character ($), or a connecting character such as the
underscore ( _ ) Identifiers cannot start with a number!
After the first character, identifiers can contain any combination of letters, currency characters,
connecting characters, or numbers
In practice, there is no limit to the number of
characters an identifier can contain
You can't use a Java keyword as an identifier
Identifiers in Java are case-sensitive; foo and FOO
are two different identifiers
Trang 9Complete List of Java Keywords
Trang 10Java Code Conventions
Classes: the names should typically be nouns
Trang 11Java Code Conventions
Variables: Like methods, starting with a lowercase
letter Sun recommends short, meaningful names,
which sounds good to us Some examples:
button Width
accoun tBalance
my String
Constants: Java constants are created by marking
variables static and final They should be named
using uppercase letters with underscore characters as separators:
MIN_HEIGHT
Trang 12The Elements of a class
Trang 13 Four of them are integer types; two are
floating-point number types; one is the
character type char, used for characters in the Unicode encoding, and one is a boolean type for truth values
Trang 14Variables and Data Types (cont.)
Trang 15Size: 1 byte Range: -2 7 2 7 - 1
Size: 2 bytes Range: -2 15 2 15 - 1
Size: 2 bytes Range: -2 15 2 15 - 1
Size: 4 bytes Range: -2 31 2 31 - 1
Size: 4 bytes Range: -2 31 2 31 - 1
Size: 8 bytes Range: -2 63 2 63 - 1
Size: 8 bytes Range: -2 63 2 63 - 1
Trang 16Primitives: Floating Points
Size: 4 bytes Range: ±1.4 x 10 -45 ±3.4 x 10 38
Size: 8 bytes Range: ±4.9 x 10 -324 ±1.8 x 10 308
Size: 8 bytes Range: ±4.9 x 10 -324 ±1.8 x 10 308
Trang 17Primitives: Characters
Char is any unsigned Unicode character
Initialized to zero (\u0000)
Range: \u0000 \uFFFF
Size: 2 bytes Range: \u0000 \uFFFF
Trang 18Primitives: Booleans
boolean values are distinct in Java
Can only have a true or false value
An int value can NOT be used in place of a
Trang 19Primitive Data Types (summary)
Keyword Description Size/Range
Integers
byte Byte-length integer 1 byte : –128 to 127
short Short integer 2 bytes : –32 768 to 32 767
int Integer 4 bytes : –2 147 483 648 to 2 147 483 647
long Long integer 8 bytes : –9,223,372,036,854,775,808L to
9,223,372,036,854,775,807L
Real numbers
float Single-precision floating point 4 bytes : ±3.40282347E+38F
(6–7 significant decimal digits) double Double-precision floating point 8 bytes : ±1.79769313486231570E+308
(15 significant decimal digits)
Other types
char A Unicode character 2 bytes
boolean A boolean value true or false
Trang 20The Sign bit for a byte
All six number types in Java are signed
Integer literals three way store present integer
numbers in the Java language: decimal(base10),
octal(base8), hexadecimal(base16)
Trang 21Variables and Data Types (cont.)
Decimal Literals: default
Trang 22Variables and Data Types (cont.)
Floating-Point Literals:
Default are defined as double (64 bits)
Attach the suffix F or f to the number if want using floating-point (32 bits)
Character Literals: 16-bit unsigned integer
char letterN = '\u004E'; // The letter 'N‘
Trang 23Variables and Data Types (cont.)
Some special characters
\n: Used to denote new line
\r: Used to denote a return
\t: Used to denote a tab
\b: Used to denote a backspace
\f: Used to denote a form feed
\': Used to denote a single quote
\": Used to denote a double quote
\\: Used to denote a backslash
Literal Values for Strings: A string literal is a source code representation of a value of a String object
String s = "Bill Joy";
Trang 24Casting Primitive Types
Casting creates a new value and allows it to be
treated as a different type than its source
Java is a strictly typed language
Assigning the wrong type of value to a variable could
result in a compile error or a JVM exception
The JVM can implicitly promote from a narrower type
Trang 25Implicit vs Explicit Casting
Implicit casting is automatic when no loss of
information is possible
byte short int long float double
An explicit cast required when there is a
"potential" loss of accuracy:
int j = c; // automatic promotion
short k = c; // why is this an error?
short k = (short) c; // explicit cast
float f = 12.35; // what’s wrong with this?
Trang 26Variables and Data Types (cont.)
Accessing Variables: you can access it by referring to
Trang 27 In Java, every variable has a type You declare a variable by placing the type first, followed by the name of the variable
int total;
int count, temp, result;
Multiple declarations on a single line Variable Type Variable Name
• A variable name must begin with a letter, and must be a
sequence of letters or digits.
• Symbols like '+' or '©' cannot be used inside variable
names, nor can spaces
Trang 28A variable's scope
Trang 29Variable Scope example
A variable's scope is the region of a program within
which the variable can be referred to
Variables declared in:
Methods can only be accessed in that method
A loop or a block can only be accessed in that loop or block
abc abcd
Trang 31Variable Classification
Class Variables - Static variables (Static Fields)
The instance variables declared with the modifier
static This tells the compiler that there is exactly one
the class in which they are declared
Instance variables (Non-Static Fields – Member
outside of any method Objects store their individual states in "non-static fields", that is, fields declared
without the static keyword Non-static fields are
also known as instance variables because their
values are unique to each instance of a class (to
each object, in other words)
Trang 32Variable Classification
Local Variables All the variables declared inside a
method Their scope is the method Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables Local
variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class
Parameters: In the main method “public static void main(String[] args)”, the args variable is the
parameter to this method The important thing to
remember is that parameters are always classified as
"variables" not "fields"
Trang 33Variables Declarations
Default Initial values for primitive types
only the Member variables acquire the default
values if not explicitly initialized
You must initialize the local variables explicitly before you use them in the code, otherwise you will receive a compiler error.
Trang 34Variable Initialization
byte largestByte = Byte.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
Trang 35Variables declarations
Non-primitive types or Reference types or
called object reference
When you declare a variable of a non-primitive data type, you actually declare a variable that is
a reference to the memory where an object
lives
The name of variable refer to object is called
pointer
Trang 36Arrays
created After creation, an array is a fixed-length
structure
and is accessed by its position within the array
Trang 37Arrays example
Arrays:
Creating an Array
scores = new int[3];
Assigning Values to Array Elements
Array variables access by index
Index start from 0
scores[0] = 75;
Trang 38Variables declarations
Arrays: (built-in object)
Arrays in Java are objects that are used to store
multiple variables of the same type (primitive types
or non-primitive types)
Declaring an Array Variable
Data type Array variable’s name Number
elements
Trang 39– Actual memory allocation is done dynamically either
by a new statement or by an array initializer
Trang 40Creating Arrays
type[] var = { val1, val2, , valN };
int[] values = { 10, 100, 1000 };
String[] names = {"Joe", "Jane", "Juan"}; Point[] points = { new Point(0, 0), new Point(1, 2), new Point(3, 4) };
int[] primes = new int[7];
String[] names = new String[someArray.length];
Trang 41Accessing Arrays
Accessing an Array Element
the program assign values to the array elements:
for (int i = 0; i < anArray.length; i++) { anArray[i] = i;
System.out.print(anArray[i] + " ");
}
Getting the Size of an Array
arrayname.length
Trang 43Khoa CNTT – ĐH Nông Lâm TP HCM 01/2013 43/56
Creating object reference Arrays
Creating an Array of Point Objects
{ Point[] p;
this.y = y;
} }
Trang 44Multidimensional Arrays
A Multidimensional array is an array of arrays
Trang 45Multidimensional Array examples
twoDim[0] = new int[5];
twoDim[1] = new int[5];
{ "Heather", "seal-point" }, { "Ted", "red-point" }};
Number of elements in each row need not be equal
{ 2, 3, 4},
{ 5 },
{ 6, 7 } }
Trang 46Khoa CNTT – ĐH Nông Lâm TP HCM 01/2013 46/56
Matrix Example
int[][] aMatrix = new int[4][];
//populate matrix
for (int i = 0; i < aMatrix.length; i++) {
aMatrix[i] = new int[5]; //create
for (int i = 0; i < aMatrix.length; i++) {
for (int j = 0; j < aMatrix[i].length; j++) {
Trang 47TriangleArray Example
int[][] triangle = new int[10][];
for (int i=0; i<triangle.length; i++) {
triangle[i] = new int[i+1];
}
for (int i=0; i<triangle.length; i++) {
for (int j=0; j<triangle[i].length; j++) {
Trang 48Array Bounds
All array subscripts begin at 0
The number of elements in an array is stored as part of the array object in the length attribute
The following code uses the length attribute to iterate on an array:
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}
Trang 49The Enhanced for Loop
• Java 2 Platform, Standard Edition (J2SE™) version 5.0 has introduced an enhanced for loop for iterating over arrays:
– The for loop can be read as for each element in list
do
for (int element : list) {
System.out.println(element);
}
}
Trang 50Array Resizing
• You cannot resize an array
• You can use the same reference variable to refer to an entirely new array, such as:
int[] myArray = new int[6];
myArray[0] = 5;
myArray[1] = 12;
myArray = new int[10];
– In the preceding case, the first array is effectively lost unless another reference to it is retained elsewhere
Trang 51Copying Arrays
Use system's arraycopy method to efficiently
copy data from one array into another
arraycopy(Object source,int srcIndex, Object dest,int destIndex, int length)
Trang 52Copying Arrays
public class ArrayCopyDemo {
public static void main(String[] args) {
System.out.println(new String(copyTo));
}
}
Trang 53Run-time Memory
Trang 54Memory Usage By Java Program
Trang 55Memory Usage By Java Program
Stack
Local variables: The variables of primitive types
defined inside a method or as method parameters
Local reference variables: The variables that
refer to an object and are defined inside a method
or as a method parameter Remember that an
object that a local variable refers to lives on the
heap and not on the stack
Method invocations (Parameters): When you
invoke (call) a method, the method is pushed onto the stack (that is, placed on top of the stack)
Trang 56Memory Usage By Java Program
Heap
Instance variables: The variables of primitive
types defined inside a class but outside of all its
methods
Instance reference variables: The variables that
refer to an object and are defined inside a class but outside of all its methods
Objects: Represent the entities in the real-world
problem that the Java program is trying to solve All the objects live on the heap, always
Note: the object will not die with the local reference variable