CPT111-小豪的笔记

CPT111-自学笔记


Brief Introduction to the Module

Students will learn the basics of programming in Java and in particular Object Oriented Programming.

1. What is java?

1.1 What is Java?

  • Created by James Gosling
  • Modern object-oriented language
    • continuously improved since 1990s
  • Widely used
    • mars rover, cell phones, web servers, …

1.2 Text Editor, Command Line Compilation and Execution

  • We can use a text editor to write the source

    • code e.g. Notepad, Notepad++, Sublime Text
  • We can compile and execute in command line

    • need to set the environment variables first
    • javac is used to compile programs
    • java is used to execute programs
    • we must always compile before execution
  • Java source code is compiled into Java bytecode

1.3 Java Virtual Machine (JVM)

  • JVM executes the Java bytecode
    • JVM is installed on various platform
  • A Java class file is a file (with the . class filename extension) containing Java bytecode that can be executed on JVM

1

1.4 Object-Oriented Language

  • Java is an Object-Oriented Language:
    • every Java file must contain a class declaration
    • all code is written inside a class
    • to run a Java program, need to define a main method
  • Java’s language features:
    • braces/curly brackets are used to denote the beginning and end of a block/a section of code
      • e.g. a class or method declaration
    • statements end with semicolons
  • Violating one of the above will cause syntax errors

1.5 Static Typing

  • Java is a statically typed language:
    • all variables, parameters, and methods must have a declared type
      • also called their static type
    • variables must be declared before use
    • that type can never change
    • expressions also have a type, e.g. 5 + 10 has type int
  • Java compiler ensures type consistency
    • if types are inconsistent, the program will not compile
      • it is another example of syntax error

1.6 A simple Java program

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

2. Data Types

2.1 Data Types

2

Strings

  • Strings are objects, and have many methods
  • At basic level, can store text data
  • Note, double quotes needed around string String str = "This is a String";

char

represents a character (‘a’, ‘b’, ‘c’, etc)

  • A different data type

  • includes non-Roman characters (Chinese, Cyrillic, Arabic, Greek etc)

  • It is actually a 16 bit integer, range 0 - 65,535

Boolean

  • Its size varies; it only uses 1 bit, but can take up to 32 bits of memory!

2.2 Operator Precedence

++, -- > () > * / % > +, -

###Math Object and Random Numbers
3

2.3 The Scanner Object

import java.util.Scanner
//创建一个扫描器对象,用于接收键盘数据
        Scanner s= new Scanner(System.in);
        System.out.println("Please enter data: ");
        //用nextLine方式接收
        String str = s.nextLine();
        System.out.println("The output content is :"+str);

        s.close();
        //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉

输入其他格式

 if (scanner.hasNextDouble()
            double x = scanner.nextDouble();
  • get multiple number inputs
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num1 = Integer.parseInt(input);

input = sc.nextLine();
double num2 = Double.parseDouble(input);

input = sc.nextLine();
int num3 = Integer.parseInt(input);

###Casting and converting between types

double >> float >> long >> int >> short >> char >>byte

2.4 Using Wrapper Classes

  • The main use for wrapper classes is to convert text to primitive number types
String s = "999"
int res = Integer.parseInt(s);

String s = "99.021"
double res = Double.parseDouble(s);
  • We can also convert from a primitive to a string!
String s = "999"
int res = Integer.parseInt(s);
String out = Integer.toString(res);

String s = "99.021"
double res = Double.parseDouble(s);
String out = Double.toString(res);

boolean x = false;
String m = Boolean.toString(x);

2.5 Coding Style

Good programming style

  • Your programming code must be easily read by others and by yourself.
  • This saves time during program maintenance.
  • It also leads to less human induced error.
  • In software development projects, maintenance often accounts for 80% of effort.
  • Program readability is of utmost importance.
变量命名规范
  • 所有变量、方法、类名:见名知意
  • 类成员变量:首字母小写和驼峰原则:monthSalary
  • 除了第一个单词以外,后面的单词首字母大写
  • 局部变量:首字母小写和驼峰原则
  • 常量:大写字母和下划线:MAX_VALUE
  • 类名:首字母大写和驼峰原则:Man, GoodMan
  • 方法名:首字母小写和驼峰原则:run(), runRun()

3. Flow Control

3.1 Branching – if – else – else if

if (condition1){
    
}
else if (condition2) {
    
}
else {
    
}

3.2 While Loops

while (loop){
    
}
//
do {

} while(condition);

3.3 For Loop

for (initial
value;condition;increment){
    
}

3.4 Switch

switch(expression){
    case value:
        //语句
        break;//可选
    case value:
        //语句
        break;//可选
    //你可以有任意数量的case语句
    default://可选
        //语句
}

4. Array

	int[] nums; //1.声明一个数组
	nums =  new int[10];//2.创建一个数组
	//int[] nums = new int[10];
  • 获取数组长度

arrays.length

5. Static Methods and String

5.1 Function Implementation

修饰符 返回值类型 方法名(参数类型 参数名){
    ...
    方法体
    ...
    return 返回值;
    }
  • Parameter: A parameter is a variable in the declaration and definition of a method.
  • Argument: When a method is called, the arguments are the data that are passed into the method’s parameters, i.e. the actual value of the parameters.

5.2 Overloading

  • Static methods whose signatures differ are different static methods

  • Using the same name for two static methods whose signatures differ is known as overloading

  • 方法的重载的规则:

    • 方法名称必须相同。
    • 参数列表必须不同(个数不同、或类型不同、参数排列顺序不同等)。
    • 方法的返回类型可以相同也可以不相同。
    • 仅仅返回类型不同不足以成为方法的重载。

5.3 Char

  • isLetter(char c)

  • isDigit(char c)

  • isWhitespace(char c)

  • isUpperCase(char c)

  • isLowerCase(char c)

  • toUpperCase(char c)

  • toLowerCase(char c)

  • toString(char c)

5.4 String

  • length()

  • substring(int start)

  • substring(int start, int end)

    • notice the length of the resulting substring can be computed by subtracting end - start
  • equals()

  • Recall the == operator used to compare primitive types int, double, char

  • equalsIgnoreCase()

  • isEmpty()

  • contains(String substring)

  • startsWith(String prefix)

  • endsWith(String postfix)

  • toUpperCase()

  • toLowerCase()

  • chatAt(int i)

  • indexOf

    • it returns the index number where the target string is first found, or -1 if the target is not found
  • lastIndexOf

  • trim() this string with leading and trailing whitespace removed

  • replace(String a, String b) this string with a replaced by b

  • replaceAll(String a, String b) this string with all a’s replaced by b’s

  • String[] split(String delimiter) array of strings between occurrences of delimiter

6. Objects

6.1 Constructor

  • Can be used to assign values when an object is created (“constructed”)

  • Can also carry out any initial tasks

  • t can have parameters

  • Whatever parameters you want!

  • Can be used to assign values to the instance variables

public class className {
	public className(parameter) {
	
	}
}

this.____

  • It can refer to its own variables and methods
  • Can call any of its own methods within the class

6.2 Public and Private

  • If it is PRIVATE, can only be accessed by that class

    • Useful for internal methods
    • something that only needs to be done within the objects
  • If it is PUBLIC, then it can be accessed by other classes

    • Useful for object methods that need

6.3 Encapsulation

  • all attributes should be private
  • Internal workings should be private
  • Object should only share what it needs
  • Can use getter methods to access

● Getter / Accessor : return the value of an instance variable
● Setter / Mutator : set the instance variable to a new value

get/set (IDEA快捷键:alt + insert)

6.4 Static

  • Static means that there is only one instance for the entire class
  • If it is static, each object will overwrite the previous variable

Use of Static

  • Our main method is static, as there is only one main method in the entire program

  • If we want to count how many objects created

  • How many people objects?

6.5 Object Method

  • .equals()

    • In Java, we can use inheritance to “override” methods, and we can create an equals method
  • toString()

    • We need to define a toString method in our data class.

6.6 Inheritance

public class Pillar extends Swordsman{...}
  • The idea is to define a new class (subclass or child class) that inherits instance variables (attribute, state) and instance methods (operation, behavior) from another class (superclass or parent class)
    • enabling code reuse

####6.6.1 Subclass and Superclass

  • in Java, a class can only be a subclass of one superclass, but a superclass can be extended by many subclasses
6.6.2 Subclass Constructor and super()
  • A subclass inherits all of the superclass’ instance variables
    • however, the subclass cannot directly initialize the inherited instance variables that are declared in the superclass as private
    • use super() to call the superclass’ constructor and pass the initial values
public class Pillar extends Swordsman {
    public Pillar(String name) {
    	super(name);
    }
    public static void main(String[] args) {
    	Pillar kyojuro = new Pillar("Kyojuro");
    }
}
6.6.3 Inherited Methods
  • We can call the inherited public methods on the superclass’ instance
6.6.4 Overloading Constructor
  • We can overload the constructor
    • match the new constructor with the overloaded superclass constructor

Add instance variables

public class Pillar extends Swordsman {
    private String type;
    public Pillar(String name, String type) {
        super(name);
        this.type = type;
    }
    public Pillar(String name, int numDemonsKilled, String type) {
        super(name, numDemonsKilled);
        this.type = type;
    }
    public static void main(String[] args) {
    	Pillar kyojuro = new Pillar("Kyojuro", 1000, "Fire");
    }
}
6.6.5 Final Instance Variable
  • If the instance variable will never be changed after it is initialized, we can declare it to be final
public class Pillar extends Swordsman {
    private final String type;
    public Pillar(String name, String type) {
        super(name);
        this.type = type;
    }
    ...
}

Constant

public static final int MAX_HP = 100;
6.6.6 Overriding Method
  • Overloading: on same class, same name, different signature
  • Overriding: on subclass, same signature
6.6.7 @Override Annotation

We can put an annotation before the overriding method:

public class Pillar extends Swordsman {
    @Override
    public int attackDamage() {
    	return 1000 + 100 * getNumDemonsKilled();
    }
}
  • The purpose is
    • if we made a mistake such as typo on the method name or parameter
      • then we will get a compile error
  • without annotation, instead of overriding, we may overload the superclass method or introduce a new method by mistake
6.6.8 Calling Overriden Method

We can still call the overridden attackDamage() method of the superclass Swordsman by using super.

public class Pillar extends Swordsman {
    @Override
    public int attackDamage() {
    	return 1000 + 100 * super.attackDamage();
    }
}
6.6.9 Overriding toString()
  • We actually have been doing overriding when we write the toString() method
    • we overrode the toString() method of the Object class
public class Swordsman {
    @Override
    public String toString() {
        String alive;
        if (this.alive) alive = "alive";
        else alive = "dead";
        return "Swordsman " + name + " is " + alive +
        " and has killed " + numDemonsKilled + " demons";
    }
}

  • In Java, every class is a subclass of Object class
6.6.10 Final Instance Method
  • If you declare an instance method to be final, it cannot be overridden
public final int attackDamage(){}
6.6.11 Java’s Object superclass
  • As every class is a subclass of the java.lang.Object class, every class inherits
6.6.12 Converting between Subclass and Superclass
  • Sometimes we want to convert a subclass type to a superclass type
Swordsman kyojuro = new Pillar("Kyojuro", 1000, "Fire");
  • However, only methods of Swordsman (superclass) can be called
  • but, we can call the toString() method, which actually has been overridden in Pillar

6.7 Polymorphism

OOP feature polymorphism

  • superclass variable calls the overridden method of each specific subclass

7.Exception

7.1 Throwing our own exception object

public static int myIntDiv(int a, int b) {
if (b == 0)
throw new ArithmeticException("Cannot divide by zero!");
else
return a / b;
}

7.2 Catching an exception

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
try {
System.out.println(myIntDiv(1, n));
    //the risky function that might
throw an exception
}
catch (ArithmeticException e) {
System.out.println("You entered a zero!");
}
}

7.3 Displaying the error message

  • use getMessage() method called on the caught exception object
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
try {
System.out.println(myIntDiv(1, n));
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}

8. List

List<Integer> list = new ArrayList<>();
List<Integer> list = new LinkedList<>();

method:

  • adding list.add(5)
  • inserting list.add(1, 3)
  • assigning list.set(2, 7)
  • retrieving list.get(2)
  • length list.size()
  • remove list.remove(1)
  • remove all list.clear()

Create a list from an array

List<Integer> list = Arrays.asList(10, 20, 30)

合并List

list.addAll(list1);
list.addAll(list2);

###8.1 Enhanced For Loops

for (int x : list) {
System.out.print(x + " ");
}

9.Set and Map

Set<Integer> set = new HashSet<>();
  • adding set.add(5)
  • checking membership set.contains(5)
  • remove set.remove(5) present or not
  • union set.addAll(c) set ∪ c
  • intersection set.retainAll(c) set ∩ c
  • difference set.removeAll(c) set \ c
  • contain/subset set.containsAll(c) check whether set ⊇ c
  • size set.size()
  • clear contents set.clear()
Map<String, Integer> map = new HashMap<>();
  • map.put(key, val) adding the mapping key → val
  • map.get(key) get the value for a key
  • map.containsKey(key) test whether the map has the key
  • map.containsValue(value) test whether the map has the value
  • map.remove(key) delete a mapping
  • map.keySet() returns a set containing all keys

10. Recursion

It finds the smallest integer in an integer array recursively.

public static int smallest(int[] array) {
    return smallest(array, 0);
}

private static int smallest(int[] array, int start) {
    
        // base case
        if(start==array.length-1){
            return array[start];
        }


        // recursive step
        if(array[start]<array[start+1]){
            int temp=array[start];
            array[start]=array[start+1];
            array[start+1]=temp;
        }
        return  smallest(array,start+1);
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小豪GO!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值