1.数据类型
int,short,byte,long
double,float
char,String
2.变量
int var; var = 12; int var1 = 12;
final int v1 = 0; //常量
C/C++变量的声明和定义是分开的,JAVA不区分。
//c/c++ extern int a; //声明 int a = 0; //定义
3.运算符
JAVA的运算符、类型强制转化与C相似。
4.枚举
enum Size {SMALL,MIDIUM,LARGE};
5.字符串
//定义 String e = ""; String greeting = "hello";//子串 String greeting = "hello"; String s = greeting.substring(0,3);//拼接 String expletive = "Expletive"; String pg = "deleted"; String msg = expletive + pg; String msg1 =expletive + 1; String all = String.join("/","S","M","L","XL"); //"S/M/L/XL"//不可修改 String str = "Help"; str = str.substring(0,3) + "p!"; //Help!//检查字符串相等 s.equals(t); "Help".equals(greeting); "Hello".equalsIgnoreCase("help");//空串和null if(str.length() == 0)if(str.equals(""))if(str == null)
6.构建字符串
StringBuilder builder = new StringBuilder(); builder.append(ch); //append a charactor builder.append(str); //append a string
7.输入输出
import java.util.*;/*** This program demonstrates console input.* @version 1.10 2004-02-10* @author Cay Horstmann*/ public class InputTest {public static void main(String[] args){Scanner in = new Scanner(System.in);// get first inputSystem.out.print("What is your name? ");String name = in.nextLine();// get second inputSystem.out.print("How old are you? ");int age = in.nextInt();// display output on consoleSystem.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));} }
读取密码
Console cons = System.console(); String username = cons.readLine("User name:"); char[] passwd = cons.readPassword("Password:");
8.控制流程
控制流程与C相似
9.大数值计算
import java.math.*; import java.util.*;/*** This program uses big numbers to compute the odds of winning the grand prize in a lottery.* @version 1.20 2004-02-10* @author Cay Horstmann*/ public class BigIntegerTest {public static void main(String[] args){Scanner in = new Scanner(System.in);System.out.print("How many numbers do you need to draw? ");int k = in.nextInt();System.out.print("What is the highest number you can draw? ");int n = in.nextInt();/** compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)*/BigInteger lotteryOdds = BigInteger.valueOf(1);for (int i = 1; i <= k; i++)lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide(BigInteger.valueOf(i));System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");} }
10.数组
import java.util.*;/*** This program demonstrates array manipulation.* @version 1.20 2004-02-10* @author Cay Horstmann*/ public class LotteryDrawing {public static void main(String[] args){Scanner in = new Scanner(System.in);System.out.print("How many numbers do you need to draw? ");int k = in.nextInt();System.out.print("What is the highest number you can draw? ");int n = in.nextInt();// fill an array with numbers 1 2 3 . . . nint[] numbers = new int[n];for (int i = 0; i < numbers.length; i++)numbers[i] = i + 1;// draw k numbers and put them into a second arrayint[] result = new int[k];for (int i = 0; i < result.length; i++){// make a random index between 0 and n - 1int r = (int) (Math.random() * n);// pick the element at the random locationresult[i] = numbers[r];// move the last element into the random locationnumbers[r] = numbers[n - 1];n--;}// print the sorted array Arrays.sort(result);System.out.println("Bet the following combination. It'll make you rich!");for (int r : result)System.out.println(r);} }
注意:
Array.toSring()
Array.copyof()
Array.copyOfRange()
Array.sort()
Array.binarySearch()
Array.fill()
Array.equals()
11.类型
对象和对象变量
Data deadline; //声明一个变量,但是该变量没有引用任何对象 deadline = new Data(); //初始化变量
自定义类
import java.time.*;/*** This program tests the Employee class.* @version 1.12 2015-05-08* @author Cay Horstmann*/ public class EmployeeTest {public static void main(String[] args){// fill the staff array with three Employee objectsEmployee[] staff = new Employee[3];staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);// raise everyone's salary by 5%for (Employee e : staff)e.raiseSalary(5);// print out information about all Employee objectsfor (Employee e : staff)System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="+ e.getHireDay());} }class Employee {private String name;private double salary;private LocalDate hireDay;public Employee(String n, double s, int year, int month, int day){name = n;salary = s;hireDay = LocalDate.of(year, month, day);}public String getName(){return name;}public double getSalary(){return salary;}public LocalDate getHireDay(){return hireDay;}public void raiseSalary(double byPercent){double raise = salary * byPercent / 100;salary += raise;} }
数学函数
Math,StrictMath
枚举
enum{}
字符串String,null,不可修改,StringBuilder
char | charAt(int index) Returns the char value at the specified index. |
int | codePointAt(int index) Returns the character (Unicode code point) at the specified index. |
int | codePointBefore(int index) Returns the character (Unicode code point) before the specified index. |
int | codePointCount(int beginIndex, int endIndex) Returns the number of Unicode code points in the specified text range of this String . |
int | compareTo(String anotherString) Compares two strings lexicographically. |
int | compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences. |
String | concat(String str) Concatenates the specified string to the end of this string. |
boolean | contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values. |
boolean | contentEquals(CharSequence cs) Compares this string to the specified CharSequence . |
boolean | contentEquals(StringBuffer sb) Compares this string to the specified StringBuffer . |
static String | copyValueOf(char[] data) Equivalent to valueOf(char[]) . |
static String | copyValueOf(char[] data, int offset, int count) Equivalent to valueOf(char[], int, int) . |
boolean | endsWith(String suffix) Tests if this string ends with the specified suffix. |
boolean | equals(Object anObject) Compares this string to the specified object. |
boolean | equalsIgnoreCase(String anotherString) Compares this String to another String , ignoring case considerations. |
static String | format(Locale l, String format, Object... args) Returns a formatted string using the specified locale, format string, and arguments. |
static String | format(String format, Object... args) Returns a formatted string using the specified format string and arguments. |
byte[] | getBytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. |
byte[] | getBytes(Charset charset) Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array. |
void | getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) Deprecated. This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset. |
byte[] | getBytes(String charsetName) Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. |
void | getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array. |
int | hashCode() Returns a hash code for this string. |
int | indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. |
int | indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. |
int | indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. |
int | indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. |
String | intern() Returns a canonical representation for the string object. |
boolean | isEmpty() Returns true if, and only if, length() is 0 . |
static String | join(CharSequence delimiter, CharSequence... elements) Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter . |
static String | join(CharSequence delimiter, Iterable extends CharSequence> elements) Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter . |
int | lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. |
int | lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. |
int | lastIndexOf(String str) Returns the index within this string of the last occurrence of the specified substring. |
int | lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. |
int | length() Returns the length of this string. |
boolean | matches(String regex) Tells whether or not this string matches the given regular expression. |
int | offsetByCodePoints(int index, int codePointOffset) Returns the index within this String that is offset from the given index by codePointOffset code points. |
boolean | regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal. |
boolean | regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal. |
String | replace(char oldChar, char newChar) Returns a string resulting from replacing all occurrences of oldChar in this string with newChar . |
String | replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. |
String | replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement. |
String | replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. |
String[] | split(String regex) Splits this string around matches of the given regular expression. |
String[] | split(String regex, int limit) Splits this string around matches of the given regular expression. |
boolean | startsWith(String prefix) Tests if this string starts with the specified prefix. |
boolean | startsWith(String prefix, int toffset) Tests if the substring of this string beginning at the specified index starts with the specified prefix. |
CharSequence | subSequence(int beginIndex, int endIndex) Returns a character sequence that is a subsequence of this sequence. |
String | substring(int beginIndex) Returns a string that is a substring of this string. |
String | substring(int beginIndex, int endIndex) Returns a string that is a substring of this string. |
char[] | toCharArray() Converts this string to a new character array. |
String | toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale. |
String | toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale . |
String | toString() This object (which is already a string!) is itself returned. |
String | toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. |
String | toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale . |
String | trim() Returns a string whose value is this string, with any leading and trailing whitespace removed. |
static String | valueOf(boolean b) Returns the string representation of the boolean argument. |
static String | valueOf(char c) Returns the string representation of the char argument. |
static String | valueOf(char[] data) Returns the string representation of the char array argument. |
static String | valueOf(char[] data, int offset, int count) Returns the string representation of a specific subarray of the char array argument. |
static String | valueOf(double d) Returns the string representation of the double argument. |
static String | valueOf(float f) Returns the string representation of the float argument. |
static String | valueOf(int i) Returns the string representation of the int argument. |
static String | valueOf(long l) Returns the string representation of the long argument. |
static String | valueOf(Object obj) Returns the string representation of the Object argument. |