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

Part 01 - Java Basics 1 - Variable_2025

The document provides an introduction to Java programming, covering basic concepts such as case sensitivity, access modifiers, and the structure of a Java program. It explains identifiers, legal naming conventions, Java keywords, data types, and the importance of variable declaration. Additionally, it discusses casting between primitive types and the scope of variables in Java.

Uploaded by

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

Part 01 - Java Basics 1 - Variable_2025

The document provides an introduction to Java programming, covering basic concepts such as case sensitivity, access modifiers, and the structure of a Java program. It explains identifiers, legal naming conventions, Java keywords, data types, and the importance of variable declaration. Additionally, it discusses casting between primitive types and the scope of variables in Java.

Uploaded by

dominhphuoc68
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Chapter 1& 2

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 of an object System.out

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 2


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 3


Comments
/**
* The MainClass is the class that help to print out the "Hello
World!" text
* @author yellowcode
* @version 1.0
* @since 2021-05-04
*/
public class MainClass {
/**
* The main function, entry point of this app
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 4


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$
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 5
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.
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 6
Complete List of Java Keywords
◼ There are nine categories
Keyword type Keyword
Tổ chức lớp package, import
Định nghĩa lớp class, interface, extends, implements
Dành cho biến và lớp abstract, public, private, protected,
static, synchronized, volatile, final,
native
Các kiểu dữ liệu nguyên thủy byte, short, int, long, float, double, char,
boolean, void
Cho các giá trị và các biến false, true, this, super, null
Xử lý ngoại lệ throw, throws, try, catch, finally
Tạo và kiểm tra các đối new, instanceof
tượng
Lệnh điều khiển chương trình if, else, switch, case, default, break,
for, while, do, continue, return
Chưa được sử dụng byvalue, future, outer, const, genetic,
rest, goto, inner, var, cast, operator
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 7
What is an example of correct identifier?
1) Tinh Tong
2) Tinh-Tong
3) Tinh_Tong
4) x_Mu_2
5) 2_Mu_2
6) Tien$
7) default
8) yahoo.com

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 8


Java Code Conventions

◼ Classes: the names should typically be nouns


◼ Dog
◼ Account
◼ PrintWriter
◼ Interfaces: the names should be adjectives
◼ Runnable
◼ Comparable
◼ Methods: the names should be verb-noun
pairs
◼ getBalance
◼ doCalculation
◼ setCustomerName

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 9


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
◼ radius
◼ 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
◼ static final int MIN_A=Integer.MIN_VALUE;
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 10
The Elements of a class

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 11


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.

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 12


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 13


Primitives: Integers
◼ Signed whole numbers
◼ Initialized to zero

Categories:
1. byte Size: 1 byte
a. integer 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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 14


Primitives: Floating Points
◼ "General" numbers
◼ Can have fractional parts
◼ Initialized to zero

Categories:
a. integer
b. floating 1. float
Size: 4 bytes
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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 15


Primitives: Characters
◼ Char is any unsigned Unicode character
◼ Initialized to zero (\u0000)

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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 16


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 17


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 18


The Sign bit for a byte

All six number types in Java are signed


(byte, short, int, long, float, double)
Integer literals three way store present integer
numbers in the Java language: decimal(base10),
octal(base8), hexadecimal(base16)
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 19
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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 20


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’

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 21


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 22


Casting Primitive Types

◼ Casting creates a new value and allows it to


be treated as a different type than its source
◼ Java is a strongly 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 (ngầm định) promote
from a narrower type to a wider type
double f;
◼ To change
int a, b; to aint
narrower
d; type, you
longmust
g; cast
explicitly
short c;
a = b + c;
(tường
shortminh)
e;
e = (short)d;
f = g;
g = f;//

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 23


Implicit vs. Explicit Casting

◼ Implicit (ngầm định) 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(error)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?

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 24


Casting Primitive Types in expression

◼ Example:
char ch;
int i;
float f;
double d;

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 25


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 26


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
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 27
A variable's scope

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 28


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
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 29
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
...
}
}

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 30


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.
Example: public static int numberOfStudents;
◼ Instance variables (Non-Static Fields–Member
variable): The variables declared inside a class but
outside of any method. 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)
Example: private String idStudent;

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 31


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.
public int compTotal(int a, int b){
int sum =0;
…..
}
◼ 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".
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 32
Variable Classification

◼ Java 10 introduced a new shiny language feature


called local variable type inference.
var variableName = value;
var x = 123; // int
var y = 123L; // long
var z = 3.14; // double
var s = "Hello"; // String

➢ Notes:
◼ Can only be used to declare local variables inside methods
(functions) or code blocks
◼ You can't use local variable type inference with method
arguments,
◼ You cannot initialize a var variable to null.

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 33


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.
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 34
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;
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 35
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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 36


Cho biết những lỗi sai và sửa lại cho đúng

1) int n = -100;
2) int x = 089, int a = 0x137E
3) unsigned int i = -100;
4) int = 2.9, b = 0x34G;
5) long m = 2, p = 4;
6) int 2k;
7) float y = y * 2;
8) char ch = “b”, m = ‘\n’;

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 37


Static variable example in Java

public class VariableDemo {


private static int count=0;
public void increment() {
count++;
}
public static void main(String args[]) {
VariableDemo obj1=new VariableDemo();
obj1.increment();
System.out.println("Obj1:count is="+obj1.count);
VariableDemo obj2=new VariableDemo();
obj2.increment();
System.out.println("Obj2: count is="+obj2.count);

System.out.println(”===============“);
System.out.println("Obj1:count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
→ the result of obj1.count =?? and obj2.count =???

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 38


Static variable example in Java

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 39


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 40


Arrays example
◼ Arrays:
◼ Declaring an Array Variable

◼ int[] scores;

◼ Creating an Array

◼ scores = new int[3];

◼ Assigning Values to Array Elements

◼ Array variables access by index

◼ Index start from 0

◼ scores[0] = 75;

◼ System.out.print(scores[0])

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 41


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]

Number
Data type Array variable’s name
elements

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 42


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.

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 43


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
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 44
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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 45


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 46


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;
}
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 47
Multidimensional Arrays
◼ A Multidimensional array is an array of arrays.

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 48


Multidimensional Array examples
◼ int [][] twoDim = new int[4][];
twoDim[0] = new int[5];
twoDim[1] = new int[2];
◼ 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 } }

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 49


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();
}
}
}
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 50
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]);
}
0
System.out.println(); 00
} 000
} 0000
00000
} 000000
0000000
00000000
000000000
0000000000
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 51
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]);
}
}

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 52


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.

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 53


Quiz for The Enhanced for Loop
public static void main(String[] args) {
String[] b= new String[20];
b[0]="1";
b[1]="hai";
b[2]="ba";
for (String i : b) {
if(i.isBlank()) {
System.out.println(i);
}
}
}

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 54


Quiz for The Enhanced for Loop

public static void main(String[] args) {


int[] b= new int[20];
b[0]=1
b[1]=100;
b[2]=10;
for (int i : b) {
System.out.println(i);
}
}

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 55


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.

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 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)

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 57


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 58


Run-time Memory

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 59


Memory Usage By Java Program

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 60


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)

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 61


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

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 62


Assignment 1

◼ Cho 3 số nguyên dương a, b, c. Hãy viết


chương trình kiểm tra ba số có lập thành
tam giác không? Nếu có hãy cho biết tam
giác đó thuộc loại nào? (cân, vuông, đều)
◼ Điều kiện để 3 số lập thành tam giác: tổng hai
cạnh phải lớn hơn cạnh còn lại ( a+b>c và
a+c>b và b+c>a)
◼ Xét loại tam giác:
◼ Tam cân: a = b hoặc b = c hoặc c = a
◼ Tam giác đều: a = b = c
◼ Tam giác vuông: a2 = b2 + c2 hoặc b2 = a2 + c2 hoặc
c2 = a2 + b2
17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 63
Assignment 2

◼ Cho 3 số nguyên a, b và c. Viết một chương trình in


ra
◼ tổng, trung bình cộng, tích của chúng,
◼ số nhỏ nhất, số lớn nhất trong 3 số.

(Lưu ý rằng trong bài này, việc tính trung bình cộng cần
cho kết quả là số kiểu nguyên, nghĩa là nếu tổng giá trị
bằng 7 thì trung bình cộng cần in ra phải là 2 chứ không
phải 2.3333.
◼ Cho 2 số nguyên a, b. Viết một chương trình kiểm
tra xem số thứ nhất có chia hết cho số thứ hai hay
không, in ra kết quả kiểm tra

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 64


Assignment 3

◼ Cho một ký tự N. Viết chương trình hiện


thực theo yêu cầu sau:
◼ Nếu là chữ hoa, xuất CHUHOA
◼ Nếu là chữ thường, xuất CHUTHUONG
◼ Nếu là số chẵn, xuất SOCHAN
◼ Nếu là số lẽ, xuất SOLE

17/02/2025 Khoa CNTT – Trường ĐH Nông Lâm TP. HCM 65

You might also like