next:[[61B_Part_1_Java]]

Java program skeleton

no need to worry about the retract(缩进) (like in python).

Just like C++!

1
2
3
4
5
6
public class ClassNameHere {
public static void main(String[] args)
{

}
}

conditions

if

1
2
if (x < 10)
x = x + 10;

other version:

1
2
3
4
5
if (x < 10) 
{
System.out.println("I shall increment x by 10.");
x = x + 10;
}

else & else if

1
2
3
4
5
6
7
if (dogSize >= 50) {
System.out.println("woof!");
} else if (dogSize >= 10) {
System.out.println("bark!");
} else {
System.out.println("yip!");
}

loops

while

1
2
3
4
5
int bottles = 99;
while (bottles > 0) {
System.out.println(bottles + " bottles of beer on the wall.");
bottles = bottles - 1;
}

for

1
2
3
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}

another version of the for loop in java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class EnhancedForBreakDemo {
public static void main(String[] args) {
String[] a = {"cat", "dog", "laser horse", "ketchup", "horse", "horbse"};

for (String s : a) {
for (int j = 0; j < 3; j += 1) {
System.out.println(s);
if (s.contains("horse")) {
break;
}
}
}
}
}

of course, you can use break; or continue; in Java

user-defined functions

use public static before making a user-defined functions

All parameters, and functions themselves master have a type.

All functions must be in a class, so all functions in Java are methods.

1
2
3
4
5
6
7
8
9
10
public static int max(int x, int y) {
if (x > y) {
return x;
}
return y;
}

public static void main(String[] args) {
System.out.println(max(10, 15));
}

data types

Important ones:

In Java, varibles are first varified before the code runs!!!

If there are type issues, Java would simply not run.

(You don’t want your TikTok broken down when having a video)

normal ones

int, double, string

Arrays (list in Python)

1
2
3
4
5
int[] numbers = new int[3];
numbers[0] = 4;
numbers[1] = 7;
numbers[2] = 10;
System.out.println(numbers[1]);

simpler one:

1
2
int[] numbers = new int[]{4, 7, 10};
System.out.println(numbers[1]);