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

Part 01 - Java Basics 1 - Variable

Uploaded by

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

Part 01 - Java Basics 1 - Variable

Uploaded by

Ja Khang
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

ADVANCED PROGRAMMING

JAVA BASICS
A Simple Java Program
public class FirstSample{
public static void main(String[] args)
{
System.out.println("Hello,
World!");
}
}
 Java is case sensitive
 The keyword public is called an access modifier

 The keyword class is there to remind you that


everything in a Java program must be inside a
class
 The main method in the source file is necessary in
order to execute the program
 The System.out.println(..) is used to invoke
method println
Khoa CNTTof anNông
– ĐH object System.out
Lâm TP. HCM 01/2013 2/56
Comments
System.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!'");
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 3/56
Compiling and executing the program

The java compiler creates a file called 'First.class' that


contains the byte codes

To actually run the program, a java interpreter called java


is required to execute the code.

4
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 4/56
Passing Command Line Arguments

class CommLineArg {
public static void main (String [] pargs) {
System.out.println("These are the arguments
passed to the main method.");
System.out.println(pargs [0]);
System.out.println(pargs [1]);
System.out.println(pargs [2]);
}
}

5
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 5/56
Passing Command Line Arguments

Output

6
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 6/56
Identifiers
 Identifiers are:
 Text strings that represent variables, methods, classes or

labels
 Case-sensitive
 Characters can be digit, letter, '$' or '_'
 Identifiers cannot:
 Begin with a digit

 Be the same as a reserved word.

An_Identifier
a_2nd_Identifier
Go2
 An-Identifier
2nd_Identifier
goto

$10 10$
7
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 7/56
Legal 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.
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 8/56
Complete List of Java Keywords

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 9/56


Java Code Conventions
 Classes: the names should typically be nouns
 Dog
 Account
 PrintWriter
 Interfaces: the names should be adjectives
 Runnable
 Serializable
 Methods: the names should be verb-noun pairs.
 getBalance
 doCalculation
 setCustomerName

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 10/56


Java Code Conventions
 Variables: Like methods, starting with a lowercase
letter. Sun recommends short, meaningful names,
which sounds good to us. Some examples:
 buttonWidth
 accountBalance
 myString
 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

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 11/56


The Elements of a class

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 12/56


Data Types
 Java is a strongly typed language.
This means that every variable must have a
declared type. There are eight primitive
types in Java
 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.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 13/56


Variables and Data Types (cont.)
 Data types
 Primitive types
 Reference types

 The primitive types are boolean, byte, char, short, int,


long, float and double
 All non-primitive types are reference types, so classes,
which specify the types of objects, are reference types

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 14/56


Primitives: Integers
 Signed whole numbers
 Initialized to zero

Categories:
Size: 1 byte
a. integer 1. byte Range: -27  27 - 1

b. floating 2. short
Size: 2 bytes
Range: -215  215 - 1
c. character
3. int Size: 4 bytes
d. boolean Range: -231  231 - 1

4. long Size: 8 bytes


Range: -263  263 - 1

15
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 15/56
Primitives: Floating Points
 "General" numbers
 Can have fractional parts
 Initialized to zero

Categories:
a. integer
Size: 4 bytes
b. floating 1. float Range: ±1.4 x 10-45  ±3.4 x 1038

c. character
2. double Size: 8 bytes
d. boolean Range: ±4.9 x 10-324  ±1.8 x 10308

16
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 16/56
Primitives: Characters

 Char is any unsigned Unicode character


 Initialized to zero (\u0000)

Categories:
a. integer
b. floating
char Size: 2 bytes
c. character Range: \u0000  \uFFFF
d. boolean

Java Basic 17
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 17/56
Primitives: 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
boolean
 Initialized to false

Categories:
a. integer
b. floating
c. character
Size: 1 byte
d. boolean boolean Range: true | false

18
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 18/56
Primitive Data Types (summary)
Keyword Description Size/Range
Integers

byte Byte-length
1 byte : –128 to 127
integer
short Short integer 2 bytes : –32 768 to 32 767
int Integer 4 bytes : –2 147 483 648 to 2 147 483 647

long 8 bytes : –9,223,372,036,854,775,808L to


Long integer
9,223,372,036,854,775,807L
Real numbers

float Single-precision 4 bytes :  ±3.40282347E+38F


floating point (6–7 significant decimal digits)

double Double-precision 8 bytes :  ±1.79769313486231570E+308


floating point (15 significant decimal digits)
Other types

char A Unicode
2 bytes
character
boolean A boolean value true or false

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 19/56


The 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)
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 20/56
Variables and Data Types (cont.)
 Decimal Literals: default
 int length = 343;

 Octal Literals: represent an integer in octal form by


placing a zero in front of the number
 int nine = 011;

 Hexadecimal Literals: including the prefix 0x or the


optional suffix extension L
 int z = 0xDeadCafe;

 Note: Java will accept capital or lowercase letters for


the extra digits in hexadecimal
 0XCAFE and 0xcafe are both legal

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 21/56


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


 Example:

 float f = 23.467890; // Error

 float g = 49837849.029847F;

 Boolean Literals
 true, false

 Character Literals: 16-bit unsigned integer


 char letterN = '\u004E'; // The letter 'N‘

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 22/56


Variables 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";

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 23/56


Casting 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
to a wider type
 To change to a narrower type, you must cast explicitly

double f;
int a, b; int d; long g;
short c; short e; f = g;
a = b + c; e = (short)d; g = f; //error

Java Basic 24
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 24/56
Implicit 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:

long p = (long) 12345.56; // p == 12345


int g = p; // illegal even though an int
// can hold 12345
char c = 't';
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?
Java Basic 25
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 25/56
Variables and Data Types (cont.)
 Accessing Variables: you can access it by referring to
it by its name

x = y;

assign y’s value to the


access the variable y
variable x

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 26/56


Variables
 In Java, every variable has a type. You declare a variable by
placing the type first, followed by the name of the variable

Variable Type Variable Name

int total;

int count, temp, result;

Multiple declarations on a single line

• 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
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 27/56
A variable's scope

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 28/56


Variable 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

int a = 1;
for (int b = 0; b < 3; b++){
int c = 1;
for (int d = 0; d <3; d++){
if (c < 3) c++;
}
abcd
System.out.print(c);
System.out.println(b); abc
}
 a = c; // ERROR! c is out of scope a
Java Basic 29
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 29/56
A variable's scope
public static void main(String[] args)
{
int n;
...
{
int k;
...
} // k is only defined up to here
}

public static void main(String[] args)


{
int n;
...
{
int k;
int n; // error--can't redefine n in inner block
...
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 30/56
Variable Classification
 Class Variables - Static variables (Static Fields)
The instance variables declared with the modifier
static. This tells the compiler that there is exactly one
copy of this variable in existence, reg. Their scope is
the class in which they are declared.
 Instance variables (Non-Static Fields – Member
variable) : The variables declared inside a class but
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)
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 31/56
Variable 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".

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 32/56


Variables Declarations
 Default Initial values for primitive types

 Note:
 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.
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 33/56
Variable Initialization
//integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;

//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble =
Double.MAX_VALUE;

//other primitive types


char aChar = 'S';
boolean aBoolean = true;

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 34/56


Variables 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

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 35/56


Arrays
 A structure that holds multiple values of the same type.
 The length of an array is established when the array is
created. After creation, an array is a fixed-length
structure.

 An array element is one of the values within an array


and is accessed by its position within the array.
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 36/56
Arrays 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;

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 37/56


Variables 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

int [] scores; or int scores []; or int scores [5]

Data type Array variable’s name Number


elements

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 38/56


Declaring Arrays
• Declaring Arrays:
– Declare arrays of primitive or class types:
char s[];
char[] s;
Point p[];
Point[] p;
– The declaration of an array creates space for a
reference.
– Actual memory allocation is done dynamically either
by a new statement or by an array initializer.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 39/56


Creating Arrays
 Declare and allocate array in one step
type[] var = { val1, val2, ... , valN };
– Examples:

int[] values = { 10, 100, 1000 };


String[] names = {"Joe", "Jane", "Juan"};
Point[] points = { new Point(0, 0), new
Point(1, 2), new Point(3, 4) };
 Use the new keyword
– Step 1: allocate an array of references:
int[] primes = new int[7];
String[] names = new String[someArray.length];
– Step 2: populate the array

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 40/56


Accessing 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

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 41/56


Creating Arrays
 An example to create and initialize a primitive (char)
array:

public char[] createArray() {


char[] s;
s = new char[26];
for ( int i = 0; i < 26; i++ ) {
s[i] = (char) ('A' + i);
}
return s;
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 42/56


Creating object reference Arrays
 Creating an Array of Point Objects

class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

public Point[] createArray() {


Point[] p;
p = new Point[10];
for ( int i=0; i<10; i++ ) {
p[i] = new Point(i, i+1);
}
return p;
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 43/56


Multidimensional Arrays
 A Multidimensional array is an array of arrays.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 44/56


Multidimensional Array examples
 int [][] twoDim = new int[4][];
twoDim[0] = new int[5];
twoDim[1] = new int[5];
 int[][] twoD = new int[64][32];
 String[][] cats = {{ "Caesar", "blue-point" },
{ "Heather", "seal-point" },
{ "Ted", "red-point" }};

 Number of elements in each row need not be equal


 int[][] irregular = { { 1 },
{ 2, 3, 4},
{ 5 },
{ 6, 7 } }

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 45/56


Matrix Example
public class ArrayOfArraysDemo2 {
public static void main(String[] args) {
int[][] aMatrix = new int[4][];

//populate matrix
for (int i = 0; i < aMatrix.length; i++) {
aMatrix[i] = new int[5]; //create sub-array
for (int j = 0; j < aMatrix[i].length; j++) {
aMatrix[i][j] = i + j;
}
}

//print matrix
for (int i = 0; i < aMatrix.length; i++) {
for (int j = 0; j < aMatrix[i].length; j++) {
System.out.print(aMatrix[i][j] + " ");
}
System.out.println();
}
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 46/56


TriangleArray Example
public class TriangleArray {
public static void main(String[] args) {
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++) {
System.out.print(triangle[i][j]);
}
System.out.println(); 0
} 00
} 000
0000
} 00000
000000
0000000
00000000
000000000
0000000000

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 47/56


Array 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:

public void printElements(int[] list) {


for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 48/56


The Enhanced for Loop
• Java 2 Platform, Standard Edition (J2SE™) version 5.0
has introduced an enhanced for loop for iterating over
arrays:
public void printElements(int[] list) {
for (int element : list) {
System.out.println(element);
}
}

– The for loop can be read as for each element in list


do.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 49/56


Array 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.

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 50/56


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

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 51/56


Copying Arrays
public class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = {'d','e','c','a','f','f',
'e','i','n','a','t','e','d' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 52/56


Run-time Memory

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 53/56


Memory Usage By Java Program

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 54/56


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

Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 55/56


Memory 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
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2013 56/56

You might also like