【JAVA】基本语法

1. 跳出for循环的方式

⑴使用label标签

package dxc1;
public class Test123 {
	 public static void main(String[] args) {
		heidou:
		for(int i=0;i<5;i++){
			for(int j=0;j<5;j++){
				  System.out.println("i是"+i+"j是"+j);
				  if(i==2&&j==3){
					  break heidou;
				  }
			}
	  		}}
}
⑵在外面加个条件
 int arr[][] = { { 1, 2, 3 }, { 4, 5, 6, 7 }, { 9 } };
        boolean found = false;
 
        for (int i = 0; i < arr.length && !found; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.println("i=" + i + ",j=" + j);
                if (arr[i][j] == 5) {
                    found = true;
                    break;
                }
            }
        }

2.switch

支持int,char,byte,short,枚举,String(JDK1.7以上)类型,从满足的case往后直到break或者执行完。

public static void main(String[] args) { 
		int i=3; 
		switch(i) 
		{ 
		  
		   case 1: 
		       System.out.println(1); 
		       break; 
		   case 2: 
		       System.out.println(2); 
		       break; 
		   case 3: 
		       System.out.println(3); 
		       break;  //屏蔽点
		   default: 
		       System.out.println("default"); 
	    	} 
}

输出:

3

3.try catch finally

  • finally{}代码块比return的最后一个操作(即return操作)前执行。
  • 多个return是按顺序执行的的,多个return执行了一个后,后面的return就不会执行了。
  • 记住一点,不管有不有异常抛出, finally都会在return返回前执行
  • 值类型变量finally不会修改return的返回值,对于引用类型会存着引用地址的拷贝,该结果会被第二个return(finally里面的)覆盖。
    例子1(值类型):
public class testswitch {
    public static void main(String[] args) {
        System.out.println(heidou(5));
    }
    private static int heidou(int i) {
        int a =5;
        try {
            return a;
        }
        finally{
            a++;
            System.out.println("finally"+a);
        }
    }
}

输出:

finally6
5

例子2(引用类型):

public class testswitch {
    public static void main(String[] args) {
        System.out.println(""+m1());
    }

    private static StringBuilder m1() {
        StringBuilder builder = new StringBuilder();
        try {
            builder.toString();
            throw new RuntimeException();
        } catch (Exception e) {
            return builder;
        } finally {
            builder.append("1");
        }
    }
}

输出:

1

例子3:

public class testswitch {
    public static void main(String[] args) {
        System.out.println(heidou(5));
    }
    private static int heidou(int i) {
        int a =5;
        try {
            return ++a;
        }
        finally{
            System.out.println("finally"+a);
            return a;
        }
    }

}

输出:

finally6
6

4.&和&& |和||

按位与:a&b是把a和b都转换成二进制数然后再进行与的运算;(都会运行)
逻辑与:a&&b就是当且仅当两个操作数均为 true时,其结果才为 true;只要有一个为false后面就不执行了
同理 | 和||也是一个意思

5.floor cell round

floor: 求小于参数的最大整数。返回double类型
例如:Math.floor(-4.2) = -5.0
ceil: 求大于参数的最小整数。返回double类型
例如:Math.ceil(5.6) = 6.0
round: 对小数进行四舍五入后的结果。返回int类型
例如:Math.round(-4.6) = -5

6.数字与字符串相加

System.out.println(1+"10"+3+"2");//11032
System.out.println(1+2+"10"+3+"2");//31032
System.out.println(1+"10"+3+1+"2");//110312 

7.instanceof运算符

  • 对象实现一个接口,用这个对象和这个接口进行instanceof判断,都为true。
  • 对象和父类进行instanceof判断,都为true
  • 对象和他的子类进行instanceof判断为false

/**
 * @author bincai, [email protected]
 * @date Sep 30 , 2018
 */
public class Test {
 
  public static void main(String[] args) {
    Man man = new Man();
    System.out.println(man instanceof Father);  // true
 
    Son son = new Son();
    System.out.println(son instanceof Father);  // true
 
    Man son1 = new Son();
    System.out.println(son1 instanceof Father); // true
 
    Man son2 = new Son();
    System.out.println(son1 instanceof Son);    // true
 
    Father man2 = new Man();
    System.out.println(man2 instanceof Son);    // false
 
    Father father = new Father();
    System.out.println(father instanceof Son);  // false
 
    Father father1 = new Father();  
    System.out.println(null instanceof Father); // false
    System.out.println(father1 instanceof Object); // true
   }
 
}
 
class Father {
}
class Man extends Father {
}
class Son extends Man {
}

8.位运算符

  • 与运算符:&
    两个操作数中位都为1,结果才为1,否则结果为0
  • 或运算符:|
    两个位只要有一个为1,那么结果就是1,否则就为0
  • 非运算符:~
    如果位为0,结果是1,如果位为1,结果是0
  • 异或:^
    两个操作数的位中,相同则结果为0,不同则结果为1

9.移位运算符

左移位<< :将操作符左侧的操作数向左移动操作数右侧指定的位数。移动的规则是在二进制的低位补0.
有符号右移位>>:将操作符左侧的操作数向右移动操作数右侧指定的位数。移动的规则是,如果被操作数的符号为正,则在二进制的高位补0;如果被操作数的符号为负,则在二进制的高位补1,>>右移几位相当于除以二的几次方
无符号右移位>>> :将操作符左侧的操作数向右移动操作数右侧指定的位数。移动的对则是,无论被操作数的符号是正是负,都在二进制的高位补0.

10.StringUtils常用方法

⑴isEmpty(String str)

判断某字符串是否为空,为空的标准是 str==null 或 str.length()==0

StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true 
StringUtils.isEmpty(" ") = false //注意在 StringUtils 中空格作非空处理
StringUtils.isEmpty("   ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
⑵isNotEmpty(String str)

判断某字符串是否非空,等于 !isEmpty(String str)

StringUtils.isNotEmpty(null) = false
StringUtils.isNotEmpty("") = false
StringUtils.isNotEmpty(" ") = true
StringUtils.isNotEmpty("         ") = true
StringUtils.isNotEmpty("bob") = true
StringUtils.isNotEmpty(" bob ") = true 
⑶isBlank(String str)

判断某字符串是否为空或长度为0或由空白符(whitespace) 构成

StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("        ") = true
StringUtils.isBlank("\t \n \f \r") = true   //对于制表符、换行符、换页符和回车符
 
StringUtils.isBlank()   //均识为空白符
StringUtils.isBlank("\b") = false   //"\b"为单词边界符
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
⑷isNotBlank(String str)

判断某字符串是否不为空且长度不为0且不由空白符(whitespace) 构成,等于 !isBlank(String str)

 StringUtils.isNotBlank(null) = false
 StringUtils.isNotBlank("") = false
 StringUtils.isNotBlank(" ") = false
 StringUtils.isNotBlank("         ") = false
 StringUtils.isNotBlank("\t \n \f \r") = false
 StringUtils.isNotBlank("\b") = true
 StringUtils.isNotBlank("bob") = true
 StringUtils.isNotBlank(" bob ") = true 

11.System.gc和System.runFinalization区别

⑴System.gc();
//告诉垃圾收集器打算进行垃圾收集,而垃圾收集器进不进行收集是不确定的

⑵System.runFinalization();
//强制调用已经失去引用的对象的finalize方法

12.判断数组是否含有某个元素


/***
 * @author bincai
 * @email [email protected]
 */
public class Test {
    public static void main(String[] args) {
        String[] values = {"AB","BC","CD","AE"};
        boolean contains = Arrays.stream(values).anyMatch("s"::equals);
        System.out.println(contains);  // flase
        int[] a = {1,2,3,4};
        boolean contains2 = IntStream.of(a).anyMatch(x -> x == 4);
        System.out.println(contains2);  // true
      }
}

13.Void类

通过Void源码可知,Void不可以继承和实例化
Void类是一个不可实例化的占位符类,如果方法返回值是Void类型,那么该方法只能返回null类型。
什么时候使用Void类?

  • 在反射中,我们需要判断一个方法的返回类型的时候可以采用
for(Method method : Testvoid.class.getMethods()) {
      if(method.getReturnType().equals(Void.TYPE)) {
        System.out.println(method.getName());
      }
    }
  • 比如使用 Callable接口,该接口必须返回一个值,但实际执行后没有需要返回的数据。 这时可以使用Void类型作为返回类型
Future<Void> f = pool.submit(new Callable() {
    @Override
    public Void call() throws Exception {
        ......
        return null;
    }
});

14.string stringbuffer stringbuilder

单线程运行效率: String<< StringBuffer< StringBuilder,执行速度StringBuilder最快
StringBuffer线程安全,可变
String是final的,所以也是线程安全的。
StringBuilder线程不安全,可变

15.对List集合内的元素进行顺序、倒序、随机排序的示例代码

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
 
public class Test {
 
     List list  =   new  LinkedList();
     public   static   void  main(String[] args)  {
        List list  =   new  LinkedList();
         for  ( int  i  =   0 ; i  <   9 ; i ++ )  {
            list.add( " a " + i);
        } 
        Collections.sort(list); // 顺序排列 
        System.out.println(list);
        
        Collections.shuffle(list); // 混乱的意思 
        System.out.println(list);
        
        Collections.reverse(list); // 倒序排列 
        System.out.println(list);
        
        System.out.println(Collections.binarySearch(list,  " a5 " )); // 折半查找 
    } 
    
}

16.双端队列

 System.out.println("--------双端队列开始--------");
	    System.out.println("-----双端ArrayDeque-----");
		Deque<Integer> test2=new ArrayDeque<Integer>();
		test2.add(1);
		test2.add(2);
		test2.add(3);
		test2.push(4);
		test2.offer(5);
		System.out.println(test2);
		System.out.println("poll是  "+test2.poll());
		System.out.println("pollFirst是  "+test2.pollFirst());
		System.out.println("pollLast是  "+test2.pollLast());
		System.out.println("-----双端LinkedList-----");
 		Deque<Integer> test3 = new LinkedList<Integer>();
 		test3.offer(1);
 		test3.offer(2);
 		test3.offer(3);
 		test3.add(4);
 		test3.push(5);
 		System.out.println(test3);
	    System.out.println(test3.poll());
	    System.out.println(test3.pollLast());
	    System.out.println("--------双端队列结束--------");

输出:

--------双端队列开始--------
-----双端ArrayDeque-----
[4, 1, 2, 3, 5]
poll是  4
pollFirst是  1
pollLast是  5
-----双端LinkedList-----
[5, 1, 2, 3, 4]
5
4
--------双端队列结束--------

17.继承小例子

package jicheng;
 
/*** 
 * @author bincai
 * @email [email protected]
 */
public class jicheng {
    public static void main(String[] args) {
        Father test = new Child();
        test.play();
        //打游戏
        System.out.println("我的年龄是"+test.age);
        //我的年龄是70
        System.out.println("通过get取到的年龄是"+test.getAge());
        //通过get取到的年龄是30
        System.out.println("我的爱好是"+((Child) test).hobby);
        //我的爱好是football
        Child canshu = new Child();
        canshu.setComputer("mac");
        test(canshu);
    }
 
    public static void test(Father father){
        System.out.println("方法传递"+father.age);
        //方法传递70
        father.play();
        //打游戏
        Child child = (Child)father;
        System.out.println("方法传递并强转"+child.hobby);
        //方法传递并强转football
        System.out.println("方法传递并强转,属性找回来了"+child.computer);
        //方法传递并强转,属性找回来了mac
    }
}
 
class Father{
    int age = 70;
    public void play(){
        System.out.println("打麻将");
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}
 
class Child extends Father{
    int age = 30;
    String hobby = "football";
    String computer;
 
    public void play(){
        System.out.println("打游戏");
    }
 
    public String getComputer() {
        return computer;
    }
 
    public void setComputer(String computer) {
        this.computer = computer;
    }
 
    @Override
    public int getAge() {
        return age;
    }
 
    @Override
    public void setAge(int age) {
        this.age = age;
    }
 
}

18.实现多重继承

我们通过内部类来实现多重继承

public class Father {  
    public int strong(){  
        return 9;  
    }  
}  
  
public class Mother {  
    public int kind(){  
        return 8;  
    }  
} 

public class Son {  
      
    /** 
     * 内部类继承Father类 
     */  
    class Father_1 extends Father{  
        public int strong(){  
            return super.strong() + 1;  
        }  
    }  
      
    class Mother_1 extends  Mother{  
        public int kind(){  
            return super.kind() - 2;  
        }  
    }  
      
    public int getStrong(){  
        return new Father_1().strong();  
    }  
      
    public int getKind(){  
        return new Mother_1().kind();  
    }  
}  

测试:


public class Test1 {  
  
    public static void main(String[] args) {  
        Son son = new Son();  
        System.out.println("Son 的Strong:" + son.getStrong());  
        System.out.println("Son 的kind:" + son.getKind());  
    }  
  
}  
----------------------------------------  
Output:  
Son 的Strong:10  
Son 的kind:6 

19.回调

假设我们这里老师和学生,老师需要等学生回答完问题,那么就可以这样子:
老师:

public class Teacher implements Callback {

    private Student student;

    public Teacher(Student student) {
        this.student = student;
    }

    public void ask(){
        student.answer(this);
    }

    @Override
    public void callBack(int answer) {
        System.out.println("over" + answer);
    }
}

学生实现接口:

public interface Student {

    void answer(Callback callback);
    
}

学生:

public class Bincai implements Student{

    @Override
    public void answer(Callback callback) {
        callback.callBack(3);
    }
}

测试类:

public class Test {
    public static void main(String[] args) {
      Student student = new Bincai();
      Teacher teacher = new Teacher(student);

      teacher.ask();
    }
}

20.asList和subList,toArray注意事项

⑴asList
  • 基本类型的数组调用asList是不可以的
        System.out.println("------int基本类型------");
        int[] ints = {1,2,3,4,5};  
        List list = Arrays.asList(ints);  
        System.out.println("list'size:" + list.size());  
        for(int i=0;i<list.size();i++)
        System.out.println(list.get(i));   
        System.out.println("------Integer包装类------");
        Integer[] ints2 = {1,2,3,4,5};
        List list2 = Arrays.asList(ints2);     
        System.out.println("Integerlist'size:" + list2.size());   
        for(int i=0;i<list2.size();i++)
        System.out.println(list2.get(i));

输出:


------int基本类型------
list'size:1
[I@37f2ae62
------Integer包装类------
Integerlist'size:5
1
2
3
4
5
  • asList产生的列表不可以操作,如果我们想操作,可以再放到new ArrayList里面
  • asList()的返回值List<?>会指定一个认为最合适元素类型
class Snow {}
class Powder extends Snow {}
class Light extends Powder {}
class Heavy extends Powder {}
class Crusty extends Snow {}
class Slush extends Snow {}
 
 
public class TestArry {
 public static void main(String[] args) {
	 List<Snow> snow1 = Arrays.asList(new Crusty(), new Slush(), new Powder());
     
     // Won’t compile:
      List<Snow> snow2 = Arrays.asList(new Light(), new Heavy());  //报错
     // Compiler says:
     // found : java.util.List<Powder>
     // required: java.util.List<Snow>
     
     // Collections.addAll() doesn’t get confused:
     List<Snow> snow3 = new ArrayList<Snow>();
     Collections.addAll(snow3, new Light(), new Heavy());
     
     // Give a hint using an explicit type argument specification:
     List<Snow> snow4 = Arrays.<Snow>asList(new Light(), new Heavy());
   
}
}
⑵subList

“非结构性修改”,是指不涉及到list的元素数量(这个数量指的是如果listb本来2个元素,又加了或者减了)改变的修改。结构性修改相反。
结构性修改:

package test;
 
import java.util.ArrayList;
import java.util.List;
 
public class test1 {
 
  public static void main(String args[]) {
	List<String> test=new ArrayList<String>();
	test.add("a");
	test.add("b");
	List<String> test2=test.subList(0,1);
	System.out.println("子list"+test2.toString());
	test2.add("c");
	System.out.println("原来的list"+test.toString());
	System.out.println("子list"+test2.toString());	
	test.remove("a");
	System.out.println("原来的list"+test.toString());
	System.out.println(test2.toString());	  // 这里会抛异常
  }
}

输出:


子list[a]
原来的list[a, c, b]
子list[a, c]
原来的list[c, b]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1239)
	at java.util.ArrayList$SubList.listIterator(ArrayList.java:1099)
	at java.util.AbstractList.listIterator(AbstractList.java:299)
	at java.util.ArrayList$SubList.iterator(ArrayList.java:1095)
	at java.util.AbstractCollection.toString(AbstractCollection.java:454)
	at test.test1.main(test1.java:19)

非结构性修改:

package test;
 
import java.util.ArrayList;
import java.util.List;
 
public class test1 {
 
  public static void main(String args[]) {
	List<String> test=new ArrayList<String>();
	test.add("a");
	test.add("b");
	List<String> test2=test.subList(0,1);
	System.out.println("子list"+test2.toString());
	test2.set(0,"c");
	System.out.println("原来的list"+test.toString());
	System.out.println("子list"+test2.toString());	
	test.set(0,"a");
	System.out.println("原来的list"+test.toString());
	System.out.println("子list"+test2.toString());	
	
  }
}

输出:

子list[a]
原来的list[c, b]
子list[c]
原来的list[a, b]
子list[a]
⑶toArray
 public static void main(String args[]) {
	  List<caiwanzi> test=new ArrayList<caiwanzi>();
	  test.add(new caiwanzi("cai"));
	  test.add(new caiwanzi("wan"));
	  test.add(new caiwanzi("zi"));
	  caiwanzi[] resulttest=test.toArray(new caiwanzi[0]);
	  System.out.println(resulttest[0].getName());
	  System.out.println(resulttest[1].getName());
	  System.out.println(resulttest[2].getName());  
  }

21.Map遍历方式

public class testswitch {
    public static void main(String[] args) {
            Map<Integer, String> map = new HashMap<Integer, String>();
            map.put(1, "a");
            map.put(2, "b");
            map.put(3, "ab");
            map.put(4, "ab");
            map.put(4, "ab");// 和上面相同 , 会自己筛选
            System.out.println(map.size());
            // 第一种:
            /*
             * Set<Integer> set = map.keySet(); //得到所有key的集合
             *
             * for (Integer in : set) { String str = map.get(in);
             * System.out.println(in + "     " + str); }
             */
            System.out.println("第一种:通过Map.keySet遍历key和value:");
            for (Integer in : map.keySet()) {
                //map.keySet()返回的是所有key的值
                String str = map.get(in);//得到每个key多对用value的值
                System.out.println(in + "     " + str);
            }
            // 第二种:
            System.out.println("第二种:通过Map.entrySet使用iterator遍历key和value:");
            Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Integer, String> entry = it.next();
                System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            }
            // 第三种:推荐,尤其是容量大时
            System.out.println("第三种:通过Map.entrySet遍历key和value");
            for (Map.Entry<Integer, String> entry : map.entrySet()) {
                //Map.entry<Integer,String> 映射项(键-值对)  有几个方法:用上面的名字entry
                //entry.getKey() ;entry.getValue(); entry.setValue();
                //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
                System.out.println("key= " + entry.getKey() + " and value= "
                        + entry.getValue());
            }
            // 第四种:
            System.out.println("第四种:通过Map.values()遍历所有的value,但不能遍历key");
            for (String v : map.values()) {
                System.out.println("value= " + v);
            }

            // 第五种:lambda java8推荐
            map.entrySet().forEach(entry -> System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue()));
            map.values().forEach(System.out::println); // 等价于map.values().forEach(value -> System.out.println(value));
            map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
        }
    }

猜你喜欢

转载自blog.csdn.net/cheidou123/article/details/95104243