Tag Archives: java

CPU 高负载排查实践

前言

前几日早上打开邮箱收到一封监控报警邮件:某某 ip 服务器 CPU 负载较高,请研发尽快排查解决,发送时间正好是凌晨。

其实早在去年我也处理过类似的问题,并记录下来:《一次生产 CPU 100% 排查优化实践》

不过本次问题产生的原因却和上次不太一样,大家可以接着往下看。

问题分析

收到邮件后我马上登陆那台服务器,看了下案发现场还在(负载依然很高)。

于是我便利用这类问题的排查套路定位一遍。


首先利用 top -c 将系统资源使用情况实时显示出来 (-c 参数可以完整显示命令)。

接着输入大写 P 将应用按照 CPU 使用率排序,第一个就是使用率最高的程序。

果不其然就是我们的一个 Java 应用。

这个应用简单来说就是定时跑一些报表使的,每天凌晨会触发任务调度,正常情况下几个小时就会运行完毕。


常规操作第二步自然是得知道这个应用中最耗 CPU 的线程到底再干嘛。

利用 top -Hp pid 然后输入 P 依然可以按照 CPU 使用率将线程排序。

这时我们只需要记住线程的 ID 将其转换为 16 进制存储起来,通过 jstack pid >pid.log生成日志文件,利用刚才保存的 16 进制进程 ID 去这个线程快照中搜索即可知道消耗 CPU 的线程在干啥了。

如果你嫌麻烦,我也强烈推荐阿里开源的问题定位神器 arthas 来定位问题。

比如上述操作便可精简为一个命令 thread -n 3 即可将最忙碌的三个线程快照打印出来,非常高效。

更多关于 arthas 使用教程请参考官方文档

由于之前忘记截图了,这里我直接得出结论吧:

最忙绿的线程是一个 GC 线程,也就意味着它在忙着做垃圾回收。

GC 查看

排查到这里,有经验的老司机一定会想到:多半是应用内存使用有问题导致的。

于是我通过 jstat -gcutil pid 200 50 将内存使用、gc 回收状况打印出来(每隔 200ms 打印 50次)。

从图中可以得到以下几个信息:

  • Eden 区和 old 区都快占满了,可见内存回收是有问题的。
  • fgc 回收频次很高,10s 之内发生了 8 次回收((866493-866485)/ (200 *5))。
  • 持续的时间较长,fgc 已经发生了 8W 多次。

内存分析

既然是初步定位是内存问题,所以还是得拿一份内存快照分析才能最终定位到问题。

通过命令 jmap -dump:live,format=b,file=dump.hprof pid 可以导出一份快照文件。

这时就得借助 MAT 这类的分析工具出马了。

问题定位

通过这张图其实很明显可以看出,在内存中存在一个非常大的字符串,而这个字符串正好是被这个定时任务的线程引用着。

大概算了一下这个字符串所占的内存为 258m 左右,就一个字符串来说已经是非常大的对象了。

那这个字符串是咋产生的呢?

其实看上图中的引用关系及字符串的内容不难看出这是一个 insert 的 SQL 语句。

这时不得不赞叹 MAT 这个工具,他还能帮你预测出这个内存快照可能出现问题地方同时给出线程快照。

最终通过这个线程快照找到了具体的业务代码:

他调用一个写入数据库的方法,而这个方法会拼接一个 insert 语句,其中的 values 是循环拼接生成,大概如下:

1
2
3
4
5
6
7
<insert id=“insert” parameterType=“java.util.List”>
insert into xx (files)
values
<foreach collection=“list” item=“item” separator=“,”>
xxx
</foreach>
</insert>

所以一旦这个 list 非常大时,这个拼接的 SQL 语句也会很长。

通过刚才的内存分析其实可以看出这个 List 也是非常大的,也就导致了最终的这个 insert 语句占用的内存巨大。

优化策略

既然找到问题原因那就好解决了,有两个方向:

  • 控制源头 List 的大小,这个 List 也是从某张表中获取的数据,可以分页获取;这样后续的 insert 语句就会减小。
  • 控制批量写入数据的大小,其实本质还是要把这个拼接的 SQL 长度降下来。
  • 整个的写入效率需要重新评估。

总结

本次问题从分析到解决花的时间并不长,也还比较典型,其中的过程再总结一下:

  • 首先定位消耗 CPU 进程。
  • 再定位消耗 CPU 的具体线程。
  • 内存问题 dump 出快照进行分析。
  • 得出结论,调整代码,测试结果。

最后愿大家都别接到生产告警。

from:https://crossoverjie.top/2019/06/18/troubleshoot/cpu-percent-100-02/

Java Versions, Features and History

his article gives you a highlight of important features added in every major Java release. Check this article to know about Java history, I am sure you will find it interesting.

Java SE 8

Java 8 was released on 18 March 2014. The code name culture is dropped with Java 8 and so no official code name going forward from Java 8.

New features in Java SE 8

  • Lambda Expressions
  • Pipelines and Streams
  • Date and Time API
  • Default Methods
  • Type Annotations
  • Nashhorn JavaScript Engine
  • Concurrent Accumulators
  • Parallel operations
  • PermGen Error Removed
  • TLS SNI

Java Version SE 7

Code named Dolphin and released on July 28, 2011.

New features in Java SE 7

  • Strings in switch Statement
  • Type Inference for Generic Instance Creation
  • Multiple Exception Handling
  • Support for Dynamic Languages
  • Try with Resources
  • Java nio Package
  • Binary Literals, underscore in literals
  • Diamond Syntax
  • Automatic null Handling

Java Version SE 6

Code named Mustang and released on December 11, 2006.

New features in Java SE 6

  • Scripting Language Support
  • JDBC 4.0 API
  • Java Compiler API
  • Pluggable Annotations
  • Native PKI, Java GSS, Kerberos and LDAP support.
  • Integrated Web Services.
  • Lot more enhancements.

J2SE Version 5.0

Code named Tiger and released on September 30, 2004.

New features in J2SE 5.0

  • Generics
  • Enhanced for Loop
  • Autoboxing/Unboxing
  • Typesafe Enums
  • Varargs
  • Static Import
  • Metadata (Annotations)
  • Instrumentation

J2SE Version 1.4

Code named Merlin and released on February 6, 2002 (first release under JCP).

New features in J2SE 1.4

  • XML Processing
  • Java Print Service
  • Logging API
  • Java Web Start
  • JDBC 3.0 API
  • Assertions
  • Preferences API
  • Chained Exception
  • IPv6 Support
  • Regular Expressions
  • Image I/O API

J2SE Version 1.3

Code named Kestrel and released on May 8, 2000.

New features in J2SE 1.3

  • Java Sound
  • Jar Indexing
  • A huge list of enhancements in almost all the java area.

J2SE Version 1.2

Code named Playground and released on December 8, 1998.

New features in J2SE 1.2

  • Collections framework.
  • Java String memory map for constants.
  • Just In Time (JIT) compiler.
  • Jar Signer for signing Java ARchive (JAR) files.
  • Policy Tool for granting access to system resources.
  • Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries.
  • Java Plug-in
  • Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
  • Audio support in Applets.

JDK Version 1.1

Released on February 19, 1997

New features in JDK 1.1

  • JDBC (Java Database Connectivity)
  • Inner Classes
  • Java Beans
  • RMI (Remote Method Invocation)
  • Reflection (introspection only)

JDK Version 1.0

Codenamed Oak and released on January 23, 1996.

Wishing you a happy new year!

This Core Java tutorial was added on 01/01/2012.

from:http://javapapers.com/core-java/java-features-and-history/

中文版本:http://www.importnew.com/844.html

 

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/