0%

Basic Terminology

  • Program – a sequence of instructions (called statements), which are executed one after another in a predictable manner. Sequential flow is the most common and straightforward sequence of statements, in which statements are executed in the order that they are written – from top to bottom in a sequential manner;
  • Statement – a single action (like print a text) terminated by semi-colon (;);
  • Block – a group of zero, one or more statements enclosed by a pair of braces {...}; There are two such blocks in the program above.
  • Method – a sequence of statements that represents a high-level operation (also known as subprogram or procedure).
  • Syntax – a set of rules that define how a program needs to be written in order to be valid; Java has its own specific syntax that we will learn;
  • Keyword – a word that has a special meaning in the programming language (public, class, and many others). These words cannot be used as variable names for your own program;
  • Identifier or name – a word that refers to something in a program (such as a variable or a function name);
  • Comment – a textual explanation of what the code does. Java comments start with //.
  • Whitespace – all characters that are not visible (space, tab, newline, etc.).

What Do Matter …

  • Public Class: A class can have any name, such as App, Main, or Program, but it must not start with a digit. A set of braces {...} encloses the body of a class.
1
2
3
public class Main {
// ...
}
  • Main Method : we put a method named main inside a class. It is the entry point for a Java program. The name of this method (main) is predefined and should always be the same.
1
2
3
public static void main(String[] args) {
// statements go here
}
  • Print
1
System.out.println("Hello, World!"); //  each statement has to end with ;

Printing Data …

  • The println method displays the passed string followed by a new line on the screen (print-line).

  • Print an empty line:

1
System.out.println(); // prints empty line
  • The print method displays the passed value and places the cursor (the position where we display a value) after it. As an example, the code below outputs all strings in a single line.
1
2
3
4
System.out.print("I ");
System.out.print("know ");
System.out.print("Java ");
System.out.print("well.");

Declaring and initializing

  • Declaration

    1
    DataType variableName = initialization
  • The **type (**or data type) of a variable determines what possible operations can be performed on the variable and which values can be stored in it. Here we use a non-existing data type (DataType) to demonstrate the general form of declaration.

  • The **name (**or identifier) distinguishes the variable from others. The name of a variable cannot start with a digit; it usually starts with a letter. Always try to choose meaningful and readable names for variables to make your code easy to understand.

  • The assignment operator denoted as = is used to assign a single value or a result of an expression to a variable.

  • The initialization is a value or a result of an expression that is assigned to the variable.

    Some Examples:

1
2
String language = "java";
int numberOfApples = 5;

  • Accessing the value of a variable

    you can only assign a value of the same type as the type of the initial variable.

  • Alternative forms of declaration

    • Declaring several variables of the same type as a single statement:

      1
      String language = "java", version = "8 or newer";
    • Separating declaration and initialization into statements:

      1
      2
      int age; // declaration
      age = 35; // initialization
  • What’s new?

    • Type inference

      Since Java 10, you can write var instead of a specific type to force automatic type inference based on the type of assigned value:

      1
      var variableName = initialization;

      Here are two examples below:

      1
      2
      var language = "Java"; // String
      var version = 10; // int

Comments

  • End-of-line comments

    The java compiler ignores any text from // to the end of the line.

    1
    2
    3
    4
    5
    6
    7
    8
    class Program {
    public static void main(String[] args) {
    // The line below will be ignored
    // System.out.println("Hello, World");
    // It prints the string "Hello, Java"
    System.out.println("Hello, Java"); // Here can be any comment
    }
    }
  • Multi-line comments

The compiler ignores any text from /* and the nearest */. It can be used as multiple and single-line comments.

1
2
3
4
5
6
7
class Program {
public static void main(String[] args) {
/* This is a single-line comment */
/* This is an example of
a multi-line comment */
}
}

Naming

  • names are case-sensitive;
  • a name can include Unicode letters, digits, and two special characters ($, _);
    • Since Java 9 the single character _ is an invalid name for a variable, but _a and __ (double _ ) are legal names.
  • a name cannot start with a digit;
  • a name must not be a keyword (class, static, int are illegal names).

Note that to keep backward compatibility the word "var" can be used as a variable name even after Java 10 was released.

  • if a variable name is a single word it should be in lowercase (for instance: number, price);
  • if a variable name includes multiple words it should be in lowerCamelCase, i.e. the first word should be in lowercase and each word after the first should have its first letter written in uppercase (for instance: numberOfCoins);
  • variable names should not start with _ and $ characters, although they are allowed;
  • choose a name that makes sense, e.g. score makes more sense than s, although they are both valid.

Standard Input (Scanner)

  • Read single-line input

The simplest way to obtain data from the standard input is to use the standard class Scanner. It allows a program to read values of different types (string, numbers, etc) from the standard input.

1
import java.util.Scanner;

Do not forget the ; in the end of thois Statement

Then construct an object of Scanner class.

1
Scanner scanner = new Scanner(System.in);

To read the input data, use:

  • scanner.next() for a single word or an integer number (will read the input till the whitespace)

  • scanner.nextLine() for any string with whitespace, tab,non-printing characters or whatever

    Input will be processed as string

  • Read multiline input

    nextLine() will read input from the position of the cursor till the new line (and again, if there is such a line in your input). If there is no anything left to read in the current line, the nextLine() method will return an empty line (“”) and place the cursor at the beginning of a new line.

For example, the content below will be processed by Java like this:

Content:

1
2
3
4
5
|This is a simple

multiline input,

that is being read

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Scanner; 

public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

String word1 = scanner.next(); // "This"
String line1 = scanner.nextLine(); // " is a simple"
String word2 = scanner.next(); // "multiline"
String word3 = scanner.next(); // "input,"
String line2 = scanner.nextLine(); // ""

}
}

Arithmetic operations

  • Binary arithmetic operators
    • addition +
    • subtraction -
    • multiplication *
    • integer division /
    • remainder %

The / operator returns the integer part of the division of two integer numbers, and any fractional part is discarded.

1
2
System.out.println(8 / 3); // prints 2
System.out.println(41 / 5); // prints 8

The % returns the remainder of the division of two numbers. When the dividend is less than the divisor, the quotient is zero and the remainder equals the dividend.

1
2
3
System.out.println(10 % 3) // prints 1, because 10 divided by 3 leaves a remainder of 1
System.out.println(12 % 4) // prints 0, because 12 divided by 4 leaves no remainder
System.out.println(5 % 9) // prints 5, because 5 divided by 9 leaves a remainder of 5
  • Unary operators

    • The unary plus operator indicates a positive value. It’s an optional operator.
    1
    System.out.println(+5); // prints 5
    • The unary minus operator negates a value or an expression.
    1
    2
    System.out.println(-8);  // prints -8
    System.out.println(-(100 + 4)); // prints -104
  • Precedence Order

    • parentheses
    • unary plus/minus
    • multiplication, division
    • addition, subtraction

Integer types and operations

If a number ends with the letter L or l it is considered as long, otherwise, it is int. It is recommended to use the uppercase letter L.

Use =, /=, %= += to make operation concise

  • Read numbers from standard input

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import java.util.Scanner;

    class Main {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    int a = scanner.nextInt();
    int b = scanner.nextInt();

    int sum = a + b;

    System.out.println(sum);
    }
    }

    long can be used in replace of int.

    1
    2
    3
    long a = scanner.nextLong();
    long b = scanner.nextLong();
    long sum = a + b;

Increment and decrement

1
2
3
4
5
6
7
int n = 10;
n++; // 11
n--; // 10
//------------//
int n = 10;
n += 1; // 11
n -= 1; // 10
  • prefix (++n or --n) increases/decreases the value of a variable before it is used;

  • postfix (n++ or n--) increases/decreases the value of a variable after it is used.

1
2
3
4
5
int a = 4;
int b = ++a;
// ++a = a = 5
System.out.println(a); // 5
System.out.println(b); // 5

The value of a has been incremented and then assigned to b. So, b is 5.

1
2
3
4
5
int a = 4;
int b = a++;
// a++ = 4; a = 5
System.out.println(a); // 5
System.out.println(b); // 4

Postfix operator has higher precedence than the assignment operator.

When assigning a++ to b, we actually assign 4, while a itself has already been incremented. So, b is 4 and a is 5.

1
2
int a = 4;
System.out.println(a++ + a); // this is 9

Characters

1
2
3
4
5
char lowerCaseLetter = 'a';
char upperCaseLetter = 'Q';
char number = '1';
char space = ' ';
char dollar = '$';
  • Initializing with unicode

    1
    2
    char ch = '\u0040'; // it represents '@'
    System.out.println(ch); // @

    Any char variable may be considered as an unsigned integer value in the range from 0 to 65535.

    1
    2
    char ch = 64;
    System.out.println(ch); // @
  • Subsequent characters

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    char ch = 'b';
    ch += 1; // 'c'
    ch -= 2; // 'a'
    // --------------------- //
    char ch = 'A';
    ch += 10;
    System.out.println(ch); // 'K'
    System.out.println(++ch); // 'L'
    System.out.println(++ch); // 'M'
    System.out.println(--ch); // 'L'
    • Escape sequences

      • '\n' is the newline character;
      • '\t' is the tab character;
      • '\r' is the carriage return character;
      • '\\' is the backslash character itself;
      • '\'' is the single quote mark;
      • '\"' is the double quote mark.
      1
      2
      3
      4
      System.out.print('\t'); // makes a tab
      System.out.print('a'); // prints 'a'
      System.out.print('\n'); // goes to the new line
      System.out.print('c'); // prints 'c'

      Code above will be phrased as :

      1
      2
        a
      c

String

  • immutable type: it’s impossible to change a character in a string;

  • it has methods for getting individual characters and extracting substrings;

  • individual characters can be accessed by indexes, the first character has the index 0, the last one – the length of the string1;

  • non-primitive type.

  • A string can be null. It means no value assigned.

    1
    String nullString = null; // it is null
  • Another way to create a variable of String is by using the keyword new.

1
String str = new String("my-string"); // it creates an object and assigns it to the variable

Methods

Documentation here.

Any string has two useful methods:

  • length() returns the number of characters in the string;
  • charAt(int index) returns a character by its index;
1
2
3
4
5
6
7
String s = "Hi, all";

int len = s.length(); // the len is 7

char theFirstChar = s.charAt(0); // 'H' has the index 0

char theFifthChar = s.charAt(4); // 'a' has the index 4
  • isEmpty() returns true if the string is empty, otherwise – false;
  • toUpperCase() returns a new string in uppercase;
  • toLowerCase() returns a new string in lowercase;
  • startsWith(prefix) returns true if the string starts with the given string prefix, otherwise, false;
  • endsWith(suffix) returns true if the string ends with the given string suffix, otherwise, false.
  • contains(...) returns true if the string contains the given string or character;
  • substring(beginIndex, endIndex) returns a substring of the string in the range: beginIndex, endIndex - 1;
  • replace(old, new) returns a new string obtained by replacing all occurrences of old with new that can be chars or strings.
  • trim() returns a copy of the string obtained by omitting the leading and trailing whitespace. Note that whitespace includes not only space character, but mostly everything that looks empty: tab, carriage return, newline character, etc.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
String text = "The simple text string";

boolean empty = text.isEmpty(); // false

String textInUpperCase = text.toUpperCase(); // "THE SIMPLE TEXT STRING"

boolean startsWith = textInUpperCase.startsWith("THE"); // true

/* replace all whitespaces with empty strings */
String noWhitespaces = textInUpperCase.replace(" ", ""); // "THESIMPLETEXTSTRING"

String textWithWhitespaces = "\t text with whitespaces !\n \t";

String trimmedText = textWithWhitespaces.trim(); // "text with whitespaces !"

Concatenation

Two strings can be concatenated using the “+” operator or the concat method.

1
2
3
4
5
6
7
8
String firstName = "John";
String lastName = "Smith";

// concatenation using the "+" operator
String fullName1 = firstName + " " + lastName; // "John Smith"

// concatenation using the concat method
String fullName2 = firstName.concat(" ").conc

Append

1
2
String str = "str" + 10 + false; // the result is "str10false"
// Will be converted into String
1
2
3
4
5
String shortString = "str";
int number = 100;

String result1 = shortString + number + 50; // the result is "str10050"
String result2 = number + 50 + shortString; // the result is "150str"

Compare

only addresses will be compared, but not actual values.

1
2
3
4
5
6
7
8
9
10
11
String first = "first";
String second = "second";

String anotherFirst = "first";
String secondInUpperCase = "SECOND";

System.out.println(first.equals(second)); // false, the strings have different values
System.out.println(first.equals(anotherFirst)); // true, the strings have the same value

System.out.println(second.equals(secondInUpperCase)); // false, the strings have different cases
System.out.println(second.equalsIgnoreCase(secondInUpperCase)); // true, it ignores cases

Logical operators

  • NOT is a unary operator that reverses the Boolean value. It is denoted as !.
1
2
boolean f = false; // f is false
boolean t = !f; // t is true
  • AND is a binary operator that returns true if both operands are true, otherwise, it is false. It is denoted as &&.
1
2
3
4
boolean b1 = false && false; // false
boolean b2 = false && true; // false
boolean b3 = true && false; // false
boolean b4 = true && true; // true
  • OR is a binary operator that returns true if at least one operand is true, otherwise, it returns false. It is denoted as ||.
1
2
3
4
boolean b1 = false || false; // false
boolean b2 = false || true; // true
boolean b3 = true || false; // true
boolean b4 = true || true; // true
  • XOR (exclusive OR) is a binary operator that returns true if boolean operands have different values, otherwise, it is false.
1
2
3
4
boolean b1 = false ^ false; // false
boolean b2 = false ^ true; // true
boolean b3 = true ^ false; // true
boolean b4 = true ^ true; // false

The XOR operator is used less often than others. Just remember that Java has it. If you really need it, you can use it.

Priority: ! (NOT) > ^ (XOR) > && (AND) > || (OR).

Relational operators

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • >= (greater than or equal to)
  • < (less than)
  • <= (less than or equal to)

Priority: Logical operators < Relational operators < arithmetic operators.

Conditional Statement

1
2
3
if (b) { // or !b  (Condiction in the bracket is true)
// do something
}

Ternary operator

Conditional Statement:

1
2
3
4
5
6
7
8
9
int a = ...;
int b = ...;
int max = ...;

if (a > b) {
max = a;
} else {
max = b;
}

Ternary Operator:

1
int max = a > b ? a : b;

that is to say:

1
result = condition ? trueCase : elseCase;

Another sample to judge even or odd number:

1
2
int num = ...;  // it's initialized by a value
System.out.println(num % 2 == 0 ? "even" : "odd");

For-loop

Basic framework:

1
2
3
for (initialization; condition; modification) {
// do something
}
  • initialization statement is executed once before the loop begins; usually, loop variables are initialized here;
  • condition is a Boolean expression that determines the need for the next iteration; if it’s false, the loop terminates;
  • modification is a statement that changes the value of the loop variables; it is invoked after each iteration of the loop; usually, it uses increment or decrement to modify the loop’s variable.

it is also possible to write an infinite loop without these parts at all:

1
2
3
for (;;) {
// do something
}

An example…

1
2
3
4
5
6
7
for (int i = 1; i < 10; i++) {
for (int j = 1; j < 10; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}

Which will print:

1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81

Switch Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
switch (variable) {
case value1:
// do something here
break;
case value2:
// do something here
break;

//... other cases

case valueN:
// do something here
break;
default:
// do something by default
break; // it can be omitted
}
An example: 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int val = ...;
switch (val) {
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("The value is less than zero or greater than two");
}

It is highly recommended to add a break after each case.

If a case meets the according condition, the following case will be executed directly from the entry point without judgement

Since Java 14, switch can be treated as an expression, returning a value from the statement. To achieve that a new switch**-**related keyword yield was introduced which works as a return statement.

1
2
3
4
5
6
7
8
9
10
int count = switch (day) {
case "Monday":
yield 1;
case "Tuesday":
yield 2;
...

default:
yield -1;
};

Unit of information

The smallest unit of information is the bit (b). 1 and 0.

A byte (B) means 8 bits

bit numbers use the lowercase letter “b” while the bytes are capital “B”.

SI metric Symbol Powers of ten IEC metric Symbol Powers of two
Kilobyte kB 10^3 B (1000 B) Kibibyte KiB 2^10 B (or 1024 B)
Megabyte MB 10^6 B (1000 kB) Mebibyte MiB 2^20 B (or 1024 KiB)
Gigabyte GB 10^9 B (1000 MB) Gibibyte GiB 2^30 B (or 1024 MiB)
Terabyte TB 10^12 B (1000 GB) Tebibyte TiB 2^40 B (or 1024 GiB)
Petabyte PB 10^15 B (1000 TB) Pebibyte PiB 2^50 B (or 1024 TiB)

Datatype in Java (number)

  • byte: size 8 bits (1 byte), range from -128 to 127
  • short: size 16 bits (2 bytes), range from -32768 to 32767
  • int: size 32 bits (4 bytes), range from −(231) to (231)−1
  • long: size 64 bits (8 bytes), range from −(263) to (263)−1
  • Floating-point typesdouble (64 bits) and float (32 bits).

Note, that when we declare and initialize a float variable, we should mark the assigned value with the special letter f. It is often a good practice to mark a long value with l as well.

Casting

Implicit casting

Transformation will be automatically completed by compiler and there is no loss in most cases when transforming.

The direction of implicit casting:

img

  • from int to long:
1
2
int num = 100;
long bigNum = num; // 100L
  • from long to double:
1
2
long bigNum = 100_000_000L;
double bigFraction = bigNum; // 100000000.0
  • from short to int:
1
2
short shortNum = 100;
int num = shortNum; // 100
  • from char to int: (Will get the ASCII code of the according character)
1
2
char ch = '?';
int code = ch; // 63

However, the loss could exist in some cases: int to float, or a long to float nor to double

1
2
long bigLong =  1_200_000_002L;
float bigFloat = bigLong; // 1.2E9 (= 1_200_000_000)

Explicit casting

Usage:

1
(targetType) source
1
2
3
4
5
6
7
8
9
10
11
12
13
double d = 2.00003;

// it loses the fractional part
long l = (long) d; // 2

// requires explicit casting because long is wider than int
int i = (int) l; // 2

// requires explicit casting because the result is long (indicated by L)
int val = (int) (3 + 2L); // 5

// casting from a long literal to char
char ch = (char) 55L; // '7'

Branching Statements

Break Statement

  • it terminates the current loop of any type (for, while, do-while);
  • it terminates a case in the switch statement (if-else);
1
2
3
4
5
6
7
int i = 10;
while (true) { // the condition to continue the loop
if (i == 0) { // the condition to perform break that stops this loop
break;
}
i--;
}

Another trick using break to print pyramid:

1
2
3
4
5
6
7
8
9
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(j + " ");
if (i == j) {
break;
}
}
System.out.println();
}

The output will be printed like:

1
2
3
4
5
6
7
8
9
10
0 
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9

Continue statement

It causes a loop to skip the current iteration and go to the next one.

  • inside the for-loop, the continue causes control to immediately move to the increment/decrement statement;
  • inside the while or do-while loop, control immediately moves to the condition.
1
2
3
4
5
6
7
int n = 10;
for (int i = 0; i < n; i++) {
if (i % 2 != 0) {
continue;
}
System.out.print(i + " ");
}

The output will be like:

1
0 2 4 6 8

Which is in fact another realization of the counter condition:

1
2
3
4
5
6
int n = 10;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}

An interesting code for practice:

1
2
3
4
5
6
7
8
9
10
for (int i = 0; i < 5; i++) {
System.out.println(i);
if (i < 3) {
continue;
} else {
for (int j = 0; j < 5; j++) {
System.out.println(j);
}
}
}

The visualized result can be accessed below:

https://cscircles.cemc.uwaterloo.ca/java_visualize/#code=public+class+main%7B%0A+++public+static+void+main(String%5B%5D+args)%7B%0A+++for+(int+i+%3D+0%3B+i+%3C+5%3B+i%2B%2B)+%7B%0A++++System.out.println(i)%3B%0A++++if+(i+%3C+3)+%7B%0A++++++++continue%3B%0A++++%7D+else+%7B%0A++++++++for+(int+j+%3D+0%3B+j+%3C+5%3B+j%2B%2B)+%7B%0A++++++++++++System.out.println(j)%3B%0A++++++++%7D%0A++++%7D++++++++%0A%7D%7D%0A%7D&mode=display&curInstr=61

Defining methods

A method has…. (bolded elements are compulsory)

  1. a set of modifiers (public, static, etc.);
  2. a type of the return value;
  3. a name;
  4. a list of parameters (as well known as formal parameters) in parenthesis ();
  5. a list of exceptions;
  6. a body containing statements to perform the operation.

An example:

1
2
3
public static int sum(int a, int b) {
return a + b;
}

The combination of the name of a method and its parameter types is called the signature. It doesn’t include the returning type, modifiers, and names of parameters.

The considered method sum has the following signature sum(int, int).

Naming Methods

a method name should be a legal identifier with following attributes:

  • identifiers are case-sensitive;
  • an identifier can include Unicode letters, digits, and two special characters ($,_);
  • an identifier can’t start with a digit;
  • identifiers must not be a keyword.

Setting returning value type and parameters

1
2
3
public static void printSum(int a, int b) {
System.out.println(a + b);
}

The code above prints the sum and returns no value due to void.

When you call a method with a value of a primitive type then a copy of the value is created. Inside a method, you can process this copy. If you change it, the passed argument is not changed.

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
int val = 100; // 100
change(val); // try to change val
System.out.println(val); // it prints "100", because the method didn't change val, only its copy
}

/**
* The method changes the given value
*/
public static void change(int val) {
val = 400; // here, the copy is 400
}

Why Homebrew?

Homebrew官网 https://brew.sh/index_zh-cn 对Homebrew的定义是:

macOS(或 Linux)缺失的软件包的管理器

Homebrew 类似于Linux上的yum与apt-get。有了Homebrew,你可以轻松使用进行以下操作:

  • 使用一句命令自动下载,安装或卸载所需要的软件与依赖包
  • 轻松管理服务的停止与启动

以CPT103课程需要用到的mysql为例,有了Homebrew,你只需要在终端中键入

1
brew install mysql

就可以一键完成mysql的下载与环境配置. Homebrew还会在安装结束时主动显示提示用户可能需要的下一步操作(caveats)。下图是使用Homebrew安装完mysql后现实的caveats,提示用户修改mysql的默认密码和启动服务的命令。

于此同时,由于清华大学Tuna协会提供了Homebrew的国内高速镜像,因此替换完镜像后的Homebrew下载速度奇快,再也不需要通过魔法上网获取所需要的软件。

How to install?

安装开发工具包

首先需要确保你的Mac中已经安装好开发工具包,打开“系统实用工具”中的“终端”,在终端中输入 xcode-select --install ,系统会自动安装好缺少的开发工具。如果你遇到了下图的提示,说明你已经安装好了开发工具包,可以直接跳到下一步操作。

另外,由于Homebrew只能通过终端输入命令进行交互,因此建议把终端放在Dock栏中,以便快速打开。

安装Homebrew

如果你会魔法⚡⚡,或者身在国际互联网畅通无阻的国家,你可以直接在终端中键入Homebrew官方的命令进行安装:

1
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

如果你只是一只还没有写完作业的苦逼学生,你可能需要使用国内镜像进行快速安装,小猿提供了修改后的脚本,让你可以使用位于Tuna清华大学的服务器下载安装Homebrew,以下是食用方式:

  1. 使用浏览器下载这个文件: https://gitee.com/isnowify/xjtluxiaoyuan/raw/master/installbrew.sh

  2. 在终端中输入以下命令(留意最后的空格)

    1
    HOMEBREW_CORE_GIT_REMOTE=https://mirrors.tuna.tsinghua.edu.cn/git/Homebrew/Homebrew-core.git bash 

    并将刚刚下载好的文件拖入终端内

按下回车键,终端便开始腹泻式安装Homebrew,期间可能会需要输入你的Mac密码,按照提示操作即可。我们录制了一个小小的GIF,帮助你更好的完成Homebrew的安装

耐心等待一会,当我们看到Installation successful, 说明Homebrew已经成功安装。

替换Homebrew下载源

安装好Homebrew以后,我们需要替换Homebrew的下载源,让Homebrew下载软件包的速度比香港记者还快

替换bottle源

依次在终端中输入以下两行命令

1
2
echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/Homebrew-bottles' >> ~/.bash_profile
source ~/.bash_profile

替换core与cask源

依次逐行键入以下命令

1
2
3
4
5
6
7
8
9
10
11
12
13
# brew 程序本身,Homebrew/Linuxbrew 相同
git -C "$(brew --repo)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/Homebrew/brew.git

# 以下针对 mac OS 系统上的 Homebrew
git -C "$(brew --repo Homebrew/core)" remote set-url origin
https://mirrors.tuna.tsinghua.edu.cn/git/Homebrew/Homebrew-core.git
git -C "$(brew --repo Homebrew/cask)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/Homebrew/Homebrew-cask.git
git -C "$(brew --repo Homebrew/cask-fonts)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/Homebrew/Homebrew-cask-fonts.git
git -C "$(brew --repo Homebrew/cask-drivers)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/Homebrew/Homebrew-cask-drivers.git


# 更换后测试工作是否正常
brew update

至此,我们完成了Homebrew的下载,安装与源替换。

一些常用命令

1.安装卸载软件

  1. brew --version或者brew -v 显示brew版本信息
  2. brew install <name> 安装指定软件
  3. brew unistall <name> 卸载指定软件
  4. brew list 显示所有的已安装的软件
  5. brew search text 搜索本地远程仓库的软件,已安装会显示绿色的勾
  6. brew search /text/ 使用正则表达式搜软件

2. 升级软件相关

  1. brew update 自动升级Homebrew(从github下载最新版本)
  2. brew outdated 检测已经过时的软件
  3. brew upgrade 升级所有已过时的软件,即列出的以过时软件
  4. brew upgrade <formula>升级指定的软件
  5. brew pin <formula> 禁止指定软件升级
  6. brew unpin <formula> 解锁禁止升级
  7. brew upgrade --all 升级所有的软件包,包括未清理干净的旧版本的包

3. 清理相关

Homebrew再升级软件时候不会清理相关的旧版本,在软件升级后我们可以使用如下命令清理

  1. brew cleanup -n 列出需要清理的内容

  2. brew cleanup <formula> 清理指定的软件过时包

  3. brew cleanup 清理所有的过时软件

  4. brew unistall <formula> 卸载指定软件

  5. brew unistall <fromula> --force 彻底卸载指定软件,包括旧版本

写在最后

这篇文章也可以在https://isnowify.com上找到,更加适合电脑端阅读。

Reference

  1. Homebrew 替换国内镜像源 https://frankindev.com/2020/05/15/replace-Homebrew-source/
  2. HomeBrew常规使用教程: https://juejin.im/post/6844903549051076622
  3. Homebrew官网: https://brew.sh/index_zh-cn
  4. 清华大学Tuna镜像源Homebrew页面:https://mirrors.tuna.tsinghua.edu.cn/help/Homebrew/

Java 随缘杂谈

小猿排版大升级!

CPT 105 第一周的课时已经差不多结束了,小猿根据一些同学提的问题写了这篇杂谈。这个系列是根据 CPT105 的教学进度以及同学提问而写的技术向杂谈,一到两周一更,比较随性,不成系统。以后的更新将以专题为主。

在阅读本文之前请先仔细阅读 CPT105 Tutorial以及课件, 并且观看课程视频。

JDK, JRE, JVM

你可能会对这三个名词感到有些糊涂,先给结论: JDK 包含 JRE ,JRE 包含 JVM

JDK: Java Development Kit Java开发工具包,提供了Java运行环境和Java开发工具

JRE: Java Runtime Environment Java运行时环境,安装了JavaRE 的设备可以运行Java程序

JVM: Java Virtual Machine Java虚拟机,Java代码事实上运行在JVM中。JVM是Java跨平台特性实现的载体,Java的核心竞争力所在,这里不铺开讲。有兴趣的自行百度。

Java 程序的组织结构

Java中的源文件以 项目(project) - 包(package) - 源文件(.java文件) 的层级结构组织起来,我们就是在源文件里敲代码。

类 (class) 和 .java 文件的关系

现阶段可以暂时认为一个.java 文件就是一个 class

作为一门面向对象编程 (OOP) 的语言,Java中的一切依托于类存在

方法 method

方法分为数个部分:修饰符,返回类型,方法签名 (method signature) 和方法体

1
2
3
4
访问权限修饰符 是否为静态方法 返回值类型 方法名称(参数表)
{
方法体
}
1
2
3
4
public static void myMethod()
{
System.out.println("Hello\nWorld");
}

其中方法签名包含了方法名称和参数表。方法的创建和调用应该会在下周学到,不用操之过急,这里只给一个基本的概念。

变量 (variable)

可执行Java程序 & 主类 (main class)

1
2
3
4
5
public class MyClass{
public static void main(String[] args){
//my code
}
}

main()方法 (method) 是java程序执行的起点,所有含有main()方法的java源文件都是可执行(run)的。

NetBeans 提供两种执行模式,一是单独执行当前源文件( 前提是当前源文件中含有main()方法 ):

另一种是执行当前项目:

项目的执行从当前项目的主类 (main class) 的 main()方法开始,Run Project之后的括号里就注明了当前的主类(Lab_01).

所有含有main()方法的源文件都有资格成为主类,而相应的,在执行项目时,只有主类的 main() 方法会被执行。

NetBeans 中如何修改主类:

点击Browse便可以查看所有有资格成为主类的类,并自定义主类

Java中变量有八个基本类型:

整数类型:int (整型), long(长整型), short(短整型), byte (字节)

字符类型:char

布尔量:boolean

浮点数(小数): float(单精度浮点类型), double(双精度浮点类型)

数据类型属于编程基础,但是内容又比较多,过两天专门写一篇文章讲吧(咕咕咕)。

变量需要定义,定义后的变量可以赋值,同名变量不可以重复定义,变量有生存期和作用域。

1
2
3
4
int num1 = 2;//定义
int num2 = 3;//定义
num1 = 10; //赋值
num1 = num2; //赋值

生存期作用域以及相关的变量类型过两天专门写一篇文章讲(咕咕咕)。

System.out.println()

System.out.println()是标准输出家族中常用的方法之一。其作用是在output console中输出括号中的内容并换行,如果要输出文本内容,记得加双引号。

System.out.print()一样会输出括号中的内容,但是不会自动换行。

手动换行的方式是在文本中插入 \n , 有兴趣的可以百度逃逸字符自行了解。

可以运行 System.out.print("Hello\nWorld");

用 + 连接文本

加号是Java唯一的重载运算符, 可以用来链接文本内容,在Java中,我们称文本内容为字符串 (String),当加号和字符串相邻出现时,会自动调用重载后的功能。

可以运行下面的语句体会与字符串一起使用时+号的功能

1
2
3
System.out.println("6" + "3");
System.out.println("6" + 3);
System.out.println(6 + 3);

从源文件到可执行文件

本周 CPT105 的教案中提及了.java 文件和 .class 文件。编程语言更接近人类的自然语言,计算机是无法”理解”的,计算机 (cpu) 只能”理解”二进制指令。编程语言发展至今,已经在二进制语言的基础上进行了多层抽象,全然见不到二进制指令的影子了,因此人机之间需要”翻译者”,这个”翻译者”就是编译器,而翻译的过程就称为编译 (compile)。.class 文件可以简单理解为 .java 文件经过翻译后的产物。

而事实上,.class文件被称作字节码(byte code),是提供给JVM执行的。

运算

编程语言中的运算符分为单目运算符,双目运算符,以及三元运算符

基本的: + 加 - 减 *乘 /除 %取余

自增自减运算符(单目): ++ ,–

a++ 等价于 a = a+1a-- 等价于 a = a-1

逻辑运算符: >, <, >=, <=, &&, ||

按位运算: << 左移 >> 右移 ^ 按位异或 &按位与 | 按位或

独自探索java

https://docs.oracle.com/en/java/javase/12/docs/api/index.html

这是Java官方的API文档,可能你现在看不懂他,但是在未来他必然会成为你的良师益友。想要自主学习Java的同学可以选择 《Java核心技术 卷 1》,或者观看B站,Mooc等平台的课程。

马上百粉啦,小猿正在给各位老粉整理 pdf 教材作为福利,现在关注你也是老粉!

有任何问题可以在后台给小猿留言。