Java CheatSheet

01.基础

hello,world!

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

 

if-else

if (income < 0) rate = 0.00;
else if (income < 8925) rate = 0.10;
else if (income < 36250) rate = 0.15;
else if (income < 87850) rate = 0.23;
else if (income < 183250) rate = 0.28;
else if (income < 398350) rate = 0.33;
else if (income < 400000) rate = 0.35;
else rate = 0.396;

loops:

/**
* compute the largest
* power of 2
* less than or equal to n
*/
public static void test2(int n){
int power = 1;
while (power < n/2)
power = 2 * power;
System.out.println(power);
}
/**
* compute a finite sum
* (1+2+...+n)
*/
public static void test3(int n){
int sum = 0;
for(int i=0; i <= n; i++)
sum += i;
System.out.println(sum);
}
/**
* compute a finite product
* (n! = 1*2*...*n)
*/
public static void test4(int n){
int product = 1;
for(int i=1; i <= n; i++)
product *= i;
System.out.println(product);
}
/**
* compute the ruler function
*/
public static void test6(int n){
StringBuilder ruler = new StringBuilder("1");
for(int i=2; i <= n; i++)
ruler.append(" ").append(i).append(" ").append(ruler);
System.out.println(ruler);
}

do-while:

//do-while
public static void test7(){
int count = 0;
do {
System.out.println("count is:"+ count);
count++;
}while (count<11);
}

 switch-case:

//switch-case
public static void test8(int day){
switch(day){
case 0: System.out.println("Sun");break;
case 1: System.out.println("Mon");break;
case 2: System.out.println("Tue");break;
case 3: System.out.println("Wed");break;
case 4: System.out.println("Thu");break;
case 5: System.out.println("Fri");break;
case 6: System.out.println("Sat");break;
}
}

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 static void test11(){
String str1 = "whatever string something";
StringBuffer buffer = new StringBuffer(str1);
String reverse = buffer.reverse().toString();
System.out.println(reverse);
}

 

按单词的字符串反转:

//按单词的字符串反转
public static void test12(){
String str1 = "reverse this string";
Stack<Object> stack = new Stack<>();
StringTokenizer tokenizer = new StringTokenizer(str1);
while (tokenizer.hasMoreElements())
stack.push(tokenizer.nextElement());
StringBuffer buffer = new StringBuffer();
while (!stack.isEmpty()){
buffer.append(stack.pop());
buffer.append(" ");
}
System.out.println(buffer);
}

大小写转化:

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;

集合遍历:

Map<String,Object> map = new HashMap<>();
map.put("1","zhangsan");
map.put("2","lisi");
map.put("3","wangwu");
for (Map.Entry<String, Object> next : map.entrySet()) {
System.out.println(next.getKey() + ":" + next.getValue());
}

 

数组排序:

int[] nums = {1,4,7,324,0,-4};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));

列表排序:

List<String> unsortList = new ArrayList<>();

unsortList.add("CCC");
unsortList.add("111");
unsortList.add("AAA");
Collections.sort(unsortList);

列表搜索:

int index = arrayList.indexOf(obj);

finding an object by value in a hashmap:

hashmap.containsValue(obj);

finding an object by key in a hashmap:

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);

arrayList 转化为 array:

Object[] objects = arrayList.toArray();

将 hashmap 转化为 array:

Object[] objects = hashmap.entrySet().toArray();

04.时间与日期类型(开发推荐使用org.apache.commons.lang3.time.DateUtils 或者 Java8新的日期工具类,切勿重复造轮子!)

打印时间与日期:

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 转化为 date:

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 arithmetic using date objects:

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);

date arithmetic using calendar objects:

Calendar today = Calendar.getInstance();
today.add(Calendar.DATE,5);

difference between two dates:

long diff = time1 - time2; diff = diff/(1000*60*60*24);

comparing dates:

boolean result = date1.equals(date2);

getting details from calendar:

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);

calculating the elapsed time:

long startTime = System.currentTimeMillis();//times flies by..

long finishTime = System.currentTimeMillis();
long timeElapsed = startTime-finishTime;
System.out.println(timeElapsed);

05.正则表达式

使用 REGEX 寻找匹配字符串:

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);

使用 StringBuffer 替换匹配字符串:

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());
}

regex:

beginning of a string: ^
end of a string: $
0 or 1 times: ?
0 or more times: (*) //without brackets
1 or more times: +
alternative characters: [...]
alternative patterns: |
any character: .
a digit: d
a non-digit: D
whitespace: s
non-whitespace: S
word character: w
non word character: W

06.数字与数学操作处理

内建数据类型:

byte: 8bits, Byte
short: 16bits, Short
long: 64bits, Long
float: 32bits, Float

判断字符串是否为有效数字:

String str = "dsfdfsd54353%%%";
try{
int result = Integer.parseInt(str);
}catch (NumberFormatException e){
System.out.println("not valid");
}

比较 Double:

Double a = 4.5;
Double b= 4.5;
boolean result = a.equals(b);
if (result) System.out.println("equal");

rounding:

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());

读取 Jar/zip/rar 文件:

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 注释某个类:

javadoc -d \home\html
-sourcepath \home\src
-subpackages java.net

Jar 打包:

jar cf project.jar *.class

运行 Jar:

java -jar something.jar

排序算法

各种排序算法总结和比较

Java语法清单-快速回顾(开发)的更多相关文章

  1. Java 语法清单

      Java 语法清单 Java 语法清单翻译自 egek92 的 JavaCheatSheet,从属于笔者的 Java 入门与实践系列.时间仓促,笔者只是简单翻译了些标题与内容整理,支持原作者请前往 ...

  2. 程序员带你学习安卓开发,十天快速入-对比C#学习java语法

    关注今日头条-做全栈攻城狮,学代码也要读书,爱全栈,更爱生活.提供程序员技术及生活指导干货. 如果你真想学习,请评论学过的每篇文章,记录学习的痕迹. 请把所有教程文章中所提及的代码,最少敲写三遍,达到 ...

  3. 006 01 Android 零基础入门 01 Java基础语法 01 Java初识 06 使用Eclipse开发Java程序

    006 01 Android 零基础入门 01 Java基础语法 01 Java初识 06 使用Eclipse开发Java程序 Eclipse下创建程序 创建程序分为以下几个步骤: 1.首先是创建一个 ...

  4. Meteor+AngularJS:超快速Web开发

        为了更好地描述Meteor和AngularJS为什么值得一谈,我先从个人角度来回顾一下这三年来WEB开发的变化:     三年前,我已经开始尝试前后端分离,后端使用php的轻量业务逻辑框架.但 ...

  5. 为 Python Server Pages 和 Oracle 构建快速 Web 开发环境。

    为 Python Server Pages 和 Oracle 构建快速 Web 开发环境. - 在水一方 - 博客频道 - CSDN.NET 为 Python Server Pages 和 Oracl ...

  6. Java语法知识总结

    一:java概述: 1991 年Sun公司的James Gosling等人开始开发名称为 Oak 的语言,希望用于控制嵌入在有线电视交换盒.PDA等的微处理器: 1994年将Oak语言更名为Java: ...

  7. Java or Python?测试开发工程师如何选择合适的编程语言?

    很多测试开发工程师尤其是刚入行的同学对编程语言和技术栈选择问题特别关注,毕竟掌握一门编程语言要花不少时间成本,也直接关系到未来的面试和就业(不同企业/项目对技术栈要求也不一样),根据自身情况做一个相对 ...

  8. 零基础的Java小白如何准备初级开发的面试

    对于各位Java程序员来说,只要能有实践的机会,哪怕工资再低,公司情况再一般,只要自己上心努力,就可能在短时间内快速提升,甚至在工作2年后进大厂都有希望,因为项目里真实的开发实践环境是平时学习不能模拟 ...

  9. Java语法糖1:可变长度参数以及foreach循环原理

    语法糖 接下来几篇文章要开启一个Java语法糖系列,所以首先讲讲什么是语法糖.语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的 ...

随机推荐

  1. Linux系统关闭对ping命令做响应。

    1.测试 ping 192.168.10.5 可以正常ping通, 2,修改 /proc/sys/net/ipv4/icmp_echo_ignore_all  文件的值=1 3.在测试 已经ping不 ...

  2. Linux编译C语言程序

    1.首先安装gcc包,运行C++程序,安装gcc-c++ 包 如果没有安装的自行进行安装 2.编辑C语言程序, 打印乘法口诀表 [root@Db1 c]# vim chengfa.c 在编辑界面中,输 ...

  3. String的static方法

    //String concat(String str) 拼接字符串 String concat_str0 = "abc"; String concat_str1 = "b ...

  4. 【JZOJ3920】噪音

    description FJ有M个牛棚,编号1至M,刚开始所有牛棚都是空的.FJ有N头牛,编号1至N,这N头牛按照编号从小到大依次排队走进牛棚,每一天只有一头奶牛走进牛棚.第i头奶牛选择走进第p[i] ...

  5. IDEA工具,配置相关笔记

    1.修改背景颜色(黑/白)File -> settings -> Editor -> Color Scheme -> General -> (Scheme选择Defaul ...

  6. 【JNDI】Java Naming and Directory Interface

    一.数据源的由来 在Java开发中,使用JDBC操作数据库的四个步骤如下:   ①加载数据库驱动程序(Class.forName("数据库驱动类");)   ②连接数据库(Conn ...

  7. Devstack 配置文件说明手册

    本文为minxihou的翻译文章,转载请注明出处Bob Hou: http://blog.csdn.net/minxihou JmilkFan:minxihou的技术博文方向是 算法&Open ...

  8. Airbnb React/JSX 编码规范

    Airbnb React/JSX 编码规范 算是最合理的React/JSX编码规范之一了 内容目录 基本规范 Class vs React.createClass vs stateless 命名 声明 ...

  9. next()nextLine()以及nextInt()的区别及用法【转载】

    next().nextLine().nextInt()作为scanner内置的方法,常常让人傻傻分不清楚,今天在这里记下他们的区别以及以此区别为出发点的用法:他们的区别在于对于空格的处理方式不同,以及 ...

  10. 优雅地使用 VSCode 来编辑 vue 文件

    javascript visual-studio-code vue.js 当然 vscode 对 vue 也不是原生支持的,今天来扒一扒如何配置 vscode 以便优雅地编辑 vue 文件 先来扒一扒 ...