know , know why . We learn to use java, things just started some details may haunt us , over time , tend to take for granted, the issue is still not clear. Being asked , it may be " natural" to tell people , "This is a java package , and know how to use on the line ." Over time, we may or many configuration tools , but no director Jin .
To a certain extent, help us figure out this vague concept , detail, hereby big java version in the various sub- board , opened a "You do not know java" series of posts , I hope the public gathering "Java Man" experience and sweat , to promote "open source " thinking , so that we know the details of some java process flow , tools or configuration files, some of Java 's become more than people know .
rules:
1. classmate message , first found himself thrown out , others may not know the details , give the answer to this question .
2. crowd of students , if that what makes you whom applauded details , please tap " useful to me ."
3. Results posted once a month , according to the " useful to me ," the degree and extent of the problem wonderful reward points corresponding proportion . ( I permissions on 200 points , if demand exceeds supply , and I hope I do not blame the public greatly stingy Ha ! )
you do not know java (SE)
here first shamelessly threw two bricks :
1. execute java program , how to pass parameters to the main method ?
executed when the command line , followed by the class name parameter , separated by a space several parameters, such as :
java MyTest Tomcat is good in use.
"Tomcat is good in use." will be divided into five string passed to the main method MyTest ( as args).
2. String, Integer , etc. j2se basic classes we usually use what java installation environment ?
in $ HOME \ jre \ lib \ rt.jar in . (rt, everywhere ah . )
3. playing jar package no problem , MANIFEST.MF also set the Main-Class, why can not execute main method response ( error "Invalid or corrupt jarfile")?
Main-Class: to add a space after the colon , and then bring the package path configuration classes , such as :
Main-Class: com.test.HelloWorld
jar package so that you can execute the command line : java-jar XXX.jar
( Of course , if you configure the default way to open jar file "Java (TM) platform SE binary", you can double-click the jar file execution )
4. said the same string hashCode, necessarily equals, how to construct two strings to the same hashCode, different strings ?
First, in order to simplify the problem , we can define , with the length of the two strings .
We know the hash strategy String.hashCode method ( reference source ) : character string loop through (c represent characters , ASCc represents the ASCII value of c ) , calculate : hashcode = 31 * hashcode + ASCc
because only two strings , hashcode initial value is 0 , the string is assumed to be two of our "XY" and "MN", then the hashcode respectively (31 * ASCX + ASCY) and ( 31 * ASCM + ASCN).
Then make up the numbers on it : ASCX and ASCM can take any value ( as small as possible , in the ASCII code range ), ASCY and ASCN ASCX and ASCM according to the values obtained curve relationship ( values should ASCII code in the range of 0 to 127 Cou ) .
ASCX values such as 49, ASCM value of 50 , the resulting equation : 31 * 49 + ASCY = 31 * 50 + ASCN, conversion : ASCY = 31 + ASCN. At this point , we might ASCN value 66 , then ASCY value 97.
Then we can use System.out.println ((char) 49); way that each ASCII character code corresponding to : 49 , '1 ' ; 50 , '2' ; ; 66, 'B'; 97, 'a'.
Ever since, the same hashCode, string constructed two different strings good : "1a", "2B" ( I rub , not deliberately construct this string .. ) .
( here to look good, to scrape together a regular character , you can also try other ASCII characters , oh the range 0 to 127 )
short step thousand miles , not small streams into a mighty torrent .
digression :
limited personal capacity , the first trial in J2SE version , welcome to the forum experienced java other students with the same title by sending topic.
If the score is limited , it can give me a message , I'll post a summary ( and marked problems provider ID).
we welcome suggestions for improvement.
------ Solution ---------------------------------------- ----
jdk7 the switch expression can be a String. Is this not
------ Solution ------------------------------------ --------
when we print the string has only know System.out.print and System.out.println two functions , I also recently learned that the original java as well as providing similar c language printf function .
String name = "张三";
int age = 20;
System.out.printf("您的姓名是:%s,年龄是:%d", name, age);
------ Solution ------------------------------------- -------
one might say we all know : java biggest feature is platform -independent, because java is running on the java virtual machine , namely jvm (Java Virtual Machine), it by the actual computer simulation to achieve a variety of computer functions . It is responsible for interaction with the operating system , used to shield the operating system environment for java run , makes Java program can run only on the generated Java Virtual Machine bytecode can.
------ Solution ---------------------------------------- ----
java fire up a large part of his cross-platform with a relationship , but now feels he is not cross-platform advantage . . net can also be cross-platform looks like a
------ Solution -------------------------------- ------------
use enum to implement singleton class , did not know enum can also define methods !
enum Singleton {
INSTANCE;
public void dosth() {
System.out.println("do sth....");
}
}
public class Test {
public static void main(String[] args) {
Singleton singleton = Singleton.INSTANCE;
singleton.dosth();
}
}
------ Solution - -------------------------------------------
String object is not change, adding the first time into StringBuffer, calling the append method , and finally converted to String, String original reference it again
------ Solution -------------- ------------------------------
class member variable load order is: the parent class static block ( static variables ) - > Then a subclass static block ( static variables ) - > parent class member variables - > parent class constructor blocks - > Son class member variables - > subclass constructor block
------ Solution ------------------------ limited expression --------------------
static method call can be calculated , but its value will be ignored. Nothing more than an empty limit
System.out.println(((Math) null).random());
------ Solution ------------------------------------- ------- application
variable parameters (C, CPP has this syntax , the most typical is the realization of a string format ) :
public PrintWriter format (String format, Object ... args);
------ Solution -------------- ------------------------------
In fact, if it is a small string splicing operation , you can use the + operator . If splicing more frequently, you can follow your argument to achieve.
now use StringBuilder. + compiler operations will be transferred into the StringBuilder append
------ Solution ----------------------- ---------------------
String of + operation, write the code , compiled with javap -c view .
------ Solution ---------------------------------------- ----
we generally in the preparation of java code , usually with a letter , underscore , numbers , etc., as class names, variable names , etc., but in fact fully support the use of Chinese java as these names.
following code can be run .
public class 测试 {
public static void main(String[] args) {
String 姓名="张三";
int 年龄=30;
System.out.printf("姓名:%s,年龄:%d",姓名,年龄);
}
}
------ Solution ------------------------------------- -------
Performance
c higher than java , it depends on what type of application is doing .
Now the performance of java is not a problem , although certainly not a high performance c theoretically , but in some applications, such as web, java performance will be very high performance , as with c to develop this application, will consume a lot of development costs and efficiency is not necessarily much higher than java , c little deal with bad words ( not all programmers can be no assurance procedures turnovers ) not as java.
In addition to lowering development costs more money with java buy servers to be clustered than c definitely better write performance .
------ Solution ---------------------------------------- ----
static method bypasses the binding of specific reference checks , and I really do not know this before .
specifically to investigate some of the JLS 7 compile-time binding method , so with the following code , the compiler can not guess , if so, what these method calls are output :
public class MethodDeterminationTest {
public static void main(String[] args) {
Object o = "abc";
MethodDeterminationTest.print(o);
MethodDeterminationTest.<String>print("abcd");
MethodDeterminationTest.<Integer>print(5);
MethodDeterminationTest.<Integer>print("abcd");
((MethodDeterminationTest)null).<Number>print(5.0);
}
public static <E> void print(E e) {
System.out.println("generic " + e);
}
public static void print(String s) {
System.out.println(s);
}
}
actually know these probably rarely used , but may be rare cases when you debug someone awful is overloading code, know that at least there will be an alert mind chord .
------ Solution ---------------------------------------- ----
static method bypasses the binding of specific reference checks , and I really do not know this before .
specifically to investigate some of the JLS 7 compile-time binding method , so with the following code , the compiler can not guess , if so, what these method calls are output :
public class MethodDeterminationTest {
public static void main(String[] args) {
Object o = "abc";
MethodDeterminationTest.print(o);
MethodDeterminationTest.<String>print("abcd");
MethodDeterminationTest.<Integer>print(5);
MethodDeterminationTest.<Integer>print("abcd");
((MethodDeterminationTest)null).<Number>print(5.0);
}
public static <E> void print(E e) {
System.out.println("generic " + e);
}
public static void print(String s) {
System.out.println(s);
}
}
actually know these probably rarely used , but may be rare cases when you debug someone awful is overloading code, know that at least there will be an alert mind chord .
plus two :
MethodDeterminationTest.print(null);
MethodDeterminationTest.<Integer>print(null);
------ Solution ------------------------------------- -------
int i=0;
i=i++;
System.out.println(i);
output is 0 ; increased since the principle : first declare a temporary variable to store the value of i is not incremented int temp = i; that this time temp = 0 Since then increased
i 1, i = i +1; finally return temp, i.e., return temp;
That is the last execution to i = i + +; time because + + operator priority than = , so i will be equal to i + + ; the return value, that is, i = temp = 0; ..... when i change this program of i ...> 0 .....> 1 .. ...> 0
------ Solution ---------------------------------- ----------
many times when converting themselves multiply a series of numbers , in fact java.util.concurrent.TimeUnit provides conversion method :
as five days is the number of seconds TimeUnit.DAYS.toSeconds (5l); having to 60l × 60 × 24 × 5
------ Solution ------------------------------------------- -
null instanceof Xxxx returns false So
aObject! = null && aObject instanceof Xxxx front of non- null judgment is superfluous.
=============================================
Collections.
=============================================
public class Baz
==============================================
List
Map
put ("1", "one");
put ("2", "two");
}};
------ Solution ------------------------------------ --------
add that , java language and java virtual machine in the future will be developed independently in both directions , because the java virtual machine can run the bytecode file, byte code file does not must only be generated by the java language , in fact , now there are some languages that can generate byte code that runs on the Java virtual machine , such as JRuby, Groovy , etc., look more generic jvm future .
------ Solution ---------------------------------------- ----
java rounding problem
double a = 2.5555;
BigDecimal b = new BigDecimal (a);
double aa = b.setScale (3, BigDecimal.ROUND_HALF_UP) doubleValue ().;
System.out.println (aa);
Note: Because a decimal stored in the computer itself is imprecise , all output is 2.555 ; If you want to avoid this problem BigDecimal b = new BigDecimal (a); brackets to incoming character string type that is used constructor Bigdecimal (String s).
------ Solution --------------------------- -----------------
using switch (this)
in the definition of enum class method ------ Solution ------ --------------------------------------
no main function of a Java program can also java command running
------ Solution ------------------------------------ --------
say one of you may know :
achieved without using an intermediate variable swap two numbers
int A=3;
int B=5;
System.out.println("A="+A+"\tB="+B);
A=A^B;
B=B^A;
A=A^B;
System.out.println("A="+A+"\tB="+B);
------ Solution ------------------------------------- -------
to calculate a number multiplied by 2 ^ n do not have to use a for loop to achieve , and it can be:
int i=3;
int j=64;
System.out.println(i<<4);//3乘以2的4次方,48
System.out.println(j>>4);//64除以2的4次方,4
This approach has limitations, only for base 2
( you may have seen , they laughed, huh )
------ Solution ----------------------- ---------------------
static code segment.
[ code ]
public class DontHaveMain {
static {
System.out.println("I'm done.");
}
} [Test] ( in Eclipse Run is probably not drop ...).
C: \> java DontHaveMain
I'm done.
Exception in thread "main" java.lang.NoSuchMethodError: main
------ Solution --------------- -----------------------------
Results posted yet today , few think to say about it , there may not know in :
Calendar is not thread safe ( this is obvious )
SimpleDateFormat is not thread-safe ( this maybe a lot of people did not notice )
So sometimes you want to avoid using private static final DateFormat SHARED = new SimpleDateFormat ("..."); such ,
- it can not use ThreadLocal it?
- ThreadLocal than every time a new one is not necessarily more efficient SimpleDateFormat
Similarly, some of them very cheap to build objects, such as StringBuilder, may not have all the advantages of using ThreadLocal on efficiency .
Calendar instantiate a little expensive, it is not suitable for use ThreadLocal ? - You can test yourself.
===============
The following classes are not immutable common (design flaw ? )
java.awt.Dimension
java.awt.Point
( but java.awt.Color is immutable , really random design ah )
java.util.Date ( this must be a design flaw )
The following classes are those commonly used immutable:
String
Integer, Boolean, Long, Double ......
BigInteger
BigDecimal
===============
When
EnumSet and EnumMap, when the total number of its use within the enum element is greater than 64 and less than equal to 64 , which are two different (efficiency ) of the underlying implementation , less than or equal 64 when higher efficiency (EnumSet time in 64 or less is a long)
===============
for members who , final contain volatile effect ;
right way of saying , private containing the final results.
===============
Arrays.sort In order to achieve internal reference type is merge sort, recursive internal parts small enough to use insertion sort.
------ Solution ------------------------------------ --------
file path , can be integrated using the " / " , rather than with a backslash , java automatically converted according to OS.
===============
When
super.method () is ( not override a ) safety calls , the equivalent final method calls , so call the parent class method in the constructor , good habits are all together ;. super
------ For reference only ----------------------------------- ----
for matching string using regular expressions more convenient , specific methods , such as I have read , again posting. First to a record
------ For reference only ---------------------------------- -----
------ For reference only ---------------------------------- -----
. net is what cross-platform way to achieve it?
------ For reference only -------------------------------------- -
ah , enumeration, there are a lot of things , it is value in making it .
If we can give to the next, how to enumerate , single- mode general category of cases , even more okay !
------ For reference only -------------------------------------- -
in fact, if it is a small string splicing operation , you can use the + operator . If splicing more frequently, you can follow your argument to achieve.
------ For reference only ---------------------------------- -----
amount on just a few days do not come to see the landlord posts learn
------ For reference only ---------------------------------------
In fact, if a splicing operation a small string, you can use the + operator . If splicing more frequently, you can follow your argument to achieve.
I said is + internal implementation process
------ For reference only ------------------------- --------------
top one , this fun ~
guess static methods and classes only relevant object without judgment .
values are ignored is what ah mean ? I tried the following code , it can get the correct result :
Math m = null;
System.out.println (m.random ());
print a bunch of decimals.
fancy which reply , the point under "To me useful" chant ?
In fact, if it is a small string splicing operation , you can use the + operator . If splicing more frequently, you can follow your argument to achieve.
I'm talking about the internal implementation process +
I know what you mean , learn it ~
Does the internal processing of such operators , there is no relevant blog or books that way ?
In fact, if it is a small string splicing operation , you can use the + operator . If splicing more frequently, you can follow your argument to achieve.
now use StringBuilder. + compiler operations will be transferred into the StringBuilder append
Thank you to share. ~
StringBuilder thread- safe , so we are using string concatenation operator + time , pay attention to thread safety issues.
------ For reference only ---------------------------------- -----
support the landlord ! have points ! !
------ For reference only -------------------------------------- -
String of + operation, write the code , compiled with javap-c to view.
Nice ~
------ For reference only ---------------------------------------
I have come to learn.
------ For reference only -------------------------------------- -
xiexie ~
------ For reference only ------------------------------- --------
recommend facie Thinking in Java which was about the stuff I see unintelligible , alas .
seeketh after feeling ...
------ For reference only --------------------------- ------------
there are a lot of good reads strenuous ah.
------ For reference only -------------------------------------- -
long exposure , thanks to the landlord
------ For reference only ---------------------------------- -----
printf this good , you can format the output. . And much like the C language printf
System.out.printf ("% s,% d,% .2,% n ( newline ) " ) ;
------ For reference only ---------------------------------- -----
C: you did me a high performance
------ For reference only --------------------- ------------------
static method bypasses the binding of specific reference checks , and I really do not know this before .
specifically to investigate some of the JLS 7 compile-time binding method , so with the following code , the compiler can not guess , if so, what these method calls are output :
public class MethodDeterminationTest {
public static void main(String[] args) {
Object o = "abc";
MethodDeterminationTest.print(o);
MethodDeterminationTest.<String>print("abcd");
MethodDeterminationTest.<Integer>print(5);
MethodDeterminationTest.<Integer>print("abcd");
((MethodDeterminationTest)null).<Number>print(5.0);
}
public static <E> void print(E e) {
System.out.println("generic " + e);
}
public static void print(String s) {
System.out.println(s);
}
}
actually know these probably rarely used , but may be rare cases when you debug someone awful is overloading code, know that at least there will be an alert mind chord .
seeking advice :
MethodDeterminationTest.
What is this ?
------ For reference only ---------------------------------- -----
static method bypasses the binding of specific reference checks , and I really do not know this before .
specifically to investigate some of the JLS 7 compile-time binding method , so with the following code , the compiler can not guess , if so, what these method calls are output :
public class MethodDeterminationTest {
public static void main(String[] args) {
Object o = "abc";
MethodDeterminationTest.print(o);
MethodDeterminationTest.<String>print("abcd");
MethodDeterminationTest.<Integer>print(5);
MethodDeterminationTest.<Integer>print("abcd");
((MethodDeterminationTest)null).<Number>print(5.0);
}
public static <E> void print(E e) {
System.out.println("generic " + e);
}
public static void print(String s) {
System.out.println(s);
}
}
actually know these probably rarely used , but may be rare cases when you debug someone awful is overloading code, know that at least there will be an alert mind chord .
seeking advice :
MethodDeterminationTest.
What is this ?
What is your Java version ? I use Java 6 (IDE Netbeans 7.2) to compile and run no problem.
------ For reference only -------------------------------------- -
net of the method used to achieve cross-platform yet. ?
framework
------ For reference only --------------------------------- ------
static method bypasses the binding of specific reference checks , and I really do not know this before .
specifically to investigate some of the JLS 7 compile-time binding method , so with the following code , the compiler can not guess , if so, what these method calls are output :
public class MethodDeterminationTest {
public static void main(String[] args) {
Object o = "abc";
MethodDeterminationTest.print(o);
MethodDeterminationTest.<String>print("abcd");
MethodDeterminationTest.<Integer>print(5);
MethodDeterminationTest.<Integer>print("abcd");
((MethodDeterminationTest)null).<Number>print(5.0);
}
public static <E> void print(E e) {
System.out.println("generic " + e);
}
public static void print(String s) {
System.out.println(s);
}
}
actually know these probably rarely used , but may be rare cases when you debug someone awful is overloading code, know that at least there will be an alert mind chord .
seeking advice :
MethodDeterminationTest.
What is this ?
What is your Java version ? I use Java 6 (IDE Netbeans 7.2) to compile and run no problem.
1.5 of
------ For reference only -------------------------------- -------
. net is what cross-platform way to achieve it? . net looks like more of a cross-language
------ For reference only ------------------------- --------------
------ For reference only ---------------------------------------
the end of the early knot stickers, Welcome everyone to seize the time , a lot of sharing ha ~
------ For reference only ----------------------------- ----------
top first , and then I made a sample to understand the usage of 2,3 points :
public class Test2
{
public static void main(String[] args)
{
/*Map<String, Integer> map1 = Collections.<String, Integer> emptyMap();
map1.put("a", 111);
System.out.println(map1.get("a"));*///空map,有何作用?
Baz baz = new Baz(new MyT());
baz.showFun();
}
}
class Baz<T extends Foo & Bar>//Bar 必须为接口
{
private T t;
public Baz(T t)
{
this.t = t;
}
public void showFun()
{
t.fooFun();
t.barFun();
}
}
class Foo
{
public void fooFun()
{
System.out.println("fooFun...");
}
}
interface Bar
{
void barFun();
}
class MyT
extends Foo
implements Bar
{
public void barFun()
{
System.out.println("barFun");
}
}
ask about the role of the empty Map , and I do not know in what scenario will be used ? (Put, get all throwing the exception )
------ For reference only ---------------------------------- -----
mark it, the landlord said fourth point really do not know
------ For reference only ----------------- ----------------------
You know there is in addition to System.out System.err what
------ For reference only -------------------- -------------------
In addition to System.out
You know what there is System.err
Why do you ask me ?
------ For reference only -------------------------------------- -
In addition to System.out
You know what there is System.err
Why do you ask me ?
I thought you did not know , to tell you about.
------ For reference only -------------------------------------- -
ah , learning the ~
------ For reference only --------------------------------------- end
the last day, we speed to fill ah !
------ For reference only ---------------------------------------
essence is based on current enum instance , switch enumeration is to ?
------ For reference only -------------------------------------- -
Good . . . . . . . . Roof . ------ For reference only -------------------------------------- -
knot posted on Monday , we have material quickly burst ah ! ~
------ For reference only ---------------------------------------
if there is a examples Jiuhaola ~
------ For reference only --------------------------------- ------
I came to learn about
------ For reference only ------------------------- --------------
public class NoMainClass {
static {
System.out.println("No main method.");
System.exit(0);
}
}
------ For reference only ----- ----------------------------------
before java8 use joda-time, jdk8 there the jsr310 (javax.time)
------ For reference only ------------------------------- --------
static code segment.
[ code ]
public class DontHaveMain {
static {
System.out.println("I'm done.");
}
} [Test] ( in Eclipse Run is probably not drop ...).
C: \> java DontHaveMain
I'm done.
Exception in thread "main" java.lang.NoSuchMethodError: main M
Thank God , that exception can circumvent it?
In addition, because the score limit , M God can not give too many points , sorry friends ~
is time shot !
sorry to pull you over.
did not see your message , quite regrettable , hehe ~
Results posted comments:
finally the end of the first month of the post, in strict accordance with 5 points allocated one vote , of course, some of the problems big score , score limit , only less to the point, really sorry ah !
@ huntor Great God 41L where there less to 5 points , even to other people, sorry ah. . .
@ raistlic brother broke the news a lot, but on the last day , you might see fewer people vote less, score just does not, will the next , huh, huh ~
@ chenchenchenliu discussion on cross-platform , and probably little relevance detailed knowledge of java , so although there is a vote , but only to score three points , two points evenly to other small partners , please understanding ha ~
early August, I got a medal , and then look at their posts by technical paste rarely , quite ashamed , they discussed the idea of such a study posted hope from the majority Javaers learned valuable lessons . If there are good java details , I will send a "second season ."
In addition , 24L brother @ u010379116 give me some inspiration, I hope to carry out some follow-up on the "Think in java" and other books of the discussion thread , while urging his reading serious point , but it is also able to share with everyone's reading comprehension .
Of course , paste it in Java , there are many great and I respect God :
such as @ ldh911 quick thinking , experience and the starting point is to treat complex problems sophistication ;
such as @ fangmingshijie framework skillful , helpful, concise ;
such as @ AA5279AA though younger than I am , for the ability to control the regular expression makes me ashamed.
( tip of the iceberg here , just mention what I see , they are a small part of the features ) Of course , there are many not mentioned , but I was impressed by the other Great God ( even some low-key Great God , only in places they are interested send a message, looks like the score is not high , in fact, is very knowledgeable ) . I hope that God is able to quite large in their areas of expertise , made some small discussions lead us to learn more in-depth knowledge of Java .
CSDN java forum personal feeling is still pretty busy popularity , if able to organize themselves , do little discussion or helpful .
brother ( Zhuangnen a ) expect you to lead us , to engage in the study of the atmosphere up ha ~
------ For reference only ---------------------------------- -----
Yes, the last sentence add : System.exit (0);
In fact, I do not need to score , we just focusing mix ^ _ ^
------ For reference only ----------------- ----------------------
If there is an example Jiuhaola ~ JUnit. . . . . .
------ For reference only -------------------------------------- -
static code segment.
[ code ]
public class DontHaveMain {
static {
System.out.println("I'm done.");
}
} [Test] ( in Eclipse Run is probably not drop ...).
C: \> java DontHaveMain
I'm done.
Exception in thread "main" java.lang.NoSuchMethodError: main M
Thank God , that exception can circumvent it?
In addition, because the score limit , M God can not give too many points , sorry friends ~
is time shot !
sorry to pull you over.
did not see your message , quite regrettable , hehe ~
Results posted comments:
finally the end of the first month of the post, in strict accordance with 5 points allocated one vote , of course, some of the problems big score , score limit , only less to the point, really sorry ah !
@ huntor Great God 41L where there less to 5 points , even to other people, sorry ah. . .
@ raistlic brother broke the news a lot, but on the last day , you might see fewer people vote less, score just does not, will the next , huh, huh ~
@ chenchenchenliu discussion on cross-platform , and probably little relevance detailed knowledge of java , so although there is a vote , but only to score three points , two points evenly to other small partners , please understanding ha ~
early August, I got a medal , and then look at their posts by technical paste rarely , quite ashamed , they discussed the idea of such a study posted hope from the majority Javaers learned valuable lessons . If there are good java details , I will send a "second season ."
没有评论:
发表评论