1.
Khai báo biến
- Khai báo hằng số: final int abc=123;
2. Nhập dữ liệu từ bàn phím
import java.util.Scanner;
public class Nhap_du_lieu{
public static void main(String[] args){
// Nhập vào chuỗi
String chuoi=new Scanner(System.in).nextLine();
// Nhập vào số
int a=new Scanner(System.in).nextInt();
}
}
3. Class
* Access Modifiers
- public, private, protected
- default: Default class chỉ có thể truy cập trong cùng một package.
* Non-Access Modifiers
- final:
public class Main {
final int x = 10;
final double PI = 3.14;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final
variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final
variable
System.out.println(myObj.x);
}
}
- static: phương thức có nghĩa là nó có thể được truy cập mà không cần tạo đối
tượng của lớp, không giống như public
- abstract:
* Java Packages & API
- To use a class or a package from the library, you need to use the import keyword:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
VD:
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the
java.util package.
* Kế thừa: To inherit from a class, use the extends keyword.
* Java Inner Classes: Lớp trong lớp
VD: class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
// Outputs 15 (5 + 10)
* Java Interface
VD: interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
4. Java Date and Time
Java does not have a built-in Date class, but we can import the java.time package
to work with the date and time API. The package includes many date and time
classes. For example:
Class Description
LocalDate Represents a date (year, month, day (yyyy-MM-dd))
LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-
ns))
LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
DateTimeFormatte Formatter for displaying and parsing date-time objects