今天碰到群里面发了一道比较有意思的笔试题
public static void main(String[] args) {
int a = 6;
int b = 8;
//int c = a;
/**
* 要求调用方法后
* 下面两行打印结果为
* a=60
* b=80
*/
method(a,b);
System.out.println("a="+a);
System.out.println("b="+b);
// System.out.println("a="+c);
// System.out.println("c="+c);
}
这道题目给值传递挖了坑 ,容易写成a=a*10 b=b*10,这样就掉坑里了
因为java只有值传递和引用传递,而这里a与b是原始类型,所以是值传递,方法里肯定是不能修改a与b的值了,那只能重写println打印方法了,所以里面的传参是个陷井,传不传参与重写println方法是没关系的
/**
* 文件名:TestOverWrite.java
*
* 版本信息:
* 日期:2017年2月17日
* Copyright 运联实泰 Corporation 2017
* 版权所有
*
*/
package com.yl.overwrite;
import java.io.PrintStream;
/**
* 此类描述的是:
* @author: zengqi
* @version: 2017年2月17日 下午3:00:30
*/
public class TestOverWrite {
public static void main(String[] args) {
int a = 6;
int b = 8;
int c = a;
/**
* 要求调用方法后
* 下面两行打印结果为
* a=60
* b=80
*/
method(a,b);
//method();
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("a="+c);
System.out.println("c="+c);
}
/**
* 此方法描述的是:
* @author: zengqi
* @version: 2017年2月17日 下午3:02:20
*/
private static void method(int a, int b) {
// TODO Auto-generated method stub
PrintStream pStream = new PrintStream(System.out){
@Override
public void println(String x) {
if("a=6".equals(x)){
x = "a=60";
}else if("b=8".equals(x)){
x = "b=80";
}else{
x = x;
}
super.println(x);
};
};
System.setOut(pStream);
}
private static void method() {
// TODO Auto-generated method stub
PrintStream pStream = new PrintStream(System.out){
@Override
public void println(String x) {
if("a=6".equals(x)){
x = "a=60";
}else if("b=8".equals(x)){
x = "b=80";
}else{
x = x;
}
super.println(x);
};
};
System.setOut(pStream);
}
}