```
String str = "Foo Bar";
for(int i=0;i<str.length();i++)
System.out.println(str.charAt(i));
```
For long strings (more than 512 chars, approximately), the fastest way to inspect the string is to use reflection to access the backing char[] of the String, something like this:
String data = "a really long string";Field field = String.class.getDeclaredField("value"); field.setAccessible(true);char[] chars = (char[]) field.get(data);for (int i = 0, n = chars.length; i < n; i++) System.out.println(chars[i]);
By using the above approach, you avoid entirely the need to create a new char[] and also you don't need to pay the cost of an extra method call to charAt() in each iteration. Take a look at this post, the answer contains detailed benchmarks.
https://habrahabr.ru/post/314386/
http://www.edumobile.org/java/30-java-programming-tips-and-best-practices/
https://www.youtube.com/watch?v=Vlb_Is-rRTQ
http://fahdshariff.blogspot.com/2011/08/changing-java-library-path-at-runtime.html
https://howtotrainyourjava.com/2014/09/28/how-to-slim-down-your-java/
https://dzone.com/articles/the-java-8-api-design-principles?oid=18544920 API design
https://www.toptal.com/java#hiring-guide
https://habrahabr.ru/company/golovachcourses/blog/228603/
Weak Soft Phantom references
https://habrahabr.ru/post/169883/
http://www.baeldung.com/java-weakhashmap
http://www.onlinetutorialspoint.com/java/reference-types-in-java-strong-soft-weak-phantom.html
https://elliot.land/strong-vs-weak-references
Memory leaks are possible in Java - see WeakReference, WeakHashMap; SoftReference, PhantomReference, ReferenceQueue
http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
http://www.toptal.com/java/hunting-memory-leaks-in-java
https://www.amazon.com/Functional-Programming-Java-functional-techniques/dp/1617292737/
https://habrahabr.ru/company/jugru/blog/317628/ Video from russian conf
Immutability in Java
http://programmergate.com/create-immutable-class-java/
https://www.youtube.com/watch?v=-Tydziij7s4
https://www.youtube.com/watch?v=pUXeNAeyY34&index=2&list=PLX8CzqL3ArzUY6rQAQTwI_jKvqJxrRrP_ Immutable collection
http://www.allitebooks.com/programming/java e-books
Multiple threads run concurrently, by using separate processors or different time slices on the same processor.
https://dzone.com/articles/bootique-a-minimally-opinionated-platform-for-mode
https://habrahabr.ru/company/jugru/blog/310088/
http://stackoverflow.com/questions/258120/what-is-the-memory-consumption-of-an-object-in-java
http://stackoverflow.com/questions/31206851/how-much-memory-does-a-string-use-in-java-8
https://intelligentjava.wordpress.com/
http://vanillajava.blogspot.com/
https://www.javacodegeeks.com/2015/09/advanced-java.html
http://www.techbeamers.com/java-coding-questions-assess-programming-skills/
http://javaonfly.blogspot.in/2016/08/java-references-and-garbage-collection.html
http://www.slideshare.net/elizarov/j-point-2014-java-memory-model
http://www.slideshare.net/elizarov/ss-61415341 multithreading
https://blog.jooq.org/2015/02/05/top-10-easy-performance-optimisations-in-java/
https://plus.google.com/110650159101065784429/posts
https://www.youtube.com/watch?v=rEs6UdWByKw
http://docs.oracle.com/javase/specs/#31069 Specs
https://habrahabr.ru/company/jugru/blog/308112/
https://zeroturnaround.com/rebellabs/java-tools-and-technologies-landscape-2016/
https://www.lektorium.tv/lecture/27454
https://greppage.com/evidanary/16 Cheat sheet
https://www.youtube.com/watch?v=XgiXKPEILoc memory model
http://www.instanceofjava.com/2014/12/jvm-architecture.html
http://objectlayout.org/ https://www.infoq.com/presentations/objectlayout-c-struct
https://dzone.com/articles/generic-object-pool-in-java
The addition of Generics to the language has not been without its problems. A particularly thorny issue with Java Generics is that of type erasure.
As an example, consider the following code snippet:
List<String> a = new ArrayList<String>(); List<Integer> b = new ArrayList<Integer>(); return a.getClass() == b.getClass(); // returns true??!!
This should presumably return false since a and b are different class types (i.e., ArrayList<String> vs. ArrayList<Integer>), yet it returns true. Why?
The culprit here is type erasure. Once the above code passes all Java compiler validation, the compiler erases the String and Integer types in the above example, to maintain backward compatibility with older JDKs. The above code is therefore converted to the following by the Java compiler:
List a = new ArrayList(); List b = new ArrayList(); return a.getClass() == b.getClass(); // returns true !!!
And thus, in the compiled code, a and b are both simply untyped ArrayList objects, and the fact that one
StringUtils from commons-lang.
FileUtils from commons-io. (Or IOUtils if you're dealing with I/O streams instead)
Strings
http://habrahabr.ru/post/260767/ StringBuffer StringBuilder
http://habrahabr.ru/post/260773/ regular expression
http://habrahabr.ru/company/mailru/blog/259125/
String is immutable while StringBuffer is mutable.
StringBuffer is mutable, good in terms of memory usage but it is slow:
all its public methods are synchronized which makes it thread-safe but same time slow.
StringBuilder which is a copy of StringBuffer but without synchronization.
static void modify (String str){
str = str + " modified";
System.out.println("INSIDE "+ str); // prints "A modified"
}
public static void main(String[] args) {
String mystr="A";
modify(mystr);
System.out.println(mystr); // prints "A"
}
Java command line arguments
public static void main( String[] args ) {
if( args.length > 0 && args[0].equals( "a" ) ) {
// first argument is "a"
} else {
...
}
}
Exceptions
On one hand, defining a method as throwing exceptions is a good way to communicate to users about possible dangers and it is obviously a huge improvement over using a global variable containing the error code. On the other hand, throwing exceptions distort the normal flow of the program and wrapping them in a try blocks becomes mundane very fast. Defining all possible errors as RuntimeExceptions is hardly a solution, because it solves the latter but not the former.
https://www.reddit.com/r/programming/comments/4mry4c/what_java_devs_do_in_checked_exceptions_catch/
https://github.com/jhalterman/failsafe
https://www.reddit.com/r/java/comments/4n0l8r/what_should_i_cover_in_a_modern_java_presentation/
https://engineering.vena.io/2016/05/09/transpose-tree/
https://news.ycombinator.com/item?id=11830329
http://www.ibm.com/developerworks/java/library/j-codetoheap/index.html
http://java67.blogspot.com/2012/09/top-10-tricky-java-interview-questions-answers.html
https://www.ibm.com/developerworks/java/library/j-jtp1029/index.html
http://data-structure-learning.blogspot.com/p/main-page.html
https://habrahabr.ru/company/luxoft/blog/278313/
https://habrahabr.ru/post/278087/
https://github.com/bytedeco/javacpp https://news.ycombinator.com/item?id=11094335
http://www.class-visualizer.net/overview.html
http://algs4.cs.princeton.edu/code/
http://vanillajava.blogspot.com/
http://virtualjug.com/getting-cc-performance-out-of-java/
http://farenda.com/java-tutorials/
http://jodd.org/ light libraries
https://www.reddit.com/r/java/comments/4n0l8r/what_should_i_cover_in_a_modern_java_presentation/
https://habrahabr.ru/company/luxoft/blog/280784/ awesome java
http://habrahabr.ru/company/golovachcourses/blog/215275/
http://habrahabr.ru/company/spbau/blog/269147/
double and long in java aren’t’ thread safe.
Add volatile keyword before them to make sure atomic read/write, thread safety.
https://habrahabr.ru/company/rambler-co/blog/277273/
https://habrahabr.ru/company/jugru/blog/275885/
http://web.mit.edu/6.005/www/fa15/classes/25-map-filter-reduce/
Number of processors:
public class proc {
public static void main(String[] args) {
int availableProcessors = Runtime.getRuntime().availableProcessors();
System.out.println("Total number of system processors: " + availableProcessors);
}
}
Executing shell command from java
shell.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class shell {
public static void main (String[] args) {
System.out.println(args[0]);
String result = execute(args[0]);
System.out.println(result);
}
public static String execute(String command) {
StringBuilder sb = new StringBuilder();
String[] commands = new String[] { "/bin/sh", "-c", command };
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader input = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader( proc.getErrorStream()));
String s = null;
while ((s = input.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
while ((s = stdError.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
Using bitmask in Java http://habrahabr.ru/post/270461/
javap -private Classname shows methods of compiled class
find . -name "*.java" -print | xargs javac -d classes/
expands to
javac src/hello/App.java -d classes/
package hello; public class App {public static void main(String[] args) { System.out.println("Hello world!"); } }
http://brianoneill.blogspot.ch/2015/10/diagnosing-memory-leaks-in-java.html
http://grepcode.com/project/repository.grepcode.com/java/root/jdk/openjdk/ Java source
https://www.youtube.com/user/JUGRuVideo
http://xpinjection.com/resources/
http://jug.ru/meetings/829 Structures
https://www.youtube.com/watch?v=Svc0WtfV63k&feature=youtu.be
https://www.youtube.com/watch?v=Svc0WtfV63k&feature=youtu.be&t=2450
https://www.youtube.com/watch?v=uZfK-9ixxec
JDK examples
http://www.oracle.com/technetwork/java/javase/downloads/jdk-netbeans-jsp-142931.html
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
http://www.ibm.com/developerworks/java/
http://www.javacodegeeks.com/courses/
http://www.javacodegeeks.com/2015/09/advanced-java.html
http://www.javacodegeeks.com/2014/04/java-interview-questions-and-answers.html
https://www.youtube.com/watch?v=r2BAVRRB-1I
import java.util.*; public class Sort { public static void main(String[] args) { List<String> list = Arrays.asList(args); Collections.sort(list); System.out.println(list); } }
Java 5 brought new concurrency library reconciled underjava.util.concurrent package.
Java 6 delivered scripting support (javax.script package) and the Java compiler API (under javax.tools package).
Java 7 brought a lot of improvements intojava.util.concurrent, introduced new I/O library under java.nio.file package and dynamic languages support with java.lang.invoke package.
Java 8 delivered a long-awaited date/time API hosted under java.time package.
Since the Java 5 release, the methods can have variable list of arguments of the same type (called varargs) using a special syntax, for example:
public void find( String ... elements ) { // Some implementation here }
http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
public class EagerSingleton { private static final EagerSingleton instance = new EagerSingleton(); private EagerSingleton() { } public static EagerSingleton getInstance() { return instance; } }
public class LazySingleton { private static LazySingleton instance; private LazySingleton() { } public static synchronized LazySingleton getInstance() { if( instance == null ) { instance = new LazySingleton(); } return instance; } }
Java 5 (2004):
For-each loops (mostly obsolete again because of the Java 8 Streams API)
Java 7 (2011):
Java 8 (2014):
https://github.com/cxxr/better-java
http://avxhome.se/ebooks/programming_development/java/3680987.html
https://news.ycombinator.com/item?id=10245673
http://codeinventions.blogspot.com/2014/12/Most-Useful-websites-that-help-Java-developers.html
https://public.grokola.com/#grok/f23fb894-6533-4a74-9194-52f249db75f0
http://www.java2blog.com/2015/08/java-interview-programs.html
https://github.com/akullpp/awesome-java
http://java67.blogspot.sg/2015/03/top-40-core-java-interview-questions-answers-telephonic-round.html
http://avxhome.se/ebooks/programming_development/java/3499133.html
http://www.javapractices.com/home/HomeAction.do
http://javarevisited.blogspot.sg/
http://blog.paralleluniverse.co/2014/05/01/modern-java/
http://habrahabr.ru/post/266821/
Java FX
http://gluonhq.com/open-source/scene-builder/ JavaFX scene Builder
http://habrahabr.ru/post/265511/ JavaFX+SpringBoot
https://dzone.com/articles/core-java-interview-questions-0
https://dzone.com/articles/core-java-interview-questions-part-ii
https://dzone.com/articles/core-java-interview-questions
https://dzone.com/articles/core-java-interview-questions-1
https://dzone.com/articles/core-java-interview-questions-2
http://xquizzes.com/programming/Java/
http://c2.com/ppr/wiki/JavaIdioms/JavaIdioms.html
115 Java Interview Questions and Answers
69 Spring Interview Questions and Answers
Multithreading and Concurrency Interview Questions and Answers
40 Java Collections Interview Questions and Answers
http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
http://www.javacodegeeks.com/category/java/core-java/
you have a Java function:
public void f(Foo bar) { ... }
void f(Foo bar) { ... } void f(Foo& bar) { ... } void f(Foo* bar) { ... }
It's the last one. Java passes everything by value, but non-primitive objects in Java are actually pointers (which Java inaccurately calls references), and the pointer is passed by value.
Java is always pass-by-value. Unfortunately, they decided to call pointers references, thus confusing newbies. Because those references are passed by value.
It goes like this:
public static void main( String[] args ){ Dog aDog = new Dog("Max"); foo(aDog); if( aDog.getName().equals("Max") ){ //true System.out.println( "Java passes by value." ); }else if( aDog.getName().equals("Fifi") ){ System.out.println( "Java passes by reference." ); }}public static void foo(Dog d) { d.getName().equals("Max"); // true d = new Dog("Fifi"); d.getName().equals("Fifi"); // true}
In this example aDog.getName() will still return "Max". The value aDog within main is not overwritten in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.
reassigning Object parameters doesn't affect the argument, e.g.,
private void foo(Object bar) { bar = null;}public static void main(String[] args) { String baz = "Hah!"; foo(baz); System.out.println(baz);}
will print out "Hah!" instead of NULL. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.
public class Cat { String color; public static void main(String args[]){ Cat myBlackCat = new Cat("black"); System.out.println("cat is: " + myBlackCat.getColor()); colorMeCat(myBlackCat); System.out.println("outside of the method, my cat is: " + myBlackCat.getColor()); } public Cat(String color){ this.color = color;} public static void colorMeCat(Cat cat){ cat = new Cat("rainbow"); System.out.println("cat is: " + cat.getColor()); } public String getColor(){ return color;}
}
The idea of using predicates is simply to replace the hard-coded condition inside the if clause by a call to a predicate, which then becomes a parameter. This means you can write only one method, taking a predicate as a parameter, and you can still cover all your use-cases, and even already support use-cases you do not know yet:
Which is the equivalent C++ function?
Each particular predicate can be defined as a standalone class, if used at several places, or as an anonymous class:
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
final Customer customer = new Customer("BruceWaineCorp");
final Predicate<PurchaseOrder> condition = new Predicate<PurchaseOrder>() {
public boolean apply(PurchaseOrder order) {
return order.getCustomer().equals(customer);
}
};
public List<PurchaseOrder> listOrders(Predicate<PurchaseOrder> condition){
final List<PurchaseOrder> selection = new ArrayList<PurchaseOrder>();
for (PurchaseOrder order : orders) {
if (condition.apply(order)) {
selection.add(order);
}
}
return selection;
}
http://javadude.com/articles/passbyvalue.htm
http://avaxhm.com/ebooks/programming_development/java/3369454.html Interview Book
http://habrahabr.ru/company/mailru/blog/251365/
http://techblog.bozho.net/on-java-generics-and-erasure/ generics
http://shipilev.net/blog/2014/jmm-pragmatics/
http://www.toptal.com/java#hiring-guide
http://habrahabr.ru/company/golovachcourses/blog/222679/
http://habrahabr.ru/company/golovachcourses/blog/228603/
Введение в Акторы на основе Java/GPars, Часть I
1000+ часов видео по Java на русском
JSR 133 (Java Memory Model) FAQ
Программирование-по-Контракту в Java
Исключения в Java, Часть I (try-catch-finally)
Исключения в Java, Часть II (checked/unchecked)
http://blog.paralleluniverse.co/2014/05/01/modern-java/
http://blog.paralleluniverse.co/2014/05/08/modern-java-pt2/
http://blog.paralleluniverse.co/2014/05/15/modern-java-pt3/
Best Java Libs
https://java.zeef.com/chandra.sekhar
https://news.ycombinator.com/item?id=9278704
http://playingwithpointers.com/peeking-into-jmm.html
Book
https://leanpub.com/modernjava
http://www.javacodegeeks.com/2013/02/40-java-collections-interview-questions-and-answers.html
http://www.ibm.com/developerworks/java/library/j-ai-search/index.html
http://www.nerds-central.com/Search/Java1-6.html
http://leepoint.net/notes-java/index.html
http://habrahabr.ru/blogs/java/116578/
http://habrahabr.ru/blogs/java/132374/
http://habrahabr.ru/blogs/java/132500/ Memory leaks
http://java.sun.com/docs/books/tutorial/index.html
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
http://faq.javaranch.com/search?CategoryFaq - FAQs
http://www.infoq.com/presentations/brian-goetz-concurrent-parallel
http://www.javapractices.com/home/HomeAction.do
http://www.java2s.com/ http://www.java-tv.com/
http://kamilche.com/java/Java%20Notes%207.html
http://kamilche.com/java/Java%20Notes%2010.html
XML XPath: http://habrahabr.ru/blogs/java/128175/
http://download.oracle.com/javase/6/docs/technotes/tools/
http://javaperformancetuning.com/
http://users.livejournal.com/_winnie/257544.html
http://myjavatools.com/ Ivan Ghandi
Interfaces
All methods and variables declared inside Java Interfaces are implicitly public and abstract,
even if you don't use public or abstract keyword.
You can not define any concrete method in interface
interface SessionIDCreator extends Serializable, Cloneable{
String TYPE = "AUTOMATIC";
int createSessionId();
}
class SerialSessionIDCreator implements SessionIDCreator{
private int lastSessionId;
@Override
public int createSessionId() {
return lastSessionId++;
}
}
Design patterns
http://www.javacodegeeks.com/2015/09/java-design-patterns.html
https://springframework.guru/command-pattern/ Command Pattern
Singleton pattern
http://habrahabr.ru/blogs/java/129494/
http://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.html
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.
Singleton using Enum
package electro;
public enum YourSingleton {
INSTANCE;
public void doStuff(String stuff) {
System.out.println("Doing " + stuff);
}
}
Usage:
YourSingleton.INSTANCE.doStuff("some stuff");
Double checked locking:
public Singleton getInstance(){
if(_INSTANCE == null){
synchronized(Singleton.class){
//double checked locking - because second check of Singleton instance with lock
if(_INSTANCE == null){
_INSTANCE = new Singleton();
}
}
}
return _INSTANCE;
}
Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.
Visitor pattern
http://java-x.blogspot.com/2007/01/implementing-visitor-pattern-in-java.html
http://snehaprashant.blogspot.com/2009/01/visitor-pattern-in-java.html
Use the Visitor pattern in any of the following situations:
1) When many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations
2) When the classes defining the object structure rarely change, but you often want to define new operations over the structure. (If the object structureclasses change often, then it's probably better to define the operations in those classes.)
3) When an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes
public interface IVisitor<T> {
void visit(T item);
}
public class CollectionUtils {
public static<T> void applyVisitor(Collection<T> collection, IVisitor<T> visitor) {
for (T item : collection)
visitor.visit(item);
}
}
Usage of IVisitor:
public static void main(String[] args) {
CollectionUtils.applyVisitor(Arrays.asList(1, 2, 3, 4, 5), new IVisitor<Integer>() {
public void visit(Integer x) {
System.out.println(x);
}
});
}
Converting Object to Integer
http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
int bb = (Integer)Obj; // JDK 1.5++
if (obj instanceof Integer) {
int bb = ((Integer)obj).intValue(); // before JDK 1.5++
}
int i = Integer.parseInt(Obj.toString()); // not effective
int i = Integer.parseInt(Obj);
MIN,MAX values
System.out.println(Integer.MIN_VALUE); // -2**31 = 2147483647
System.out.println(Integer.MAX_VALUE); // 2**31 -1 = -2147483648
System.out.println(Long.MIN_VALUE); // -9223372036854775808
System.out.println(Long.MAX_VALUE); // 9223372036854775807
Maven
mvn clean package
https://habrahabr.ru/post/309222/
https://habrahabr.ru/post/77382/
https://habrahabr.ru/post/311108/
https://www.youtube.com/watch?v=6tnefehAmj0
https://www.reddit.com/r/java/comments/3yot3d/my_first_maven_plugin_whats_my_version_appreciate/ MAVEN
http://www.sonatype.com/books/mvnref-book/reference/public-book.html
http://www.ibm.com/developerworks/java/tutorials/j-mavenv2/index.html
http://www.ibm.com/developerworks/java/library/j-5things13/index.html
http://www.informit.com/guides/content.aspx?g=java&seqNum=513
JUnit
If there are multiple tests, then you have the option of initializing and cleaning up the environment before and between tests by implementing the following two methods: setUp() and tearDown(). In setUp() you initialize the environment and in teardown() you clean up the environment. Note that these methods are called between each test to ensure that there are no side effects between test cases; they are truly independent. The mechanism that JUnit employs to test actual values against expected values is a set of assert methods:
There are assertEquals() methods for each primitive type.
assertTrue() and assertFalse() test boolean values.
assertNull() and assertNotNull() test whether an object is null.
assertSame() and assertNotSame() test object equality.
In addition, a fail() method (that you can call anywhere in your test case) can immediately mark a test as failing.
hudson http://hudson-labs.org/
In general, only one outer class in any given file may have the public modifier and
its name must be the same name as the file name. public class = file name
classpath sourcepath
http://habrahabr.ru/blogs/java/125210/
http://www.sergiy.ca/how-to-compile-and-launch-java-code-from-command-line/
В качестве разделителя нескольких путей в classpath в Windows используется ';' , в Linux ':'
Instead setting CLASSPATH environment variable one can use the explicit -classpath or -cp options when running
java, javac, javap, etc
The CLASSPATH environment variable is only used by the java.exe command and even then only when used without any of the -cp, -classpath, -jar arguments.
javac -d bin -sourcepath src src/com/elharo/gui/MainFrame.java
ant http://code.google.com/appengine/docs/java/tools/ant.html
binary file processing serialization
view jar file: jar tf jar-file
Manifest file: META-INF/MANIFEST.MF
How to modify default manifest file
1) create a text file named Manifest.txt with the following contents:
Main-Class: MyPackage.MyClass
Warning: The text file must end with a new line or carriage return.
2) create a JAR file named MyJar.jar by entering the following command:
jar cfm MyJar.jar Manifest.txt MyPackage/*.class
This creates the JAR file with a manifest with the following contents:
Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)
Main-Class: MyPackage.MyClass
3) run the JAR file with the following command, the main method of MyClass executes:
java -jar MyJar.jar
in Java6 there is simple way to introduce entry point: jar cfe app.jar MyApp MyApp.class
if Main.class is in a package called foo the entry point can be specified in the following ways:
jar cfe Main.jar foo.Main foo/Main.class
Then need to reference classes in other JAR files from within a JAR file att the following line to Manifest file:
Class-Path: jar1-name jar2-name directory-name/jar3-name
java.lang.ClassNotFoundException
http://code.google.com/p/classjarsearch/
http://rickwagner.blogspot.com/2010/10/how-to-find-which-jar-class-is-in.html
Below $1 is the command line arg which is the pattern to look
f.sh:
for j in `find . -name '*.jar' -type f`; do
for c in `jar -tf $j | grep -i $1`; do
echo "$j : $c";
done;
done;
http://www.reddit.com/r/programming/comments/gtkil/find_java_classes_or_packages_contained_in_jar/
http://download.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html
http://javahowto.blogspot.com/2006/07/jdk-6-supports-in-classpath-but-be.html
http://www.ibm.com/developerworks/java/library/j-classpath-unix/
PACKAGE=com/yahoo/uda/fetl/abf1/splitter/mapred
DIRTEST=~/SVN_FETL/fetl/abf1_splitter/trunk/src/test/java/$PACKAGE
DIRMAIN=~/SVN_FETL/fetl/abf1_splitter/trunk/src/main/java/$PACKAGE
SPATH=~/SVN_FETL/fetl/abf1_splitter/trunk/src/test/java:~/SVN_FETL/fetl/abf1_splitter/trunk/src/main/java
CLS=~/CLASS
CPATH=.:/home/y/lib/junit.jar:$CLS:$SPATH
#NAME=TZCounterTest
NAME=PropertyTZTest
rm -r $CLS/*
javac -d $CLS ${DIRMAIN}/TZCounter.java
javac -d $CLS ${DIRMAIN}/PropertyTZ.java
javac -d $CLS -classpath $CPATH -sourcepath $SPATH ${DIRTEST}/${NAME}.java
pkg=com.yahoo.uda.fetl.abf1.splitter.mapred
java -classpath $CPATH -Ddata=/homes/lubinsky/SVN_FETL/fetl/abf1_splitter/trunk/src/test/java/data junit.textui.TestRunner ${pkg}.$NAME
TYPE ERASURE
http://www.slideshare.net/buzdin/type-erasure
http://beust.com/weblog/2011/07/29/erasure-vs-reification/
http://stackoverflow.com/questions/355060/c-sharp-vs-java-generics
http://www.jprl.com/Blog/archive/development/2007/Aug-31.html
http://blog.adaptivesoftware.biz/2009/02/what-is-type-erasure-in-java.html
http://nerds-central.blogspot.com/2011/04/java-type-erasure-what-pile-of-bollocks.html
http://www.cowtowncoder.com/blog/archives/2012/04/entry_471.html
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html
http://www.indicthreads.com/7706/understanding-type-erasure-in-java/
http://lampwww.epfl.ch/~emir/bqbase/2006/10/16/erasure.html
jar
http://download.oracle.com/javase/tutorial/deployment/jar/index.html
https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html
http://www.ibm.com/developerworks/java/library/j-5things6.html
Generating a Thread Dump: Windows
The Java application that you want to produce a thread dump for must be started in a command console. When you want to produce a thread dump press Ctrl-Break
Generating a Thread Dump: Linux
If the JVM is running in a console then simply press Ctrl-\.
If the JVM is running in the background then send it the QUIT (3) signal:
kill -QUIT process_id
There process_id is the process number of the running Java process. The thread dump will be sent to wherever standard out is redirected too.
Since Java 5 we have the getStackTrace() method of Thread class
http://marxsoftware.blogspot.com/2010/10/reading-java-stack-traces-few-tips.html
jstack
http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/tooldocs/share/jstack.html
jstack <pid> >dump.log 2>&1
JVM command line options
-verbose:gc #print to console
-Xloggc #print to log file
http://www.interview-questions-java.com/
overriding the method equals() of an object, you might also overwrite hashCode()
== compares references while public boolean equals(Object obj) compares contents
o final - declare constant; final class can’t be extended
o finally - handles exception
o finalize - helps in garbage collection
Garbage collector
Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (i.e. background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you can’t force it.
http://habrahabr.ru/post/269621/
http://habrahabr.ru/post/269863/
Object java.lang.Object
protected Object clone() throws CloneNotSupportedException // Creates and returns a copy of this object.
public boolean equals(Object obj) // Indicates whether some other object is "equal to" this one.
protected void finalize() throws Throwable // Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
public final Class getClass() // Returns the runtime class of an object.
public int hashCode() // Returns a hash code value for the object.
public String toString() // Returns a string representation of the object.
public final void notify()
public final void notifyAll()
public final void wait()
public final void wait(long timeout)
public final void wait(long timeout, int nanos)
Examples
String.format("%+03d",i);
Datetime:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
try{
String s="201100010000";
Date d = sdf.parse(s);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
System.out.println(offset2(sdf,d, 0) );
System.out.println(offset2(sdf,d, 1) );
System.out.println(offset2(sdf,d, 2) );
System.out.println(offset2(sdf,d, -1) );
} catch (ParseException ex) {
}
public static String offset2(SimpleDateFormat sdf, Date d, int timeShift){
return sdf.format(new Date(d.getTime() + (timeShift * 3600000)));
}
passing objects by reference
You never pass an object in a Java application, only an object reference. Therefore, you are passing objects by reference. The fact that a Java application passes objects by reference does not mean that a Java application passes parameters by reference. Parameters can be object references, and a Java application passes object references by value.
the default behavior of an object’s clone() method makes a shallow copy.
A fine approach to object copying is to provide a copy constructor or copy
factory. A copy constructor:
public Pet(Pet petToCopy); //usage: Pet p2=new Pet(p1)
A copy factory is the static factory analog of a copy constructor:
//static factory method
public static Pet newInstance(Pet petToCopy){
…
}
advantage of static factory methods is that, unlike constructors,
they are not required to create a new object each time they’re invoked
unlike constructors, they can return an object of any subtype of their return type
The clone() method can be disabled as follows:
public final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
The assignment operation (=) is always a shallow assignment
The == is always a address compare operator
Transient variables cannot be serialized. The fields marked transient in a serializable object will not be transmitted in the byte stream. An example would be a file handle, a database connection, a system thread etc.
Such objects are only meaningful locally. So they should be marked as transient in a serializable class.
Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.
Copy constructor, disable clone()
Overloading deals with multiple methods in the same class
with the same name but different method signatures.
super(..)
Invocation of a superclass constructor must be the first line in the subclass constructor.
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
If the super class does not have a no-argument constructor, you will get a compile-time error.
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.
You can also use super. to refer to a hidden field
Immutable objects
- ensure the class cannot be overridden -
make the class final (cannot be extendend), or
use static factories and keep constructors private (construct instances in factory methods)
- make fields private and final
- force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
- do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
Volatile
The changes to a volatile variable are always visible to other threads. Declaring a volatile Java variable means:
The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
We say "acts as though" in the second point, because to the programmer at least (and probably in most JVM implementations) there is no actual lock object involved. Here is how synchronized and volatile compare:
the main differences between synchronized and volatile are:
a primitive variable may be declared volatile (whereas you can't synchronize on a primitive with synchronized);
an access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;
because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we're prepared to "miss an update");
a volatile variable that is an object reference may be null (because you're effectively synchronizing on the reference, not the actual object).
Attempting to synchronize on a null object will throw a NullPointerException
http://www.javamex.com/tutorials/synchronization_concurrency_1.shtml
http://www.javamex.com/tutorials/synchronization_concurrency_9_locks.shtml
Use ArrayList, HashMap etc as opposed to Vector, Hashtable etc, where possible to avoid any synchronization overhead. Even better is to use just arrays where possible. If multiple threads concurrently access a collection and at least one of the threads either adds or deletes an entry into the collection, then the collection must be externally synchronized.
Exceptions
if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
http://habrahabr.ru/post/268683/
Checked exceptions: try/catch or throws interface
java.io.FileNotFoundException
Unchecked exceptions: not required to have catch()
- Error
- RuntimeException - programmers bugs NullPointerException
The types of exceptions that need not be included in a methods throws list are called Unchecked Exceptions.
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IndexOutOfBoundsException
IllegalStateException
NullPointerException
SecurityException
The types of exceptions that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself are called Checked Exceptions.
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
If a client of your API can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
public void writeList() throws IOException, ArrayIndexOutOfBoundsException {
Remember that ArrayIndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory. You could just write the following.
public void writeList() throws IOException {
Generics
public interface Stack<E> {
public void push(E item);
public E pop();
...
}
public interface LookupTable<K,V> {
public void add(K key, V value);
public V lookup(K key);
...
}
Collection<? extends Animal> dogs = new ArrayList<Dog>();
public static <T>
int binarySearch(List<? extends Comparable<? super T>> list, T key) {
...
}
Enchanced loop syntax
For this syntax to be accepted by the compiler, the class in question must provide a method which returns an implementation of the Iterator interface, and furthermore this method must be called iterator. In Java 5 there is now an Iterable interface. A class implements this interface precisely if it provides an iterator method in the above sense. To benefit from the enhanced syntax, a class must not only provide the iterator, it must say that it does so by declaring that it implements the Iterable interface.
int[] array = {10,20,30};
for (int i : array) {
System.out.println(i);
}
List<Shape> l = new LinkedList<Shape>();
l.add(new Shape("square"));
l.add(new Shape("circle"));
for(Shape shape : l) {
System.out.println("Shape: " + shape);
}
varargs
public Auto (String year, String make, String model, String... options) { …)
StringBuilder & StringBuffer
java.lang.StringBuilder class provides a faster alternative to StringBuffer.
In most ways StringBuilder works exactly the same as StringBuffer but it is not ThreadSafe:
(multiple threads should not access StringBuilder objects without Synchronizing)
String s = new String("stringette"); // DON'T DO THIS!
String s = "stringette"; // DO THIS
Enum
Enum classes come bundled with the following functionality:
declare the method values() that returns an array containing the valid enum instances
declare the method valueOf(String) that returns the appropriate enum instance for the given string rendition
implement Comparable and Serializable
override the methods toString(), equals(), hashCode() and compareTo() as you'd expect.
public enum Days {
sunday, monday, tuesday,wednesday, thursday, friday, saturday;
}
public class TestDays{
public static void main(String[] args){
Days today = Days.monday;
System.out.println("Today is : " + today);
for (Days d : Days.values()) {
System.out.println(d);
}
}
}
java -D to set up environment variables
java -Dproperty=value
-D is an important switch that allows you to set environment properties.
java -Dkey1="val 1" -Dkey2="val 2" SomeClass
java -Dtest="true" -jar myApplication.jar
You can call the following from anywhere in the code to read the properties given on the command line:
String value = System.getProperty("key", "defaultvalue");
Some of the default properties that are supposed to have already been set include: file.encoding, file.separator, java.home and java.version.
In C/C++ compilers the similar syntax is used to define preprocessor macros from the command line:
gcc hello.c -DGREETING="\"Hello, world\""
hello.c :
#include <stdio.h>
int main(int argc, char* argv[]) {
printf(GREETING);
return 0;
}
Java Properties on Steroids
В Java есть стандартный класс Properties, с помощью которого можно загрузить ini-файл и прочитать его свойства. При большом объеме конфигурационных файлов чтение и запись настроек в объекты превращается в очень нудную и рутинную работу: создать объект Properties, конвертировать каждую настройку в нужный формат и записать его в поле.
3rd party solution: http://owner.aeonbits.org/
Annotations
http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html
are equal, but if two objects are equal then they must return the same hashCode() result
== is reference equality, use .equals() for value comparisons
Null out references once they become obsolete
If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface
hashCode() and equals() : equal objects must have equal hash codes
http://habrahabr.ru/post/168195/
You must override hashCode in every class that overrides equals. Failure to do so will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
http://www.artima.com/lejava/articles/equality.html
If you look into the source code of Object class you will find the following code
public boolean equals(Object obj) {
return (this == obj);
}
If 2 objects have the same hashCode() result does not mean that they
It is often misunderstood that hashCode() needs to somehow uniquely identify an object or reflect differences in equals(), but that is not the case.
The hashCode method is redefined below. This is essential for any class that redefines the equals method.
@Override public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name) o;
return n.firstName.equals(firstName) && n.lastName.equals(lastName);
}
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
}
Singleton
public class SingletonClass {
private static SingletonClass ourInstance = new SingletonClass();
public static SingletonClass getInstance() {
return singletonObj;
}
private SingletonClass() {
}
}
//-------------ANOTHER APPROACH------------------------------------------------
class SingletonClass {
private static SingletonClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private SingletonClass() {
// Optional Code
}
public static synchronized SingletonClass getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonClass();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
JDBC
http://webmoli.com/2009/02/01/jdbc-performance-tuning-with-optimal-fetch-size/
http://minborgsjavapot.blogspot.ca/2015/11/easily-create-database-content-with.html
http://www.java2s.com/Code/Java/Database-SQL-JDBC/CatalogDatabase-SQL-JDBC.htm
https://github.com/davidmoten/rxjava-jdbc
http://www.thetechrepo.com/main-articles/450-useful-open-source-third-party-java-libraries
http://java-source.net/open-source/workflow-engines
http://sujitpal.blogspot.com/2009/04/higher-order-functions-in-java.html
http://neo4j.org/ Graph database
http://jena.sourceforge.net/ Semantic Web framework
http://www.manageability.org/blog/stuff/open-source-graph-network-visualization-in-java/view
Others