--- Basic syntax java trap

2010-11-01  来源:本站原创  分类:Java  人气:101 

Basic syntax:

1, find odd:

public static boolean isOdd (int i) {

return i% 2 == 1;

}

If i is negative, then the return value are all false, this is a negative odd% 2 because the words get is a negative number.

Therefore, the correct way is:

public static boolean isOdd (int i) {

if ((i% 2) == 1 | | (i% 2) ==- 1) {

return true;

} Else {

return false;

}

}

2, floating-point subtraction:

System. Out. Println (2.0-1.1);

Logically speaking, the result is 0.9, but the running result is 0.8999999999999999. This is because the java operation inside the floating-point subtraction problems with loss of precision, in order to avoid this, the correct approach should be:

System. Out. Println (new BigDecimal ("2.0"). Subtract (new BigDecimal ("1.1 ")));

Or:

System. Out. Println (2.0f-1.1f);

Or:

System. Out. Printf ("% .1 f", (2.0-1.1));

3, long division:

final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; / / microsecond

final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; / / ms System. out. println (MICROS_PER_DAY / MILLIS_PER_DAY);

It stands to reason, the result should be 1000, but the running result is 5, is the data out of bounds it? This is the long data type O can not be it. Why is this? This is because the java inside, multiplication on both sides of the data, java will it as a type of data, int. Since it is int type, int type, or, after multiplying, so there is not the correct result.

The correct way is:

final long MICROS_PER_DAY = (long) 24 * 60 * 60 * 1000 * 1000; / / microsecond

final long MILLIS_PER_DAY = (long) 24 * 60 * 60 * 1000; / / ms

Or:

final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000;

final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;

4, exchange content:

int x = 1999;

int y = 2000;

System. Out. Println ("x =" + x + ", y =" + y);

Among the C language, so the content can be interchangeable, but which in java, run the result is:

x = 0, y = 1999. y swap came, x is not reversed.

Content can be interchanged in java like this:

int temp = 0;

temp = y;

y = x;

x = temp;

System. Out. Println ("x =" + x + ", y =" + y);

Can XOR the above:

y = (x ^ = (y ^ = x)) ^ y;

5, string and character:

System. Out. Print ("H" + "a");

System. Out. Println ('H' + 'a');

Imagine the output should be HaHa, but the running result is: Ha169. This is because Ha is the second single quotes. Characters between single quotes in java is char type, char type smaller than int type, char character when the sum of the two, then automatically promoted to int type of the. Therefore, 'H' + 'a' is the result of 169.

6 array of characters:

char [] c = {'1 ', '2', '3 '};

System. Out. Println ("Array c =" + c);

The output is: array c = [C @ de6ced. One can imagine that such a result is not that people want. But remove the "array c =", then, System. Out. Println (c); like this the output is 123. This is because the System. Out. Println ("Array c =" + c), the string is the process of splicing, println method of receiving a String type of string. See, void java.io.PrintStream.println (String x), it will automatically call the toString method. In the System. Out. Println (c), the string is a char type receiving array, see, void java.io.PrintStream.println (char [] x). Therefore, we must score to open write:

System. Out. Print ("array c =");

System. Out. Println (c);

Or:

System. Out. Println ("Array c =" + new String (c));

7, the escape character:

System. Out. Println ("a \ u0022.length () + \ u0022b". Length ());

The output is not a \ u0022.length () + \ u0022b length, it is because \ u0022 represents a double quote. This above statement is equivalent to:

System. Out. Println ("a". Length () + "b". Length ());

8, print out the class name:

System. Out. Println (MyClass. class. GetName (). ReplaceAll (".", "/")

+ ". Class");

If the package name is the package com.ibeifeng.interview.pitfalls; but the output is:

///////////////////////////////////////. Class, rather than:

com / ibeifeng / interview / pitfalls / MyClass.class

This is because the "." Special characters such as this it must be escaped, use "\ \.".

You could use replace method:

System. Out. Println (MyClass. class. GetName (). Replace (".", "/") + ". Class");

9, random question:

private static Random random = new Random ();

public static void main (String [] args) {

StringBuffer word = null;

switch (random. nextInt (3)) {

case 1:

word = new StringBuffer ('P');

break;

case 2:

word = new StringBuffer ('G');

break;

default:

word = new StringBuffer ('M');

}

word.append ('a');

word.append ('i');

word.append ('n');

System. Out. Println (word);

}

}

The output is ain. This is because the StringBuffer will receive an int type of data as its capacity. Look, java.lang.StringBuffer.StringBuffer (int capacity). So will 'P', 'G', 'M', int type data into the capacity of a StringBuffer, so the lack of word values. This time as long as the single quote quotes in pairs on the line rewrite.

10, the relentless incremental steps:

int j = 0;

for (int i = 0; i <100; i + +) {

j = j + +;

}

System. Out. Println (j);

The output is 0, because j + + is the first assignment and then do + + operator. Therefore, the value of j is always 0. Will be replaced by j = j + + j + + or + + j it.

11, Integer border issues

private static final int END = Integer. MAX_VALUE;

private static final int START = END - 100;

public static void main (String [] args) {

int count = 0;

for (int i = START; i <= END; i + +) {

count + +;

}

System. Out. Println (count);

}

This program will lead to infinite loop. END is the int type as the maximum, when i = END time, i + + will lead to i become a minimum.

12, indecisive Returns:

public static boolean decision () {

try {

return true;

} Finally {

return false;

}

}

Used try statement in the return statement, the final returns false. This is because the try statement will eventually be interrupted.

13, finally have to run it?

try {

System. Out. Println ("Hello World");

System. Exit (0);

} Finally {

System. Out. Println ("Good Bye World ");</

相关文章
  • --- Basic syntax java trap 2010-11-01

    Basic syntax: 1, find odd: public static boolean isOdd (int i) { return i% 2 == 1; } If i is negative, then the return value are all false, this is a negative odd% 2 because the words get is a negative number. Therefore, the correct way is: public st

  • Java ---- java basic syntax of the cast, operator, if the branch, for loop, while, break, continue, switch 2010-04-23

    1: java basic syntax of the cast, Grammatical forms such as: data type (reference data type) variable name = (mandatory data type) value of other variable or variables; Examples: int i = (int) (1 * 0.11); 2: java based syntax of operators and express

  • Java trap the assert keyword 2010-09-04

    Java trap the assert keyword I. Introduction In C and C + + language has the key to assert that claim. In Java, there are also assert keyword that assertion, the use and meaning are similar. Second, grammar In Java,, assert keyword is introduced from

  • Basic knowledge JAVA 2010-03-27

    Basic knowledge JAVA 1, object-oriented features are what 1. Abstract: Abstract is to overlook a topic unrelated to the current target those aspects in order to more fully pay attention to related aspects of the current target. Abstract did not inten

  • The basic syntax of oracle stored procedure and precautions 2010-03-31

    The basic syntax of oracle stored procedure 1. The basic structure CREATE OR REPLACE PROCEDURE stored procedure name ( Parameter 1 IN NUMBER, Parameter 2 IN NUMBER ) IS Variable 1 INTEGER: = 0; Variable 2 DATE; BEGIN END stored procedure name 2.SELEC

  • MySQL Select statement in the basic syntax 2010-04-08

    SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [HIGH_PRIORITY] [DISTINCT|DISTINCTROW|ALL] select_list [INTO {OUTFILE|DUMPFILE} 'file_name' export_options] [FROM table_references [WHERE where_definition] [GROUP BY col_name,...] [HAVING whe

  • The basic syntax of mysql stored procedure articles 2010-06-24

    Learning the basic grammar of the main reference to the mysql User's Guide Mysql database stored procedure needs to have proc Table. The table created during the MySQL 5.1 installation. If you are upgrading from an earlier version to MySQL 5.1, make

  • The basic syntax highlights ORACLE 2011-08-03

    The basic syntax highlights ORACLE - Table create table test (names varchar2 (12), dates date, num int, dou double); - View create or replace view vi_test as select * from test; - Synonyms create or replace synonym aa for dbusrcard001.aa; - Stored Pr

  • The basic syntax of oracle stored procedures and precautions 2010-10-12

    The basic syntax of oracle stored procedure 1 The basic structure CREATE OR REPLACE PROCEDURE stored procedure name ( Parameter 1 IN NUMBER, Parameter 2 IN NUMBER ) IS Variable 1 INTEGER: = 0; Variable 2 DATE; BEGIN END stored procedure name 2.SELECT

  • PL / SQL block basic syntax (ORACLE stored procedures, functions, packages, cursors) 2011-07-11

    PL / SQL block basic syntax (ORACLE stored procedures, functions, packages, cursors) 1, PL / SQL block PL / SQL block apply only to Oracle database, using the temporarily stored in the client, rather than stored in the database. Basic syntax: declare

  • oracle PL / SQL basic composition, block structure and basic syntax requirements, data types, variable definitions, operators and functions 2011-10-08

    oracle PL / SQL basic composition, block structure and basic syntax requirements, data types, variable definitions, operators and functions Feature PL / SQL language is the SQL language extensions, designed for application developers with features su

  • basic syntax oracle stored procedure 2010-03-29

    Keywords: oracle 1. The basic structure CREATE OR REPLACE PROCEDURE stored procedure name ( Parameter 1 IN NUMBER, Parameter 2 IN NUMBER ) IS Variable 1 INTEGER: = 0; Variable 2 DATE; BEGIN END stored procedure name 2.SELECT INTO STATEMENT To select

  • Four basic sort JAVA 2010-06-25

    JAVA four basic sort, including the bubble method, insertion method, selection method, SHELL sort. One selection method improved bubble law, SHELL insertion sort method is improved. So basically it can be summed up in two different sorting methods: n

  • The basic syntax of LDAP 2010-11-26

    Basic LDAP syntax • = (equals) The LDAP parameters indicate that the value of a property is equal to a certain condition is met. For example, if you want to find "name" property to "John" all objects, you can use: (GivenName = John) Th

  • The basic syntax of SQL 2010-12-26

    SQL database design and advanced query -------------------------------------------------- -------------------------------------------------- ------------------------ 2009.2.27 Yin Database Design Chapter ----------------------------------------------

  • BI, the basic syntax and concepts MDX 2011-07-17

    Find a report on the MDX syntax and basic concepts of the article, with their little correction, posted to share. MDX syntax and basic concepts 1, MDX Overview MDX (multi-dimensional expressions Multidimensional Expressions) is a syntax that supports

  • Basic syntax mysql database 2011-03-10

    Start: net start mySql; Enter: mysql-u root -p/mysql-h localhost-u root-p databaseName; Listed in the database: show databases; Select a database: use databaseName; List form: show tables; Display table column attributes: show columns from tableName;

  • Flex basic syntax code (1) 2010-05-05

    Here is some code flex based syntax, check in time would be convenient to forget: package { import flash.display.Sprite; public class AS_0100_HelloWorld extends Sprite { public function AS_0100_HelloWorld() { trace("HelloWorld"); } } } trace nee

  • Basic knowledge JAVA 6 Pz% @ 5P 1. What are the characteristics of object-oriented aspects of yl3 = V 5b 1. Abstraction: 8 9M.C | Dkf abstract is to ignore the topic with the current 2010-05-07

    Introduction: We are learning Java about three directions, the first, desktop systems, including C / S structure; second, J2ME, for an unlimited field of promising guys, look at China's mobile phone users will know. Third, for enterprise applications

  • freemarker basic syntax 2010-06-06

    1. Insert ( Export )${book.name} Null value judgments :${book.name?if_exists }, ${book.name?default('xxx')}// Default xxx ${ book.name!"xxx"}// Default xxx Date Format :${book.date?string('yyyy-MM-dd')} Digital format :${book?string.number}--20