Good about Java:

friendly syntax, memory management[GC can collect unreferenced memory resources], object-oriented features, portability.

Stack

Stores method invocations, local variables(include object reference, but the object itself is still stored in heap).

If you look at the stack trace, the top method is the one being called, and once it is finished, it will be removed out of the stack.

Heap

Stores all objects(include instance variables in the class).

.hashcode() returns the memory address of the object, so no same hashcode for two objects.

But when the Class is value object, you could override .hashcode() and .equals().

Constructor

Default parameterless constructor: only generated by compiler when there is no your constructor.

Parent constructor: if parent class has default constructor, compiler will automatically call it without .super(). But if not, or you want to call the parent constructor with parameters, you need to call .super() explicitly.

Overloaded constructor: use .this(...) at the first line.

File I/O

There are two streams: Character stream & Binary stream

Character stream: to read/write human readable files, like .txt .xml .html

Class: FileReader/Writer[extends InputStreamReader, 缺点:使用系统默认字符字节编码方式], more advanced: BufferedReader/Writer

Binary stream: to read/write machine readable files, like .exe .class .obj

Class: FileInput/OutputStream, more advanced for Object: ObjectInput/OutpoutStream(.writeObject() method).

FileInputStream是最基本的,只能读出来Byte,而Wrapper class DataInputStream高级一些,可以读出来各种primitive types。ObjectInputStream另有readObject()。如果你想读出来String, 那么使用InputStreamReader[优点:可以指定字符字节编码方式].InputStreamReader (and its father Reader) are used specifically to deal with characters (so strings) so they handle charset encodings (utf8, iso-8859-1, and so on) gracefully.

Example:

// 读取字节转换成字符
String charset = "US-ASCII";
FileInputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream, charset);
StringBuffer buffer = new StringBuffer();
char[] buf = new char[64];
int count = 0;
try {
while ((count = reader.read(buf)) != -1) {
buffer.append(buffer, 0, count);
}
} finally {
reader.close();
}

读写file要注意的: new FileReader(filename)会throw FileNotFoundException(extends IOException),bufferedReader.readLine()会throw IOException,最后别忘记bufferedReader.close()。读写file更好的方法是用InputStreamReader(new FileInputStream(filename)),因为FileReader does not allow you to specify an encoding and instead uses the plaform default encoding, which makes it pretty much useless as using it will result in corrupted data when the code is run on systems with different platform default encodings.

Immutable Class

Instance could not be modified. 这就保证了当前线程用到的immutable object不会被其它线程修改。

How to: private final fields, final class, no setter methods, ensure exlusive access to mutable components.

String

StringBuilder不是thread-safe的,而StringBuffer由于有synchronized methods所以是thread-safe的。

ClassLoader

JVM有Bootstrap(核心类库), Extensions(扩展类库), System Class Loaders,App classloader(CLASSPATH类),会load很多classes before loading包含main()的class。

程序的开始是main(String[] args), 由此开始由Class loader来load用到的class。

一个classloader只能load同一个class一次,而同一个class可以由不同的classloaders来load。

software library is a collection of related object code. In the Java language, libraries are typically packaged in JAR files. Libraries can contain objects of different types. The most important type of object contained in a Jar file is a Java class. A class can be thought of as a named unit of code. The class loader is responsible for locating libraries, reading their contents, and loading the classes contained within the libraries. This loading is typically done "on demand", in that it does not occur until the class is actually used by the program. A class with a given name can only be loaded once by a given classloader.

Even building a JAR file from the class files doesn't change this -- the JAR is just a container for the class files.

The initial set of class loads are all triggered by the attempt to load the 起始class. These are the core classes that are used by every Java program, no matter how small. 然后开始load 当前class用到的class, recursively.

A lot happens inside the JVM when a class is loaded and initialized, including decoding the binary class format, checking compatibility with other classes, verifying the sequence of bytecode operations, and finally constructing a java.lang.Class instance to represent the new class.

Sockets

In UDP, as you have read above, every time you send a datagram, you have to send the local descriptor and the socket address of the receiving socket along with it. Since TCP is a connection-oriented protocol, on the other hand, a connection must be established before communications between the pair of sockets start. So there is a connection setup time in TCP.

Client:

Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}

Server:

ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Socket clientSocket = null;
try {
serviceSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}

Input at Client side:

DataInputStream input;
try {
input = new DataInputStream(MyClient.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}

Input at Server side:

DataInputStream input;
try {
input = new DataInputStream(serviceSocket.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}

Output at Client side:

PrintStream output;
try {
output = new PrintStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}

Passing parameter

Java is always passing by value. Value means copy of primitive variable, or copy of object reference[pointing to the same object].

So the original variable is not changed, in the method there will be a copy, but if you set the object, it will change the object content.

Why arguments passed to an anonymous inner class have to be final?

如果你pass local variables to anonymous class, 那么当当前method退出的时候这些local var会被stack清除,而你的anonymous class object如果再想access这些fields就会报错。所以,如果你把这些local var定义为final,那么JVM compiler就把它们变成了constants,之后再access这些fields就不会有问题。

 Boxing & Unboxing

Why do we need wrappers for primitive types?

So that a null value is possible, to include in a collection...

Boxing: auto from primitive to Wrapper class. Unboxing: vice versa, but can throw NullPointerException, if Integer i = null; int x = i;

 Public methods of java.land.Object class

.toString(), .hashCode(), .equals(), .clone(), .wait(), .notify(), .notifyAll(), .getClass()

What problems can be encountered when only overriding .equals() and not .hashcode()?

x.equals(y) does not mean they have same hashcode[default implementation], then it is not possible to use this type as a key in hashmap: because hashmap will first call .hashcode() and then .equals() when determining if the key is present in the map.

所以实际中你override了.equals()以后,一定要override .hashcode(),用同一套fields来calculate both methods.

[Java Basics] Stack, Heap, Constructor, I/O, Immutable, ClassLoader的更多相关文章

  1. 如何给女朋友讲明白:Java 中 Stack(栈) 与 Heap(堆)

    背景 Java 中 Stack(栈) 与 Heap(堆) 是面试中被经常问到的一个话题. 有没有对 Java 中 Stack(栈) 与 Heap(堆) 烂熟于心的童鞋,请举手!!!(怎么没人举手-) ...

  2. 认识Java Core和Heap Dump

    什么是Java Core和Heap Dump Java程序运行时,有时会产生Java Core及Heap Dump文件,它一般发生于Java程序遇到致命问题的情况下. 发生致命问题后,Java进程有时 ...

  3. java集合类——Stack类

    查看java的API文档,Stack继承Vector类. 栈的特点是后进先出. API中Stack自身的方法不多,基本跟栈的特点有关. import java.util.Stack; public c ...

  4. java.util.Stack类中 empty() 和 isEmpty() 方法的作用

    最近在学习算法和数据结构,用到Java里的Stack类,但程序运行结果一直和我预料的不一样,网上也没查清楚,最后查了API,才搞明白. java.util.Stack继承类 java.util.Vec ...

  5. Java数据类型Stack栈、Queue队列、数组队列和循环队列的比较

    判断括号是否匹配:调用java本身 import java.util.Stack; public class Solution { public boolean isValid(String s){ ...

  6. java.util.Stack类中的peek()方法

    java.util.stack类中常用的几个方法:isEmpty(),add(),remove(),contains()等各种方法都不难,但需要注意的是peek()这个方法. peek()查看栈顶的对 ...

  7. java之Stack详细介绍

    1  Stack介绍 Stack简介 Stack是栈.它的特性是:先进后出(FILO, First In Last Out). java工具包中的Stack是继承于Vector(矢量队列)的,由于Ve ...

  8. java.util.Stack(栈)的简单使用

    import java.util.Stack; import org.junit.Before; import org.junit.Test; /** * Stack(栈)继承了Vector类,底层实 ...

  9. java集合类——Stack栈类与Queue队列

    Stack继承Vector类,它通过五个操作对类 Vector 进行了扩展. 栈是 后进先出的. 栈提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法.测试堆栈是否为空的 em ...

随机推荐

  1. nodeschool.io 5

    ~~ FILTERED LS ~~ Create a program that prints a list of files in a given directory,filtered by the ...

  2. 《javascript高级程序设计》第三章 Language Basics

    3.1 语法syntax 3.1.1 区分大小写case-sensitivity 3.1.2 标识符identifiers 3.1.3 注释comments 3.1.4 严格模式strict mode ...

  3. 关于位域如何节省内存(C++)

    位域:  最先使用在c语言中后来C++继承了这一优良的特点. 举个栗子:     int  -->  4字节   2^32位 ,如果我们只需要其表达一个0~16的数字, 使用一个int就显得稍稍 ...

  4. java多线程下如何调用一个共同的内存单元(调用同一个对象)

    /* * 关于线程下共享相同的内存单元(包括代码与数据) * ,并利用这些共享单元来实现数据交换,实时通信与必要的同步操作. * 对于Thread(Runnable target)构造方法创建的线程, ...

  5. IE5,IE6,IE7,IE8的css兼容性列表[转自MSDN]

    CSS 2.1:   IE 5.0 IE 5.5 IE 6.0 IE 7.0 IE8 Beta 1 IE8 Beta 2 IE 8.0 @charset No Yes Yes Yes Yes Yes ...

  6. CRM创建物料FM2

    这是在佛山好帮手时受启发而研究出来的,创建物料,带单位,类型组 经测试....算了,不说了,有什么限制自己测去...今天心情不好... FUNCTION ZLY_CREATE_PRODUCT_UNIT ...

  7. oracle优化原则(二)

    SQL优化原则 二.SQL语句编写注意问题 www.2cto.com 下面就某些SQL语句的where子句编写中需要注意的问题作详细介绍.在这些where子句中,即使某些列存在索引,但是由于编写了劣质 ...

  8. RRDTool 存储原理简介——基于时间序列的环型数据库

    转自:http://www.jianshu.com/p/b925b1584ab2 RRDTool是一套监测工具,可用于存储和展示被监测对象随时间的变化情况.比如,我们在 Windows 电脑上常见的内 ...

  9. VSS Plugin配置FAQ(翻译)[转]

    前言(译者) 就个人的成长历程来说,刚参加工作用的是 CVS ,前前后后有接近三年的使用体验,从今年开始使用 SVN .总的来说我更喜欢 SVN ,用起来的确很方便,例如在本地源代码文件中加一个空格然 ...

  10. String.resize()

    void resize (size_t n); void resize (size_t n, char c); 测试代码: // resizing string #include <iostre ...