Java Basic

learning web: https://ocw.mit.edu/ans7870/6/6.005/s16/index.html

Introduction to Java

While there are many IDEs with built-in execution capabilities (Eclipse and IntelliJ for example), Java can also be run directly from the command line.

Before you can run the program from the command line, you must compile it. Open your terminal or command prompt (depending on OS), and navigate to the directory where the file you want to run is located. Once there, use javac and the filename to compile:

1
javac MyClass.java

This creates the .class file that can be executed. However, if there are any bugs found in your program, they will be flagged at this point, and the executable .class file will not be created. You won’t be able to run the file until it compiles with no issues.

Once you have your executable file, use java and the name of the class to run it:

1
java MyClass

Note: Do not include the .java or .class suffixes, only use the name of the class.

Let’s say we had the following Java class:

1
2
3
4
5
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

We would compile this using:

1
javac HelloWorld.java

Then run it using:

1
java HelloWorld

It would output the following:

1
Hello world!

Details

Language type

Statically typed languages

A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is; other languages (e.g.: Java, C, C++) offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala, Kotlin).

The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.

Examples: C, C++, Java, Rust, Go, Scala

Dynamically typed languages

A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference).

Examples: Perl, Ruby, Python, PHP, JavaScript, Erlang

Most scripting languages have this feature as there is no compiler to do static type-checking anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.

Both Interpreter and compiler

java has both interpreter and compiler.

If you have no idea what the differences are, click the link below:

Compiler and Interpreter

JVM structure

https://dzone.com/articles/jvm-architecture-explained

2021年 java虚拟机jvm性能调优实战+面试_哔哩哔哩_bilibili

Details supplement

: Why Static methods can’t call the non-static methods? (Also answered the question “What do we actually mean when we say that we load class, store the methods”)

https://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static

https://softwareengineering.stackexchange.com/questions/348662/static-vs-non-static-in-java-in-terms-of-memory-state/348677

【新面试题】Java中的静态方法为什么不能调用非静态方法 - 知乎 (zhihu.com)

Java Syntax

Variable

1
2
3
4
5
int x; // declaration
x = 3; // assignment
int y = 3; // initialization

final double pi = 3.1415926; // final means can't be assigned anymore.

String

difference between String.equals and ==

1
2
3
4
5
String s1 = new String("java");
String s2 = new String("java");

System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); //true

java:String使用equals和==比较的区别

String methods

1
2
3
4
5
6
String.length()
String.CharAt() // index -> char
String.indexOf() // char -> index
String.trim() // move the space infont and behind the string
String.replace('a', 'b') // change all 'a' in the string to 'b'

Loop

Java is an object-oriented programming language, which means it consists of classes and their methods. Unlike some other programming languages, Java only has methods (which are associated with classes), and no functions.

but a for-each loop is simpler and more straightforward:

1
2
3
for (String s : myArray) {
// Do something
}

Scanner

difference between scanner.next and scanner.nextLine

When encountering the space、tab or \n, scanner.next just stop reading in, and leave the blank character in the input buffer.

The scanner.nextLine end reading until \n comes up, and it just throw away that \n.

scanner.next will first skip the blank character and read in the normal character until encounter the blank again.

Whereas scanner.nextLine may get stuck in the beginning of reading.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
input:ab cd
scanner.next() // get [ab]
scanner.nextLine() // get [ cd], have a space in the front

input:ab cd
scanner.next() // get [ab]
scanner.next() // get [cd], does not have a space in the front

input:ab
scanner.next() // get [ab]
input:cd
scanner.nextLine() // get nothing, because it just encountered \n and just threw it away

input:ab
scanner.next() // get [ab]
input:cd
scanner.next() // get [cd]

Wrapper class

wrapper class = provides a way to use primitive data types as reference date types

reference data types contain useful methods can be used with collections (ex. ArrayList)

1
2
3
4
5
6
// primitive      //wrapper
//---------- //--------
// boolean Boolean
// char Character
// int Interger
// double Double

autoboxing = the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

unboxing = the reverse of autoboxing. Automatic conversion of wrapper class to primitive classes.

Array

An array is a fixed collection of values with the same data type.

Only after initialization, can we use the array with the index.

1
2
3
4
5
int[] lottoNumbers; // declaration
lottoNumbers = {12, 29, 4, 38, 3}; // assignment

int[] lottoNumbers = {12, 29, 4, 38, 3}; // initialization
dataType[] emptyArrayName = new dataType[number of elements in array]; // initialization

ArrayList

ArrayList = a resizable array that only store reference data types.

Elements can be added and removed after compilation phase.

2D ArrayList = a dynamic list of lists.

You can change the size of thses lists during runtime.

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

ArrayList<ArrayList<String>> shopping_list = new ArrayList();
ArrayList<String> fruit = new ArrayList();
ArrayLisr<String> vegetable = new ArrayList();

fruit.add("apple");
fruit.add("banana");
fruit.set(1, "orange");
// fruit.set(2, "orange"); This is incorrect, we can not set in a new position.

shopping_list.add(fruit);
System.out.printIn(shopping_list.get(0).get(0)); // apple

Overloaded methods

overloaded methods = methods that share the same name but have different parameters

method name + parameters = method signature.

1
2
3
4
5
6
7
8
static int add(int a, int b){
return a + b;
}

// overloaded
static int add(int a, int b, int c){
return a + b + c;
}

Object Oriented Programming(OOP)

object = an instance of a class that may contain attributes and methods.

Constructor

constructor = special method that is called when an object is instantiated(created).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Pizza{
// attributes
String bread;
String cheese;
int size;

// constructor
Pizza(String b, String c, int s){
this.bread = b;
this.cheese = c;
this.size = s;
}


}

ToString

1
2
3
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, when we call the method or just print the object like this:

1
2
3
System.out.println(objectname)
System.out.println(objectname.toString)
// get: Classname@address

And we can rewrite it using overloaded method:

1
2
3
public String toString(){
return attributes1 + '\n' + attributes2...
}

Static

static = modifier. A single copy of a variable/method is created and shared.

The class “owns” the static member.

Static variable

static variable explanation

Static method

static method explanation

继承 + 文件、流 + 线程 + jvm详细