UCB CS61b——Introduction

Hello world

package hello_pkg;

public class hello_world {
    public static void main(String[] args){
        System.out.println("Hello world Phoebe");
    }
}

Simple loop

package hello_pkg;

public class hello_nums {
    public static void main(String[] args){
        int x = 1;
        while (x<10){
            System.out.println(x);
            x = x+1;
        }
    }
}
/*
1. Before Java variables can be used, they must be declared first.
2. Java variables must have a specific type;
3. Java variables can not be changed, for example, after we declare x as int, we can not write x = 'horse'
   or string x = 'horse' since variable x has been declared as int.
4. Types are verified before the code runs.
if we write x = 'horse' after the loop, the code even won't run and will give us the error message, while in python
if we write x = 1+'fre' after the loop, we still get 0 to 9 first and get error message.
Here is a huge difference between Java and python, java is more strict about types of variables which makes it easier
to debug and you will know that x should always be an integer.
*/

Larger number

package hello_pkg;

public class largerdemo {
    /** we can use this to demonstrate the function since some software will use /** to find sentences to build a document */
    public static int larger(int x, int y){
        if (x > y){
            return x;
        }
        return y;
    }
    public static void main(String[] args){
        System.out.println(larger(-5, 10));
    }
}
/*
1. functions are declared as a part of a class in Java.
    A function in Java is called "method", so all functions in Java are methods.
2. To define a function we use public static while we may use other definitions later.
3. All variables in a function must have declared type and the return variable must have declared type too.
    Java functions only return one value.
4. To run a Java code, we must define a main method, now we are using public static void main(String[] args){}.

*/

你可能感兴趣的:(Java)