Java 语法清单翻译自 egek92 的 JavaCheatSheet,从属于笔者的 Java 入门与实践系列。时间仓促,笔者只是简单翻译了些标题与内容整理,支持原作者请前往原文点赞。需要注意的是,此文在 Reddit 上也引起了广泛的讨论,此文讲解的语法要点还是以 Java 7 为主,未涉及 Java 8 中内容,略显陈旧,读者可以带着批判的视角去看。
01
基础
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
类:
图片来自 Wikipedia
个人推荐 IntelliJ IDEA 并且对于 学生免费.
02
字符串操作
boolean result = str1.equals(str2);
boolean result = str1.equalsIgnoreCase(str2);
int result = str1.indexOf(str2);
int result = str1.indexOf(str2,5);
String index = str1.substring(14);
public class Main {
public static void main(String[] args) {
String str1 = "whatever string something";
StringBuffer str1buff = new StringBuffer(str1);
String str1rev = str1buff.reverse().toString();
System.out.println(str1rev);
}
}
public class Main {public static void main(String[] args) {
String str1 = "reverse this string";
Stack stack = new Stack<>();
StringTokenizer strTok = new StringTokenizer(str1);
while(strTok.hasMoreTokens()){
stack.push(strTok.nextElement());
}
StringBuffer str1rev = new StringBuffer();
while(!stack.empty()){
str1rev.append(stack.pop());
str1rev.append(" ");
}
System.out.println(str1rev);
}
String strUpper = str1.toUpperCase();
String strLower = str1.toLowerCase();
String str1 = " asdfsdf ";
str1.trim(); //asdfsdf
str1.replace(" ","");
String str = "tim,kerry,timmy,camden";
String[] results = str.split(",");
03
数据结构
int[] myArray = new int[10];
int[] tmp = new int[myArray.length + 10];
System.arraycopy(myArray, 0, tmp, 0, myArray.length);
myArray = tmp;
for (Iterator it = map.entrySet().iterator();it.hasNext();){
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();}
HashMap map = new HashMap();
map.put(key1,obj1);
map.put(key2,obj2);
map.put(key2,obj2);
int[] nums = {1,4,7,324,0,-4};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
ListunsortList = new ArrayList();
unsortList.add("CCC");
unsortList.add("111");
unsortList.add("AAA");
Collections.sort(unsortList);
int index = arrayList.indexOf(obj);
hashmap.containsValue(obj);
hashmap.containsKey(obj);
int[] nums = new int[]{7,5,1,3,6,8,9,2};
Arrays.sort(nums);int index = Arrays.binarySearch(nums,6);
System.out.println("6 is at index: "+ index);
Object[] objects = arrayList.toArray();
Object[] objects = hashmap.entrySet().toArray();
04
时间与日期类型
Date todaysDate = new Date(); //todays date
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); //date format
String formattedDate = formatter.format(todaysDate);
System.out.println(formattedDate);
Date mDate = new Date();
Calendar mCal = Calendar.getInstance();
mCal.setTime(mDate);
Calendar mCal = Calendar.getInstance();
Date mDate = mDate.getTime();
public void StringtoDate(String x) throws ParseException{
String date = "March 20, 1992 or 3:30:32pm";
DateFormat df = DateFormat.getDateInstance();
Date newDate = df.parse(date);
}
Date date = new Date();
long time = date.getTime();
time += 5*24*60*60*1000; //may give a numeric overflow error on IntelliJ IDEA
Date futureDate = new Date(time);
System.out.println(futureDate);
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE,5);
long diff = time1 - time2; diff = diff/(1000*60*60*24);
boolean result = date1.equals(date2);
Calendar cal = Calendar.getInstance();
cal.get(Calendar.MONTH);
cal.get(Calendar.YEAR);
cal.get(Calendar.DAY_OF_YEAR);
cal.get(Calendar.WEEK_OF_YEAR);
cal.get(Calendar.DAY_OF_MONTH);
cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
cal.get(Calendar.DAY_OF_MONTH);
cal.get(Calendar.HOUR_OF_DAY);
long startTime = System.currentTimeMillis();//times flies by..
long finishTime = System.currentTimeMillis();
long timeElapsed = startTime-finishTime;
System.out.println(timeElapsed);
05
正则表达式
String pattern = "[TJ]im";
Pattern regPat = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
String text = "This is Jim and that's Tim";
Matcher matcher = regPat.matcher(text);
if (matcher.find()){
String matchedText = matcher.group();
System.out.println(matchedText);
}
String pattern = "[TJ]im";
Pattern regPat = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
String text = "This is jim and that's Tim";
Matcher matcher = regPat.matcher(text);
String text2 = matcher.replaceAll("Tom");
System.out.println(text2);
Pattern p = Pattern.compile("My");
Matcher m = p.matcher("My dad and My mom");
StringBuffer sb = new StringBuffer();
boolean found = m.find();
while(found){
m.appendReplacement(sb,"Our");
found = m.find();
}
m.appendTail(sb);
System.out.println(sb);
String pattern = "\\sa(\\w)*t(\\w)*"; //contains "at"Pattern regPat = Pattern.compile(pattern);
String text = "words something at atte afdgdatdsf hey";
Matcher matcher = regPat.matcher(text);
while(matcher.find()){
String matched = matcher.group();
System.out.println(matched);
}
String pattern = "^a";
Pattern regPat = Pattern.compile(pattern);
Matcher matcher = regPat.matcher("");
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine())!= null){
matcher.reset(line);
if (matcher.find()){
System.out.println(line);
}
}
String pattern = "\\d$"; //any single digitString text = "line one\n line two\n line three\n";
Pattern regPat = Pattern.compile(pattern, Pattern.MULTILINE);
Matcher matcher = regPat.matcher(text);
while (matcher.find()){
System.out.println(matcher.group());
}
06
数字与数学操作处理
String str = "dsfdfsd54353%%%";
try{
int result = Integer.parseInt(str);
}catch (NumberFormatException e){
System.out.println("not valid");
}
Double a = 4.5;
Double b= 4.5;
boolean result = a.equals(b);
if (result) System.out.println("equal");
double doubleVal = 43.234234200000000234040324;
float floatVal = 2.98f;
long longResult = Math.round(doubleVal);
int intResult = Math.round(floatVal);
System.out.println(longResult + " and " + intResult); // 43 and 3
double value = 2343.8798;
NumberFormat numberFormatter;
String formattedValue;
numberFormatter = NumberFormat.getNumberInstance();
formattedValue = numberFormatter.format(value);
System.out.format("%s%n",formattedValue); //2.343,88
double currency = 234546457.99;
NumberFormat currencyFormatter;
String formattedCurrency;
currencyFormatter = NumberFormat.getCurrencyInstance();
formattedCurrency = currencyFormatter.format(currency);
System.out.format("%s%n",formattedCurrency); // $ 234.546.457,99
int val = 25;
String binaryStr = Integer.toBinaryString(val);
String octalStr = Integer.toOctalString(val);
String hexStr = Integer.toHexString(val);
double rn = Math.random();
int rint = (int) (Math.random()*10); // random int between 0-10
System.out.println(rn);
System.out.println(rint);
double cos = Math.cos(45);
double sin = Math.sin(45);
double tan = Math.tan(45);
double logVal = Math.log(125.5);
07
输入输出操作:
//throw IOexception first
BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
String inline ="";
while (!(inline.equalsIgnoreCase("quit"))){
System.out.println("prompt> ");
inline=inStream.readLine();
}
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);
formatter.format("PI: "+Math.PI);
System.out.println(buffer.toString());
BufferedReader br = new BufferedReader(new FileReader(textFile.txt)); //for reading
BufferedWriter bw = new BufferedWriter(new FileWriter(textFile.txt)); //for writing
InputStream is = new FileInputStream(fileName);
int offset = 0;
int bytesRead = is.read(bytes, ofset, bytes.length-offset);
File file = new File(something.bin);
RandomAccessFile raf = new RandomAccessFile(file,"rw");
raf.seek(file.length());
ZipFile file =new ZipFile(filename);
Enumeration entries = file.entries();
while(entries.hasMoreElements()){
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()){
//do something
} else{
//do something
}
}
file.close();
08
文件与目录
File f = new File("textFile.txt");
boolean result = f.createNewFile();
File f = new File("textFile.txt");
File newf = new File("newTextFile.txt");
boolean result = f.renameto(newf);
File f = new File("somefile.txt");
f.delete();
File f = new File("somefile.txt");
f.setReadOnly(); // making the file read only
f.setLastModified(desired time);
File f = new File("somefile.txt");
long length = file.length();
File f = new File("somefile.txt");
boolean status = f.exists();
File f = new File("somefile.txt");
File dir = new File("directoryName");
boolean success = f.renameTo(new File(dir, file.getName()));
File f = new File("somefile.txt");
File absPath = f.getAbsoluteFile();
File f = new File("somefile.txt");
boolean isDirectory = f.isDirectory();
System.out.println(isDirectory); //false
File directory = new File("users/ege");
String[] result = directory.list();
boolean result = new File("users/ege").mkdir();
09
网络客户端
String serverName = "www.egek.us";
Socket socket = new Socket(serverName, 80);
System.out.println(socket);
try {
Socket sock = new Socket(server_name, tcp_port);
System.out.println("Connected to " + server_name);
sock.close( );
} catch (UnknownHostException e) {
System.err.println(server_name + " Unknown host");
return;
} catch (NoRouteToHostException e) {
System.err.println(server_name + " Unreachable" );
return;
} catch (ConnectException e) {
System.err.println(server_name + " connect refused");
return;
} catch (java.io.IOException e) {
System.err.println(server_name + ' ' + e.getMessage( ));
return;
}
10
包与文档
package com.ege.example;
javadoc -d \home\html
-sourcepath \home\src
-subpackages java.net
jar cf project.jar *.class
java -jar something.jar