Title: "[[Java-Programming-Essentials]]"
Author:
- AllenYGY
status: DONE
tags:
- NOTE
- Java
- Lec2
- Program
created: 2023-11-04T00:59
updated: 2024-05-31T01:02
Java Programming Essentials
int numberOfBeans;
double myBalance, totalWeight;
Every variable in a Java program must be declared before it is used
Local variables are declared (visible) in methods, constructors or blocks. No default value for local variables, therefore should be assigned an initial value before the first use.
局部变量(local variable)是在方法或代码块内部定义的变量,只能在该方法或代码块内部访问。它们的生命周期仅限于该方法或代码块的执行期间。局部变量必须先声明,然后才能使用。在声明时,可以指定变量的类型和初始值。例如:
public void exampleMethod() {
int x = 5; // x是一个局部变量,类型为int,初始值为5
System.out.println(x); // 输出5
}
Instance variables are declared in a class, but outside a method, constructor or any block. Instance variables have default values, e.g., numbers – 0, Boolean – false,etc.
实例变量相当于该类的属性,需要 "new对象 "才能被调用。而且该变量不常驻内存,当这个类不再被使用时会java回收机制所释放。例如:
public class ExampleClass {
int x; // x是一个实例变量,初始值为0
String str = "hello"; // str是一个实例变量,初始值为"hello"
}
实例变量存在默认值:
Class/static variables
Class/Static variables are declared with the static keyword in a class, but outside a method, constructor or blocks.
There would only be one copy of each class variable per class, regardless of how many objects are created from it. Default values are same with instance variables.
静态变量用 static字符修饰,随着类的加载而加载,静态变量存放在方法池中的静态区,可以直接通过"类名.变量名直接"调用,也可以通过类的对象调用。
public class ExampleClass {
static int x; // x是一个静态变量,初始值为0
static String str = "hello"; // str是一个静态变量,初始值为"hello"
}
int a = ExampleClass.x; // 通过类名访问静态变量x
String s = ExampleClass.str; // 通过类名访问静态变量str
System.out.println(); //Print a line to the standard output (screen)
System.out.print(); //Print something to the standard output (screen)
import java.util.Scanner;
Scanner input = new Scanner(System.in);
int a=input.nextInt();
String b=input.nextline();
Double c=input.nextDouble();
A package is a collection of classes that is stored in a manner that makes it easily accessible to any program.
In order to use a class that belongs to a package, the class must be brought into a program using an import statement
if(){}
else{}
switch() {case"": break;}
while(Boolean_Expression) {
Statement_1
Statement_2
Statement_Last
}
do {
Statement_1
Statement_2
Statement_Last
} while(Boolean_Expression);
for(initialization;Boolean_Expression;Update){
}