All posts by dotte

图像识别 API

谷歌Cloud Vision API

第三方开发者可以集成图像识别和分类等功能到自己的应用。

微软 Project Oxford

Project Oxford 提供了用于计算机视觉、人脸识别,以及情绪分析的 API。

Computer Vision – Preview 5,000 transactions per month, 20 per minute.
Key 1:
d863ba460b9146daafba10aeb8099b07
Regenerate | Hide | Copy
Key 2:
XXXXXXXXXXXXXXXXXXXXXXXXXXX
Regenerate | Show | Copy
active ‎2016‎年‎8‎月‎4‎日
‎10‎:‎10‎:‎50
Show Quota

Video API https://www.microsoft.com/cognitive-services/en-us/video-api/documentation

Linux Shell 文本处理工具集锦

本文将介绍Linux下使用Shell处理文本时最常用的工具:

find、grep、xargs、sort、uniq、tr、cut、paste、wc、sed、awk;

提供的例子和参数都是最常用和最为实用的;

我对shell脚本使用的原则是命令单行书写,尽量不要超过2行;

如果有更为复杂的任务需求,还是考虑python吧;

find 文件查找

  • 查找txt和pdf文件
      find . ( -name "*.txt" -o -name "*.pdf" ) -print
  • 正则方式查找.txt和pdf
      find . -regex  ".*(.txt|.pdf)$"

    -iregex: 忽略大小写的正则

  • 否定参数查找所有非txt文本
       find . ! -name "*.txt" -print
  • 指定搜索深度打印出当前目录的文件(深度为1)
      find . -maxdepth 1 -type f

定制搜索

  • 按类型搜索:
      find . -type d -print  //只列出所有目录

    -type f 文件 / l 符号链接

  • 按时间搜索:-atime 访问时间 (单位是天,分钟单位则是-amin,以下类似)-mtime 修改时间 (内容被修改)-ctime 变化时间 (元数据或权限变化)最近7天被访问过的所有文件:
      find . -atime 7 -type f -print
  • 按大小搜索:w字 k M G寻找大于2k的文件
      find . -type f -size +2k

    按权限查找:

      find . -type f -perm 644 -print //找具有可执行权限的所有文件

    按用户查找:

      find . -type f -user weber -print// 找用户weber所拥有的文件

找到后的后续动作

  • 删除:删除当前目录下所有的swp文件:
      find . -type f -name "*.swp" -delete
  • 执行动作(强大的exec)
      find . -type f -user root -exec chown weber {} ; //将当前目录下的所有权变更为weber

    注:{}是一个特殊的字符串,对于每一个匹配的文件,{}会被替换成相应的文件名;

    eg:将找到的文件全都copy到另一个目录:

      find . -type f -mtime +10 -name "*.txt" -exec cp {} OLD ;
  • 结合多个命令tips: 如果需要后续执行多个命令,可以将多个命令写成一个脚本。然后 -exec 调用时执行脚本即可;
      -exec ./commands.sh {} \;

-print的定界符

默认使用’n’作为文件的定界符;

-print0 使用”作为文件的定界符,这样就可以搜索包含空格的文件;

grep 文本搜索

grep match_patten file // 默认访问匹配行

  • 常用参数-o 只输出匹配的文本行 VS -v 只输出没有匹配的文本行-c 统计文件中包含文本的次数
      grep -c "text" filename

    -n 打印匹配的行号

    -i 搜索时忽略大小写

    -l 只打印文件名

  • 在多级目录中对文本递归搜索(程序员搜代码的最爱):
      grep "class" . -R -n
  • 匹配多个模式
      grep -e "class" -e "vitural" file
  • grep输出以作为结尾符的文件名:(-z)
      grep "test" file* -lZ| xargs -0 rm

xargs 命令行参数转换

xargs 能够将输入数据转化为特定命令的命令行参数;这样,可以配合很多命令来组合使用。比如grep,比如find;

  • 将多行输出转化为单行输出cat file.txt| xargsn 是多行文本间的定界符
  • 将单行转化为多行输出cat single.txt | xargs -n 3-n:指定每行显示的字段数

xargs参数说明

-d 定义定界符 (默认为空格 多行的定界符为 n)

-n 指定输出为多行

-I {} 指定替换字符串,这个字符串在xargs扩展时会被替换掉,用于待执行的命令需要多个参数时

eg:

cat file.txt | xargs -I {} ./command.sh -p {} -1

-0:指定为输入定界符

eg:统计程序行数

find source_dir/ -type f -name "*.cpp" -print0 |xargs -0 wc -l

sort 排序

字段说明:

-n 按数字进行排序 VS -d 按字典序进行排序

-r 逆序排序

-k N 指定按第N列排序

eg:

sort -nrk 1 data.txt
sort -bd data // 忽略像空格之类的前导空白字符

uniq 消除重复行

  • 消除重复行
      sort unsort.txt | uniq
  • 统计各行在文件中出现的次数
      sort unsort.txt | uniq -c
  • 找出重复行
      sort unsort.txt | uniq -d

    可指定每行中需要比较的重复内容:-s 开始位置 -w 比较字符数

用tr进行转换

  • 通用用法
      echo 12345 | tr '0-9' '9876543210' //加解密转换,替换对应字符
      cat text| tr 't' ' '  //制表符转空格
  • tr删除字符
      cat file | tr -d '0-9' // 删除所有数字

    -c 求补集

      cat file | tr -c '0-9' //获取文件中所有数字
      cat file | tr -d -c '0-9 n'  //删除非数字数据
  • tr压缩字符tr -s 压缩文本中出现的重复字符;最常用于压缩多余的空格
      cat file | tr -s ' '
  • 字符类tr中可用各种字符类:alnum:字母和数字alpha:字母digit:数字

    space:空白字符

    lower:小写

    upper:大写

    cntrl:控制(非可打印)字符

    print:可打印字符

    使用方法:tr [:class:] [:class:]

      eg: tr '[:lower:]' '[:upper:]'

cut 按列切分文本

  • 截取文件的第2列和第4列:
      cut -f2,4 filename
  • 去文件除第3列的所有列:
      cut -f3 --complement filename
  • -d 指定定界符:
      cat -f2 -d";" filename
  • cut 取的范围N- 第N个字段到结尾-M 第1个字段为MN-M N到M个字段
  • cut 取的单位-b 以字节为单位-c 以字符为单位-f 以字段为单位(使用定界符)
  • eg:
      cut -c1-5 file //打印第一到5个字符
      cut -c-2 file  //打印前2个字符

paste 按列拼接文本

将两个文本按列拼接到一起;

cat file1
1
2

cat file2
colin
book

paste file1 file2
1 colin
2 book

默认的定界符是制表符,可以用-d指明定界符

paste file1 file2 -d “,”

1,colin

2,book

wc 统计行和字符的工具

wc -l file // 统计行数

wc -w file // 统计单词数

wc -c file // 统计字符数

sed 文本替换利器

  • 首处替换
      seg 's/text/replace_text/' file   //替换每一行的第一处匹配的text
  • 全局替换
       seg 's/text/replace_text/g' file

    默认替换后,输出替换后的内容,如果需要直接替换原文件,使用-i:

      seg -i 's/text/repalce_text/g' file
  • 移除空白行:
      sed '/^$/d' file
  • 变量转换已匹配的字符串通过标记&来引用.
    echo this is en example | seg 's/\w+/[&]/g'
    $>[this]  [is] [en] [example]
  • 子串匹配标记第一个匹配的括号内容使用标记 1 来引用
      sed 's/hello([0-9])/1/'
  • 双引号求值sed通常用单引号来引用;也可使用双引号,使用双引号后,双引号会对表达式求值:
      sed 's/$var/HLLOE/'

    当使用双引号时,我们可以在sed样式和替换字符串中指定变量;

    eg:
    p=patten
    r=replaced
    echo "line con a patten" | sed "s/$p/$r/g"
    $>line con a replaced
  • 其它示例字符串插入字符:将文本中每行内容(PEKSHA) 转换为 PEK/SHA
      sed 's/^.{3}/

awk 数据流处理工具

  • awk脚本结构awk ‘ BEGIN{ statements } statements2 END{ statements } ‘
  • 工作方式1.执行begin中语句块;2.从文件或stdin中读入一行,然后执行statements2,重复这个过程,直到文件全部被读取完毕;3.执行end语句块;

print 打印当前行

  • 使用不带参数的print时,会打印当前行;
      echo -e "line1nline2" | awk 'BEGIN{print "start"} {print } END{ print "End" }'
  • print 以逗号分割时,参数以空格定界;
    echo | awk ' {var1 = "v1" ; var2 = "V2"; var3="v3"; 
    print var1, var2 , var3; }'
    $>v1 V2 v3
  • 使用-拼接符的方式(””作为拼接符);
    echo | awk ' {var1 = "v1" ; var2 = "V2"; var3="v3"; 
    print var1"-"var2"-"var3; }'
    $>v1-V2-v3

特殊变量: NR NF $0 $1 $2

NR:表示记录数量,在执行过程中对应当前行号;

NF:表示字段数量,在执行过程总对应当前行的字段数;

$0:这个变量包含执行过程中当前行的文本内容;

$1:第一个字段的文本内容;

$2:第二个字段的文本内容;

echo -e "line1 f2 f3n line2 n line 3" | awk '{print NR":"$0"-"$1"-"$2}'
  • 打印每一行的第二和第三个字段:
      awk '{print $2, $3}' file
  • 统计文件的行数:
      awk ' END {print NR}' file
  • 累加每一行的第一个字段:
      echo -e "1n 2n 3n 4n" | awk 'BEGIN{num = 0 ;
      print "begin";} {sum += $1;} END {print "=="; print sum }'

传递外部变量

var=1000
echo | awk '{print vara}' vara=$var #  输入来自stdin
awk '{print vara}' vara=$var file # 输入来自文件

用样式对awk处理的行进行过滤

awk ‘NR awk ‘NR==1,NR==4 {print}’ file #行号等于1和4的打印出来

awk ‘/linux/’ #包含linux文本的行(可以用正则表达式来指定,超级强大)

awk ‘!/linux/’ #不包含linux文本的行

设置定界符

使用-F来设置定界符(默认为空格)

awk -F: ‘{print $NF}’ /etc/passwd

读取命令输出

使用getline,将外部shell命令的输出读入到变量cmdout中;

echo | awk '{"grep root /etc/passwd" | getline cmdout; print cmdout }'

在awk中使用循环

for(i=0;ifor(i in array){print array[i];}

eg:

以逆序的形式打印行:(tac命令的实现)

seq 9| 
awk '{lifo[NR] = $0; lno=NR} 
END{ for(;lno>-1;lno--){print lifo[lno];}
} '

awk实现head、tail命令

  • head:
       awk 'NR<=10{print}' filename
  • tail:
      awk '{buffer[NR%10] = $0;} END{for(i=0;i<11;i++){ \
      print buffer[i %10]} } ' filename

打印指定列

  • awk方式实现:
      ls -lrt | awk '{print $6}'
  • cut方式实现
      ls -lrt | cut -f6

打印指定文本区域

  • 确定行号
      seq 100| awk 'NR==4,NR==6{print}'
  • 确定文本打印处于start_pattern 和end_pattern之间的文本;
      awk '/start_pattern/, /end_pattern/' filename

    eg:

    seq 100 | awk '/13/,/15/'
    cat /etc/passwd| awk '/mai.*mail/,/news.*news/'

awk常用内建函数

index(string,search_string):返回search_string在string中出现的位置

sub(regex,replacement_str,string):将正则匹配到的第一处内容替换为replacement_str;

match(regex,string):检查正则表达式是否能够匹配字符串;

length(string):返回字符串长度

echo | awk '{"grep root /etc/passwd" | getline cmdout; print length(cmdout) }'

printf 类似c语言中的printf,对输出进行格式化

eg:

seq 10 | awk '{printf "->%4sn", $1}'

迭代文件中的行、单词和字符

1. 迭代文件中的每一行

  • while 循环法
    while read line;
    do
    echo $line;
    done < file.txt
    改成子shell:
    cat file.txt | (while read line;do echo $line;done)
  • awk法:cat file.txt| awk ‘{print}’

2.迭代一行中的每一个单词

for word in $line;
do 
echo $word;
done

3. 迭代每一个字符

${string:start_pos:num_of_chars}:从字符串中提取一个字符;(bash文本切片)

${#word}:返回变量word的长度

for((i=0;i<${#word};i++))
do
echo ${word:i:1);
done
from:http://www.cnblogs.com/me115/p/3427319.html

18 道 Google 面试题

即使是最成功的公司,它的招聘过程有时也会很不靠谱,经常会出一些奇怪的看似没有答案的面试问题,但标准答案却让应聘者还没来得及接近「起跑线」就被「退赛」了。Google 曾经就是这样的公司,招聘人员会出一些难为应聘者的高质量问题。

事实上,有些问题实在是太古怪了,最终被完全禁用。2009 年,西雅图工作教练 Lewis 列出了他的客户被 Google 公司问过的 140 个问题,并选出了 17 个最让人抓狂的问题。这些问题已经被禁用了,Google 公司未来的新员工应该感到庆幸。下面让我们看看这些让人崩溃的问题吧。

1. 清洗所有西雅图的窗户需要多少钱?seattle-getty

2. 为什么井盖是圆的?

3. 如何在不直接询问你朋友 Bob 的情况下,确认他是否有你的电话号码?

你必须在卡片上写下问题并将卡片给 Eve,Eve 将卡片转交给 Bob 并将问题的回复转达给你。你不能直接将问题写在卡片上,但要确保让 Bob 对回复的信息进行加密,将电话号码对 Eve 保密。

4. 全世界有多少钢琴调音师?6-piano-palyer-get

5. 在一个有 100 对已婚夫妇的村庄里,每个男人都欺骗他的妻子

村里的每个妇人都会立刻知道其他妇人的丈夫是否欺骗了他的妻子,但不知道自己的丈夫有没有欺骗自己。村里规定不允许私通。任何妇人只要能证明她的丈夫对她不忠,她的丈夫就必须在当天被处死。村里的妇人们都遵守这项规定。有一天,村庄的女王宣布至少有一个丈夫不忠。究竟发生了什么?

6. 一个人把车推到了一家旅馆并失去了他的财产,发生了什么?

7. 钟表的指针每天重叠多少次?

daylight-savings-time

8. 美国每年生产多少个真空装置?

9. 为旧金山设计一个疏散计划

10. 解释一下「死牛肉」的重要性

Fui1OkEhMfBfgxx9dc0T2BAanddu

11. 如果一个人在电话上拨了一串数字,这些数字最有可能组成什么单词或是字符串?

12. 如果保证人体密度不变的情况下,将你缩小到一个硬币的大小,并且被扔进了一个空的玻璃搅拌机中,搅拌机将在 60 秒之后启动,你将怎么做?

13. 一辆校车能装多少个高尔夫球?

623221_bin

14. 两个鸡蛋和 100 层大楼的问题

你拥有两个鸡蛋,鸡蛋从某一特定楼层及以上的楼层扔下会破粹,从以下的楼层扔下会完好无损。两个鸡蛋完全相同。现在有一个 100 层的大楼,只有两个鸡蛋可以使用,你需要找出让鸡蛋摔碎的临界楼层,问题是你将扔多少次鸡蛋?

15. 你必须从 A 点到达 B 点,但你并不清楚能否到达,你将怎么办?

16. 你和你的朋友一起参加一个派对,同时出席的一共有十个人(包括你和你的朋友)

v2-drinking

17. 用三句话向你八岁大的侄子解释什么是数据库

from:http://www.techug.com/google-used

原文地址:www.independent.co.uk

Java 8 简明教程

目 录

  1. 允许在接口中有默认方法实现
  2. Lambda表达式
  3. 函数式接口
  4. 方法和构造函数引用
  5. Lambda的范围
  6. 内置函数式接口
  7. Streams
  8. Parallel Streams
  9. Map
  10. 时间日期API
  11. Annotations
  12. 总结

“Java并没有没落,人们很快就会发现这一点”

欢迎阅读我编写的Java 8介绍。本教程将带领你一步一步地认识这门语言的新特性。通过简单明了的代码示例,你将会学习到如何使用默认接口方法,Lambda表达式,方法引用和重复注解。看完这篇教程后,你还将对最新推出的API有一定的了解,例如:流控制,函数式接口,map扩展和新的时间日期API等等。

允许在接口中有默认方法实现

Java 8 允许我们使用default关键字,为接口声明添加非抽象的方法实现。这个特性又被称为扩展方法。下面是我们的第一个例子:

1
2
3
4
5
6
7
interface Formula {
    double calculate(int a);
    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}

在接口Formula中,除了抽象方法caculate以外,还定义了一个默认方法sqrt。Formula的实现类只需要实现抽象方法caculate就可以了。默认方法sqrt可以直接使用。

1
2
3
4
5
6
7
8
9
Formula formula = new Formula() {
    @Override
    public double calculate(int a) {
        return sqrt(a * 100);
    }
};
formula.calculate(100);     // 100.0
formula.sqrt(16);           // 4.0

formula对象以匿名对象的形式实现了Formula接口。代码很啰嗦:用了6行代码才实现了一个简单的计算功能:a*100开平方根。我们在下一节会看到,Java 8 还有一种更加优美的方法,能够实现包含单个函数的对象。

Lambda表达式

让我们从最简单的例子开始,来学习如何对一个string列表进行排序。我们首先使用Java 8之前的方法来实现:

1
2
3
4
5
6
7
8
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return b.compareTo(a);
    }
});

静态工具方法Collections.sort接受一个list,和一个Comparator接口作为输入参数,Comparator的实现类可以对输入的list中的元素进行比较。通常情况下,你可以直接用创建匿名Comparator对象,并把它作为参数传递给sort方法。

除了创建匿名对象以外,Java 8 还提供了一种更简洁的方式,Lambda表达式。

1
2
3
Collections.sort(names, (String a, String b) -> {
    return b.compareTo(a);
});

你可以看到,这段代码就比之前的更加简短和易读。但是,它还可以更加简短:

1
Collections.sort(names, (String a, String b) -> b.compareTo(a));

只要一行代码,包含了方法体。你甚至可以连大括号对{}和return关键字都省略不要。不过这还不是最短的写法:

1
Collections.sort(names, (a, b) -> b.compareTo(a));

Java编译器能够自动识别参数的类型,所以你就可以省略掉类型不写。让我们再深入地研究一下lambda表达式的威力吧。

函数式接口

Lambda表达式如何匹配Java的类型系统?每一个lambda都能够通过一个特定的接口,与一个给定的类型进行匹配。一个所谓的函数式接口必须要有且仅有一个抽象方法声明。每个与之对应的lambda表达式必须要与抽象方法的声明相匹配。由于默认方法不是抽象的,因此你可以在你的函数式接口里任意添加默认方法。

任意只包含一个抽象方法的接口,我们都可以用来做成lambda表达式。为了让你定义的接口满足要求,你应当在接口前加上@FunctionalInterface 标注。编译器会注意到这个标注,如果你的接口中定义了第二个抽象方法的话,编译器会抛出异常。

举例:

1
2
3
4
5
6
7
8
@FunctionalInterface
interface Converter<F, T> {
    T convert(F from);
}
Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
Integer converted = converter.convert("123");
System.out.println(converted);    // 123

注意,如果你不写@FunctionalInterface 标注,程序也是正确的。

方法和构造函数引用

上面的代码实例可以通过静态方法引用,使之更加简洁:

1
2
3
Converter<String, Integer> converter = Integer::valueOf;
Integer converted = converter.convert("123");
System.out.println(converted);   // 123

Java 8 允许你通过::关键字获取方法或者构造函数的的引用。上面的例子就演示了如何引用一个静态方法。而且,我们还可以对一个对象的方法进行引用:

1
2
3
4
5
6
7
8
9
10
class Something {
    String startsWith(String s) {
        return String.valueOf(s.charAt(0));
    }
}
Something something = new Something();
Converter<String, String> converter = something::startsWith;
String converted = converter.convert("Java");
System.out.println(converted);    // "J"

让我们看看如何使用::关键字引用构造函数。首先我们定义一个示例bean,包含不同的构造方法:

1
2
3
4
5
6
7
8
9
10
11
class Person {
    String firstName;
    String lastName;
    Person() {}
    Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

接下来,我们定义一个person工厂接口,用来创建新的person对象:

1
2
3
interface PersonFactory<P extends Person> {
    P create(String firstName, String lastName);
}

然后我们通过构造函数引用来把所有东西拼到一起,而不是像以前一样,通过手动实现一个工厂来这么做。

1
2
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Peter", "Parker");

我们通过Person::new来创建一个Person类构造函数的引用。Java编译器会自动地选择合适的构造函数来匹配PersonFactory.create函数的签名,并选择正确的构造函数形式。

Lambda的范围

对于lambdab表达式外部的变量,其访问权限的粒度与匿名对象的方式非常类似。你能够访问局部对应的外部区域的局部final变量,以及成员变量和静态变量。

访问局部变量

我们可以访问lambda表达式外部的final局部变量:

1
2
3
4
5
final int num = 1;
Converter<Integer, String> stringConverter =
        (from) -> String.valueOf(from + num);
stringConverter.convert(2);     // 3

但是与匿名对象不同的是,变量num并不需要一定是final。下面的代码依然是合法的:

1
2
3
4
5
int num = 1;
Converter<Integer, String> stringConverter =
        (from) -> String.valueOf(from + num);
stringConverter.convert(2);     // 3

然而,num在编译的时候被隐式地当做final变量来处理。下面的代码就不合法:

1
2
3
4
int num = 1;
Converter<Integer, String> stringConverter =
        (from) -> String.valueOf(from + num);
num = 3;

在lambda表达式内部企图改变num的值也是不允许的。

访问成员变量和静态变量

与局部变量不同,我们在lambda表达式的内部能获取到对成员变量或静态变量的读写权。这种访问行为在匿名对象里是非常典型的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Lambda4 {
    static int outerStaticNum;
    int outerNum;
    void testScopes() {
        Converter<Integer, String> stringConverter1 = (from) -> {
            outerNum = 23;
            return String.valueOf(from);
        };
        Converter<Integer, String> stringConverter2 = (from) -> {
            outerStaticNum = 72;
            return String.valueOf(from);
        };
    }
}

访问默认接口方法

还记得第一节里面formula的那个例子么? 接口Formula定义了一个默认的方法sqrt,该方法能够访问formula所有的对象实例,包括匿名对象。这个对lambda表达式来讲则无效。

默认方法无法在lambda表达式内部被访问。因此下面的代码是无法通过编译的:

1
Formula formula = (a) -> sqrt( a * 100);

内置函数式接口

JDK 1.8 API中包含了很多内置的函数式接口。有些是在以前版本的Java中大家耳熟能详的,例如Comparator接口,或者Runnable接口。对这些现成的接口进行实现,可以通过@FunctionalInterface 标注来启用Lambda功能支持。

此外,Java 8 API 还提供了很多新的函数式接口,来降低程序员的工作负担。有些新的接口已经在Google Guava库中很有名了。如果你对这些库很熟的话,你甚至闭上眼睛都能够想到,这些接口在类库的实现过程中起了多么大的作用。

Predicates

Predicate是一个布尔类型的函数,该函数只有一个输入参数。Predicate接口包含了多种默认方法,用于处理复杂的逻辑动词(and, or,negate)

1
2
3
4
5
6
7
8
9
10
Predicate<String> predicate = (s) -> s.length() > 0;
predicate.test("foo");              // true
predicate.negate().test("foo");     // false
Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();

Functions

Function接口接收一个参数,并返回单一的结果。默认方法可以将多个函数串在一起(compse, andThen)

1
2
3
4
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
backToString.apply("123");     // "123"

Suppliers

Supplier接口产生一个给定类型的结果。与Function不同的是,Supplier没有输入参数。

1
2
Supplier<Person> personSupplier = Person::new;
personSupplier.get();   // new Person

Consumers

Consumer代表了在一个输入参数上需要进行的操作。

1
2
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));

Comparators

Comparator接口在早期的Java版本中非常著名。Java 8 为这个接口添加了不同的默认方法。

1
2
3
4
5
6
7
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
Person p1 = new Person("John", "Doe");
Person p2 = new Person("Alice", "Wonderland");
comparator.compare(p1, p2);             // > 0
comparator.reversed().compare(p1, p2);  // < 0

Optionals

Optional不是一个函数式接口,而是一个精巧的工具接口,用来防止NullPointerEception产生。这个概念在下一节会显得很重要,所以我们在这里快速地浏览一下Optional的工作原理。

Optional是一个简单的值容器,这个值可以是null,也可以是non-null。考虑到一个方法可能会返回一个non-null的值,也可能返回一个空值。为了不直接返回null,我们在Java 8中就返回一个Optional.

1
2
3
4
5
6
7
Optional<String> optional = Optional.of("bam");
optional.isPresent();           // true
optional.get();                 // "bam"
optional.orElse("fallback");    // "bam"
optional.ifPresent((s) -> System.out.println(s.charAt(0)));     // "b"

Streams

java.util.Stream表示了某一种元素的序列,在这些元素上可以进行各种操作。Stream操作可以是中间操作,也可以是完结操作。完结操作会返回一个某种类型的值,而中间操作会返回流对象本身,并且你可以通过多次调用同一个流操作方法来将操作结果串起来(就像StringBuffer的append方法一样————译者注)。Stream是在一个源的基础上创建出来的,例如java.util.Collection中的list或者set(map不能作为Stream的源)。Stream操作往往可以通过顺序或者并行两种方式来执行。

我们先了解一下序列流。首先,我们通过string类型的list的形式创建示例数据:

1
2
3
4
5
6
7
8
9
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");

Java 8中的Collections类的功能已经有所增强,你可以之直接通过调用Collections.stream()或者Collection.parallelStream()方法来创建一个流对象。下面的章节会解释这个最常用的操作。

Filter

Filter接受一个predicate接口类型的变量,并将所有流对象中的元素进行过滤。该操作是一个中间操作,因此它允许我们在返回结果的基础上再进行其他的流操作(forEach)。ForEach接受一个function接口类型的变量,用来执行对每一个元素的操作。ForEach是一个中止操作。它不返回流,所以我们不能再调用其他的流操作。

1
2
3
4
5
6
stringCollection
    .stream()
    .filter((s) -> s.startsWith("a"))
    .forEach(System.out::println);
// "aaa2", "aaa1"

Sorted

Sorted是一个中间操作,能够返回一个排过序的流对象的视图。流对象中的元素会默认按照自然顺序进行排序,除非你自己指定一个Comparator接口来改变排序规则。

1
2
3
4
5
6
7
stringCollection
    .stream()
    .sorted()
    .filter((s) -> s.startsWith("a"))
    .forEach(System.out::println);
// "aaa1", "aaa2"

一定要记住,sorted只是创建一个流对象排序的视图,而不会改变原来集合中元素的顺序。原来string集合中的元素顺序是没有改变的。

1
2
System.out.println(stringCollection);
// ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1

Map

map是一个对于流对象的中间操作,通过给定的方法,它能够把流对象中的每一个元素对应到另外一个对象上。下面的例子就演示了如何把每个string都转换成大写的string. 不但如此,你还可以把每一种对象映射成为其他类型。对于带泛型结果的流对象,具体的类型还要由传递给map的泛型方法来决定。

1
2
3
4
5
6
7
stringCollection
    .stream()
    .map(String::toUpperCase)
    .sorted((a, b) -> b.compareTo(a))
    .forEach(System.out::println);
// "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"

Match

匹配操作有多种不同的类型,都是用来判断某一种规则是否与流对象相互吻合的。所有的匹配操作都是终结操作,只返回一个boolean类型的结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
boolean anyStartsWithA =
    stringCollection
        .stream()
        .anyMatch((s) -> s.startsWith("a"));
System.out.println(anyStartsWithA);      // true
boolean allStartsWithA =
    stringCollection
        .stream()
        .allMatch((s) -> s.startsWith("a"));
System.out.println(allStartsWithA);      // false
boolean noneStartsWithZ =
    stringCollection
        .stream()
        .noneMatch((s) -> s.startsWith("z"));
System.out.println(noneStartsWithZ);      // true

Count

Count是一个终结操作,它的作用是返回一个数值,用来标识当前流对象中包含的元素数量。

1
2
3
4
5
6
7
long startsWithB =
    stringCollection
        .stream()
        .filter((s) -> s.startsWith("b"))
        .count();
System.out.println(startsWithB);    // 3

Reduce

该操作是一个终结操作,它能够通过某一个方法,对元素进行削减操作。该操作的结果会放在一个Optional变量里返回。

1
2
3
4
5
6
7
8
Optional<String> reduced =
    stringCollection
        .stream()
        .sorted()
        .reduce((s1, s2) -> s1 + "#" + s2);
reduced.ifPresent(System.out::println);
// "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"

Parallel Streams

像上面所说的,流操作可以是顺序的,也可以是并行的。顺序操作通过单线程执行,而并行操作则通过多线程执行。

下面的例子就演示了如何使用并行流进行操作来提高运行效率,代码非常简单。

首先我们创建一个大的list,里面的元素都是唯一的:

1
2
3
4
5
6
int max = 1000000;
List<String> values = new ArrayList<>(max);
for (int i = 0; i < max; i++) {
    UUID uuid = UUID.randomUUID();
    values.add(uuid.toString());
}

现在,我们测量一下对这个集合进行排序所使用的时间。

顺序排序

1
2
3
4
5
6
7
8
9
10
11
long t0 = System.nanoTime();
long count = values.stream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("sequential sort took: %d ms", millis));
// sequential sort took: 899 ms

并行排序

1
2
3
4
5
6
7
8
9
10
11
long t0 = System.nanoTime();
long count = values.parallelStream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("parallel sort took: %d ms", millis));
// parallel sort took: 472 ms

如你所见,所有的代码段几乎都相同,唯一的不同就是把stream()改成了parallelStream(), 结果并行排序快了50%。

Map

正如前面已经提到的那样,map是不支持流操作的。而更新后的map现在则支持多种实用的新方法,来完成常规的任务。

1
2
3
4
5
6
7
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
    map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));

上面的代码风格是完全自解释的:putIfAbsent避免我们将null写入;forEach接受一个消费者对象,从而将操作实施到每一个map中的值上。

下面的这个例子展示了如何使用函数来计算map的编码

1
2
3
4
5
6
7
8
9
10
11
map.computeIfPresent(3, (num, val) -> val + num);
map.get(3);             // val33
map.computeIfPresent(9, (num, val) -> null);
map.containsKey(9);     // false
map.computeIfAbsent(23, num -> "val" + num);
map.containsKey(23);    // true
map.computeIfAbsent(3, num -> "bam");
map.get(3);             // val33

接下来,我们将学习,当给定一个key值时,如何把一个实例从对应的key中移除:

 

1
2
3
4
5
map.remove(3, "val3");
map.get(3);             // val33
map.remove(3, "val33");
map.get(3);             // null

另一个有用的方法:

1
map.getOrDefault(42, "not found");  // not found

将map中的实例合并也是非常容易的:

1
2
3
4
5
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
map.get(9);             // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
map.get(9);             // val9concat

合并操作先看map中是否没有特定的key/value存在,如果是,则把key/value存入map,否则merging函数就会被调用,对现有的数值进行修改。

时间日期API

Java 8 包含了全新的时间日期API,这些功能都放在了java.time包下。新的时间日期API是基于Joda-Time库开发的,但是也不尽相同。下面的例子就涵盖了大多数新的API的重要部分。

Clock

Clock提供了对当前时间和日期的访问功能。Clock是对当前时区敏感的,并可用于替代System.currentTimeMillis()方法来获取当前的毫秒时间。当前时间线上的时刻可以用Instance类来表示。Instance也能够用于创建原先的java.util.Date对象。

1
2
3
4
5
Clock clock = Clock.systemDefaultZone();
long millis = clock.millis();
Instant instant = clock.instant();
Date legacyDate = Date.from(instant);   // legacy java.util.Date

Timezones

时区类可以用一个ZoneId来表示。时区类的对象可以通过静态工厂方法方便地获取。时区类还定义了一个偏移量,用来在当前时刻或某时间与目标时区时间之间进行转换。

1
2
3
4
5
6
7
8
9
10
System.out.println(ZoneId.getAvailableZoneIds());
// prints all available timezone ids
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
// ZoneRules[currentStandardOffset=+01:00]
// ZoneRules[currentStandardOffset=-03:00]

LocalTime

本地时间类表示一个没有指定时区的时间,例如,10 p.m.或者17:30:15,下面的例子会用上面的例子定义的时区创建两个本地时间对象。然后我们会比较两个时间,并计算它们之间的小时和分钟的不同。

1
2
3
4
5
6
7
8
9
10
LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now1.isBefore(now2));  // false
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
System.out.println(hoursBetween);       // -3
System.out.println(minutesBetween);     // -239

LocalTime是由多个工厂方法组成,其目的是为了简化对时间对象实例的创建和操作,包括对时间字符串进行解析的操作。

1
2
3
4
5
6
7
8
9
10
LocalTime late = LocalTime.of(23, 59, 59);
System.out.println(late);       // 23:59:59
DateTimeFormatter germanFormatter =
    DateTimeFormatter
        .ofLocalizedTime(FormatStyle.SHORT)
        .withLocale(Locale.GERMAN);
LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
System.out.println(leetTime);   // 13:37

LocalDate

本地时间表示了一个独一无二的时间,例如:2014-03-11。这个时间是不可变的,与LocalTime是同源的。下面的例子演示了如何通过加减日,月,年等指标来计算新的日期。记住,每一次操作都会返回一个新的时间对象。

1
2
3
4
5
6
7
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);    // FRIDAY<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">Parsing a LocalDate from a string is just as simple as parsing a LocalTime:</span>

解析字符串并形成LocalDate对象,这个操作和解析LocalTime一样简单。

1
2
3
4
5
6
7
DateTimeFormatter germanFormatter =
    DateTimeFormatter
        .ofLocalizedDate(FormatStyle.MEDIUM)
        .withLocale(Locale.GERMAN);
LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
System.out.println(xmas);   // 2014-12-24

LocalDateTime

LocalDateTime表示的是日期-时间。它将刚才介绍的日期对象和时间对象结合起来,形成了一个对象实例。LocalDateTime是不可变的,与LocalTime和LocalDate的工作原理相同。我们可以通过调用方法来获取日期时间对象中特定的数据域。

1
2
3
4
5
6
7
8
9
10
LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
System.out.println(dayOfWeek);      // WEDNESDAY
Month month = sylvester.getMonth();
System.out.println(month);          // DECEMBER
long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println(minuteOfDay);    // 1439

如果再加上的时区信息,LocalDateTime能够被转换成Instance实例。Instance能够被转换成以前的java.util.Date对象。

1
2
3
4
5
6
Instant instant = sylvester
        .atZone(ZoneId.systemDefault())
        .toInstant();
Date legacyDate = Date.from(instant);
System.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014

格式化日期-时间对象就和格式化日期对象或者时间对象一样。除了使用预定义的格式以外,我们还可以创建自定义的格式化对象,然后匹配我们自定义的格式。

1
2
3
4
5
6
7
DateTimeFormatter formatter =
    DateTimeFormatter
        .ofPattern("MMM dd, yyyy - HH:mm");
LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
String string = formatter.format(parsed);
System.out.println(string);     // Nov 03, 2014 - 07:13

不同于java.text.NumberFormat,新的DateTimeFormatter类是不可变的,也是线程安全的。

更多的细节,请看这里

 

Annotations

Java 8中的注解是可重复的。让我们直接深入看看例子,弄明白它是什么意思。

首先,我们定义一个包装注解,它包括了一个实际注解的数组

1
2
3
4
5
6
7
8
@interface Hints {
    Hint[] value();
}
@Repeatable(Hints.class)
@interface Hint {
    String value();
}

只要在前面加上注解名:@Repeatable,Java 8 允许我们对同一类型使用多重注解,

变体1:使用注解容器(老方法)

1
2
@Hints({@Hint("hint1"), @Hint("hint2")})
class Person {}

变体2:使用可重复注解(新方法)

1
2
3
@Hint("hint1")
@Hint("hint2")
class Person {}

使用变体2,Java编译器能够在内部自动对@Hint进行设置。这对于通过反射来读取注解信息来说,是非常重要的。

1
2
3
4
5
6
7
8
Hint hint = Person.class.getAnnotation(Hint.class);
System.out.println(hint);                   // null
Hints hints1 = Person.class.getAnnotation(Hints.class);
System.out.println(hints1.value().length);  // 2
Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class);
System.out.println(hints2.length);          // 2

尽管我们绝对不会在Person类上声明@Hints注解,但是它的信息仍然可以通过getAnnotation(Hints.class)来读取。并且,getAnnotationsByType方法会更方便,因为它赋予了所有@Hints注解标注的方法直接的访问权限。

1
2
@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
@interface MyAnnotation {}

先到这里

我的Java 8编程指南就到此告一段落。当然,还有很多内容需要进一步研究和说明。这就需要靠读者您来对JDK 8进行探究了,例如:Arrays.parallelSort, StampedLock和CompletableFuture等等 ———— 我这里只是举几个例子而已。

我希望这个博文能够对您有所帮助,也希望您阅读愉快。完整的教程源代码放在了GitHub上。您可以尽情地fork,并请通过Twitter告诉我您的反馈。

原文链接: winterbe 翻译: ImportNew.com 黄小非
译文链接: http://www.importnew.com/10360.html

100+ Core Java Interview Questions

Table of Contents

  1. Basic Questions
  2. OOPs interview Questions
  3. Exception handling interview Questions
  4. Java Multithreading interview Questions
  5. Serialization interview Questions
  6. String Interview Questions
  7. Java Collections interview Questions
  8. Applet interview Questions

Basic Questions

Q) Is Java platform independent?
Yes. Java is a platform independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run it on Linux or any other supported platform. This is one of the main features of java.

Q) What all memory areas are allocated by JVM?
Heap, Stack, Program Counter Register and Native Method Stack

Q) Java vs. C ++?
The following features of java make it different from the C++:

  • Simple
  • Multi-threaded
  • Distributed Application
  • Robust
  • Security
  • Complexities are removed (Pointers, Operator overloading, Multiple inheritance).

Q) What is javac ?
It produces the java byte code from *.java file. It is the intermediate representation of your source code that contains instructions.

Q) What is class?
Class is nothing but a template that describes the data and behavior associated with instances of that class

Q) What is the base class of all classes?
java.lang.Object

Q) Path and ClassPath
Path specifies the location of .exe files while classpath is used for specifying the location of .class files.

Q) Different Data types in Java.

  • byte – 8 bit (are esp. useful when working with a stream of data from a network or a file).
  • short – 16 bit
  • char – 16 bit Unicode
  • int – 32 bit (whole number)
  • float – 32 bit (real number)
  • long – 64 bit (Single precision)
  • double – 64 bit (double precision)

Note: Any time you have an integer expression involving bytes, shorts, ints and literal numbers, the entire expression is promoted to int before the calculation is done.

Q) What is Unicode?
Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.

Q) What are Literals?
A literal is a value that may be assigned to a primitive or string variable or passed as an argument to a method.

Q) Dynamic Initialization?
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.

Q) What is Type casting in Java?
To create a conversion between two incompatible types, we must use a cast. There are two types of casting in java: automatic casting (done automatically) and explicit casting (done by programmer).

Q) Arrays?
An array is a group of fixed number of same type values. Read more about Arrays here.

Q) What is BREAK statement in java?
It is also referred as terminator. In Java, the break statement can be used in following two cases:

  • It terminates a statement sequence in a switch-case statement.
  • It can be used to come out of a loop

Q) Why can’t I do myArray.length () ? Arrays are just objects, right?
Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as toString () and hashCode () on an array. However, length is a data item of an array and not a method. So you have to use myArray.length.

Q) How can I put all my classes and resources into one file and run it?
Use a JAR file. Put all the files in a JAR, then run the app like this:

Java -jar [-options] jarfile [args...]

Q) Can I declare a data type inside loop in java?
Any Data type declaration should not be inside the loop.

Q) Advantage over jdk 1.0 vs. jdk 1.1 ?
Jdk1.1 release consists of Java Unicode character to support the multiple language fonts, along with Event Handling, Java security, Java Beans, RMI, SQL are the major feature provided.

Q) java.lang.* get imported by default. For using String and Exception classes, you don’t need to explicitly import this package. The major classes inside this package are

  • Object class
  • Data type wrapper classes
  • Math class
  • String class
  • System and Runtime classes
  • Thread classes
  • Exception classes
  • Process classes
  • Class classes

Q) Arrays can be defined in different ways. Write them down.

int arr[] = null;
int arr[][] = new int arr[][];
int [][] arr = new arr [][];
int [] arr [] = new arr[][];

OOPs Interview Questions

Q) Four main principles of OOPS language?

  • Inheritance
  • Polymorphism
  • Data Encapsulation
  • Abstraction

Q) What is inheritance?
The process by which one class acquires the properties and functionalities of another class. Inheritance brings reusability of code in a java application. Read more here.

Q) Does Java support Multiple Inheritances?
When a class extends more than one classes then it is called multiple inheritance. Java doesn’t support multiple inheritance whereas C++ supports it, this is one of the difference between java and C++.  Refer this: Why java doesn’t support multiple inheritance?

Q) What is Polymorphism and what are the types of it?
Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism, read them in detail here.

Q) What is the method overriding?
It is a feature using which a child class overrides the method of parent class. It is only applicable when the method in child class has the signature same as parent class. Read more about method overriding here.

Q) Can we override a static method?
No, we cannot override a static method.

Q) What is method overloading?
Having more than one method with the same name but different number, sequence or types of arguments is known is method overloading. Read more about it here.

Q) Does Java support operator overloading?
Operator overloading is not supported in Java.

Q) Can we overload a method by just changing the return type and without changing the signature of method?
No, We cannot do this.

Q) Is it possible to overload main() method of a class?
Yes, we can overload main() method as well.

Q) What is the difference between method overloading and method overriding?
There are several differences; You can read them here: Overloading Vs Overriding.

Q) What is static and dynamic binding?
Binding refers to the linking of method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding.

Q) What is Encapsulation?
Encapsulation means the localization of the information or knowledge within an object.
Encapsulation is also called as “Information Hiding”. Read it here in detail.

Q) Abstract class?
An abstract class is a class which can’t be instantiated (we cannot create the object of abstract class), we can only extend such classes. It provides the generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial abstraction using abstract classes, to achieve full abstraction we use interfaces.

Q) What is Interface in java?
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Read more about interface here.

Q) What is the difference between abstract class and interface?
1) abstract class can have abstract and non-abstract methods. An interface can only have abstract methods.
2) An abstract class can have static methods but an interface cannot have static methods.
3) abstract class can have constructors but an interface cannot have constructors.

Q) Which access modifiers can be applied to the inner classes?
public ,private , abstract, final, protected.

Q) What are Constructors?
Constructors are used for creating an instance of a class, they are invoked when an instance of class gets created. Constructor name and class name should be same and it doesn’t have a return type. Read more about constructors here.

Q) Can we inherit the constructors?
No, we cannot inherit constructors.

Q) Can we mark constructors final?
No, Constructor cannot be declared final.

Q) What is default and parameterized constructors?
Default: Constructors with no arguments are known as default constructors, when you don’t declare any constructor in a class, compiler creates a default one automatically.

Parameterized: Constructor with arguments are known as parameterized constructors.

Q) Can a constructor call another constructor?
Yes. A constructor can call the another constructor of same class using this keyword. For e.g. this() calls the default constructor.
Note: this() must be the first statement in the calling constructor.

Q) Can a constructor call the constructor of parent class?
Yes. In fact it happens by default. A child class constructor always calls the parent class constructor. However we can still call it using super keyword. For e.g. super() can be used for calling super class default constructor.

Note: super() must be the first statement in a constructor.

Q)THIS keyword?
The THIS keyword is a reference to the current object.

Q) Can this keyword be assigned null value?
No, this keyword cannot have null values assigned to it.

Q) Explain ways to pass the arguments in Java?
In java, arguments can be passed in 2 ways,

Pass by value – Changes made to the parameter of the subroutines have no effect on the argument used to call it.
Pass by reference – Changes made to the parameter will affect the argument used to call the subroutine.

Q) What is static variable in java?
Static variables are also known as class level variables. A static variable is same for all the objects of that particular class in which it is declared.

Q) What is static block?
A static block gets executed at the time of class loading. They are used for initializing static variables.

Q) What is a static method?
Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating instance of class.

Q) Explain super keyword in Java?
super keyword references to the parent class. There are several uses of super keyword:

  • It can be used to call the superclass(Parent class) constructor.
  • It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).
  • To call the constructor of parent class.

Q) Use of final keyword in Java?
Final methods – These methods cannot be overridden by any other method.
Final variable – Constants, the value of these variable can’t be changed, its fixed.
Final class – Such classes cannot be inherited by other classes. These type of classes will be used when application required security or someone don’t want that particular class. More details.

Q) What is a Object class?
This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods

  • objectClone () – to creates a new object that is same as the object being cloned.
  • boolean equals(Object obj) – determines whether one object is equal to another.
  • finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
  • toString () – Returns a string representation of the object.

Q) What are Packages?
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations )

Q)What is the difference between import java.util.Date and java.util.* ?
The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-time performance.

Q) What is static import?
Read it here.

Q) Garbage collection in java?
Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no references to an object exist for a long time is called garbage collection. The whole purpose of Garbage collection is efficient memory management.

Q) Use of finalize() method in java?
finalize() method is used to free the allocated resource.

Q) How many times does the garbage collector calls the finalize() method for an object?
The garbage collector calls the finalize() method Only once for an object.

Q) What are two different ways to call garbage collector?
System.gc() OR Runtime.getRuntime().gc().

Q) Can the Garbage Collection be forced by any means?
No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.

Exception handling Interview Questions

Q) What is an exception?
Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by programmer.

Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?
Java.lang.Exception
This package contains definitions for Exceptions.

Q) What are the types of exceptions?
There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.

Q) What is the difference between Error and Exception?
Error: Mostly a system issue. It always occur at run time and must be resolved in order to proceed further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.

Q) What is throw keyword in exception handling?
The throw keyword is used for throwing user defined or pre-defined exception.

Q) What is throws keyword?
If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method’s signature.

Q) Difference between throw and throws in Java
Read the difference here: Java – throw vs throws.

Q) Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.

Q) What is finally block?
Finally block is a block of code that always executes, whether an exception occurs or not. Finally block follows try block or try-catch block.

Q) ClassNotFoundException vs NoClassDefFoundError?
1) ClassNotFoundException occurs when loader could not find the required class in class path.
2) NoClassDefFoundError occurs when class is loaded in classpath, but one or more of the class which are required by other class, are removed or failed to load by compiler.

Q) Can we have a try block without catch or finally block?
No, we cannot have a try block without catch or finally block. We must have either one of them or both.

Q) Can we have multiple catch blocks following a single try block?
Yes we can have multiple catch blocks in order to handle more than one exception.

Q) Is it possible to have finally block without catch block?
Yes, we can have try block followed by finally block without even using catch blocks in between.

When a finally block does not get executed?
The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.

Q) Can we handle more than one exception in a single catch block?
Yes we can do that using if-else statement but it is not considered as a good practice. We should have one catch block for one exception.

Q) What is a Java Bean?
A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.

Java Multithreading Interview Questions

Q) What is Multithreading?
It is a process of executing two or more part of a program simultaneously. Each of these parts is known as threads. In short the process of executing multiple threads simultaneously is known as multithreading.

Q) What is the main purpose of having multithread environment?
Maximizing CPU usage and reducing CPU idle time

Q) What are the main differences between Process and thread? Explain in brief.
1)  One process can have multiple threads. A thread is a smaller part of a process.
2)  Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and shares it with other threads.
3) Threads of same process can communicate with each other using keyword like wait and notify etc. This process is known as inter process communication.

Q) How can we create a thread in java?
There are following two ways of creating a thread:
1)  By Implementing Runnable interface.
2)  By Extending Thread class.

Q) Explain yield and sleep?
yield() – It causes the currently executing thread object to temporarily pause and allow other threads to execute.

sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock.

Q) What is the difference between sleep() and wait()?
sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock

wait() – It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

Q) What is a daemon thread?
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

Q) What does join( ) method do?
if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.

Q) Preemptive scheduling vs. time slicing?
1) The preemptive scheduling is prioritized. The highest priority process should always be the process that is currently utilized.
2) Time slicing means task executes for a defined slice/ period of time and then enter in the pool of ready state. The scheduler then determines which task execute next based on priority or other factor.

Q) Can we call run() method of a Thread class?
Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, you should call Thread.start() method to start it.

Q) What is Starvation?
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

Q) What is deadlock?
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

Serialization interview Questions

Q: What is Serialization and de-serialization?
Serialization is a process of converting an object and its attributes to the stream of bytes. De-serialization is recreating the object from stream of bytes; it is just a reverse process of serialization. To know more about serialization with example program, refer this article.

Q) Do we need to implement any method of Serializable interface to make an object serializable?
No. In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.

Q) What is a transient variable?
1) transient variables are not included in the process of serialization.
2) They are not the part of the object’s serialized state.
3) Variables which we don’t want to include in serialization are declared as transient.

String interview questions

Q) A string class is immutable or mutable?
String class is immutable that’s the reason once its object gets created, it cannot be changed further.

Q) Difference between StringBuffer and StringBuilder class?
1) StringBuffer is thread-safe but StringBuilder is not thread safe.
2) StringBuilder is faster than StringBuffer.
3) StringBuffer is synchronized whereas StringBuilder is not synchronized.

Q) What is toString() method in Java?
The toString() method returns the string representation of any object.

Java collections interview questions

Q) What is List?
Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.

Q) What is Map?
Map interface maps unique keys to values. A key is an object that we use to retrieve a value later. A map cannot contain duplicate keys: Each key can map to at most one value.

Q) What is Set?
A Set is a Collection that cannot contain duplicate elements.

Q) Why ArrayList is better than Arrays?
Array can hold fixed number of elements. ArrayList can grow dynamically.

Q) What is the difference between ArrayList and LinkedList?
1) LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
2) LinkedList is preferred for add and update operations while ArrayList is a good choice for search operations. Read more here.

Q) For addition and deletion. Which one is most preferred: ArrayList or LinkedList?
LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.

Q) For searches. Which one is most preferred: ArrayList or LinkedList?
ArrayList. Searching an element is faster in ArrayList compared to LinkedList.

Q) What is the difference between ArrayList and Vector?
1) Vector is synchronized while ArrayList is not synchronized.
2) By default, Vector doubles the size of its array when it is re-sized internally. ArrayList increases by half of its size when it is re-sized. More details.

Q) What is the difference between Iterator and ListIterator?
Following are the major differences between them:
1) Iterator can be used for traversing Set, List and Map. ListIterator can only be used for traversing a List.
2) We can traverse only in forward direction using Iterator. ListIterator can be used for traversing in both the directions(forward and backward). Read more at: ListIterator vs Iterator.

Q) Difference between TreeSet and SortedSet?
TreeSet implements SortedSet interface.

Q) What is the difference between HashMap and Hashtable?
1) Hashtable is synchronized. HashMap is not synchronized.
2) Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. Read more here.

Q) What is the difference between Iterator and Enumeration?
1) Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. We cannot add/remove elements from a collection when using enumerator.
2) Iterator has improved method names.
Enumeration.hasMoreElement() -> Iterator.hasNext()
Enumeration.nextElement() -> Iterator.next().

Applet Interview Questions

Q) How do you do file I/O from an applet?
Unsigned applets are simply not allowed to read or write files on the local file system .

Unsigned applets can, however, read (but not write) non-class files bundled with your applet on the server, called resource files

Q) What is container ?
A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog

Learning)

  1. Flow Layout is default for panel.
  2. Border Layout is default for Frames.

Q) On Windows, generally frames are invisible, how to make it visible. ?

Frame f = new Frame();
f.setSize(300,200);  //height and width
f.setVisible(true) ;  // Frames appears

Q) JFC – Java Foundation Class
Swing
AWT
Java2D
Drag and Drop
Accessibility

Learning) Listeners and Methods?
ActionListerner – actionPerformed();
ItemListerner – itemStateChanged();
TextListener – textValueChanged();
FocusListener – focusLost(); & FocusGained();

WindowListener – windowActified(); windowDEactified(); windowIconified(); windowDeiconified(); windowClosed(); windowClosing(); windowOpened();

MouseMotionListener – mouseDragged(); & mouseMoved();

MouseListener – mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClicked();

Learnings)
parseInt – to convert string to int.
getBytes – string to byte array

Q) Applet Life cycle?
Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy().

Q) showStatus() ?–
To display the message at the bottom of the browser when applet is started.

Q) What is the Event handling?
Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event Handling.

Q) What is Adapter class?
Adapter class is an abstract class.

Advantage of adapter: To perform any window listener, we need to include all the methods used by the window listener whether we use those methods are not in our class like Interfaces whereas with adapter class, its sufficient to include only the methods required to override. Straight opposite to Interface.

Further readings:
If you have finished reading above interview questions then you can go through the below tutorials to sharpen your knowledge in java. We will keep adding new question and answers to the above list.

1) Java Collection tutorial
2) Core Java concepts
3) OOPs concepts
4) Java Multithreading
5) String class and its methods
6) Java Exception handling

from:http://beginnersbook.com/2013/05/java-interview-questions/