程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java 語言沒有 unsigned 類型

Java 語言沒有 unsigned 類型

編輯:關於JAVA
 

跟 C 語言不同,Java 中沒有 unsigned 類型,這點可能讓很多人都有過困擾。

那如果碰到確實需要用到 unsigned 類型的情況怎麼辦呢? 通常的辦法就是用更大一號的類型來處理,比如:

處理 unsigned byte,就用 int;
處理 unsigned int,就用 long;
處理 unsigned long,這個不好辦,只能用 BigInteger 了。但是要注意的是,Java 中的 long 是 8 bytes,而 C 語言只有4 bytes,所以碰到這種情況的話,那就等同於上面 unsigned int 的情況了。
另外,Java 中比 C 語言增加了一種不帶符號的移位操作: >>> ,固定的用 0 來填充左邊高位的空缺,這在一定程度上減輕了沒有 unsigned 類型帶來的影響。

 


擴展閱讀:這裡有篇文章介紹了 Java 中怎麼處理 unsigned 類型的。文中提到的一篇對 C /C++/Java 語言創始人的訪談中提到了 Java 中沒有定義 unsigned 類型的原因,見最後 Gosling 的部分:

Q: Programmers often talk about the advantages and disadvantages of programming
in a "simple language." What does that phrase mean to you, and is [C/C++/Java] a
simple language in your view?

Ritchie: C (and the others for that matter) are simple in some ways, though they are
also subtle; other, somewhat similar languages like Pascal are arguably simpler. What
has become clear is that aspects of the environment like libraries that aren't part of
the core language are much bigger and more complicated. The 1999 C standard grew
hugely more in the library part than in the language; the C++ STL and other things
are big; AWT and other things associated with Java are too.

Stroustrup: I see three obvious notions of "simple:" to be easy to learn, to make it
easy to express ideas, and to have a one-to-one correspondence to some form of
math. In those terms, none of the three languages is simple. However, once mastered,
C and C++ make it easy to express quite complex and advanced ideas -- especially
when those ideas have to be expressed under real-world resource constraints.

Gosling: For me as a language designer, which I don't really count myself as these days,
what "simple" really ended up meaning was could I expect J. Random Developer to
hold the spec in his head. That definition says that, for instance, Java isn't -- and
in fact a lot of these languages end up with a lot of corner cases, things that nobody
really understands. Quiz any C developer about unsigned, and pretty soon you discover
that almost no C developers actually understand what goes on with unsigned,
what unsigned arithmetic is. Things like that made C complex.
The language part of Java is, I think, pretty simple. The libraries you have to look up.

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved