字符型
Java中使用单引号来表示字符常量,字符型在内存中占2个字节。 char 类型用来表示在Unicode编码表中的字符。Unicode编码被设计用来处理各种语言的文字,它占2个字节,可允许有65536个字符。
转义字符
转移字符 含义 Unicode值 \b 退格 \u0008 \n 换行 \u000a \r 回车 \u000d \t 制表符(tab) \u0009 " 双引号 \u0022 ’ 单引号 \u0027 \ 反斜杠 \u005c
实例
package StudyTest01 ; public class TestVar01 { public static void main ( String [ ] args) { char ch1 = 'a' ; System . out. println ( ch1) ; char ch2 = 'A' ; System . out. println ( ch2) ; char ch3 = '4' ; System . out. println ( ch3) ; char ch4 = '中' ; System . out. println ( ch4) ; char ch5 = '?' ; System . out. println ( ch5) ; char ch6 = ' ' ; System . out. println ( ch6) ; System . out. println ( "--------------------------------" ) ; char ch7 = '\n' ; System . out. println ( "aaa" + ch7+ "bbb" ) ; System . out. println ( "aaa\nbbb" ) ; System . out. println ( "aaaaaaa\tbbb" ) ; System . out. println ( "aaa\bbbb" ) ; System . out. println ( "aaa\rbbb" ) ; System . out. println ( "\"java\"" ) ; }
}
运行结果
ASCII码
实例
class TestVar02 { public static void main ( String [ ] args) { char ch1 = 'A' ; System . out. println ( ch1) ; System . out. println ( ch1+ 90 ) ; System . out. println ( 155 - ch1) ; char ch2 = '中' ; System . out. println ( ch2) ; System . out. println ( ch2+ 90 ) ; System . out. println ( 20103 - ch2) ; int num1 = ( int ) ch2; System . out. println ( num1) ; char ch = ( char ) 20013 ; System . out. println ( ch) ; int num2 = '中' ; char ch5 = 20013 ; System . out. println ( ch5) ; char ch6 = '2' + 2 ; System . out. println ( ch6) ; }
运行结果
布尔型
boolean类型有两个常量值,true和false,在内存中占一位(不是一个字节),不可以使用 0 或非 0 的整数替代 true 和 false ,这点和C语言不同。 boolean 类型用来判断逻辑条件,一般用于程序流程控制 。
实例
public class TestVar03 { public static void main ( String [ ] args) { boolean flag1 = true ; System . out. println ( flag1) ; boolean flag2 = false ; System . out. println ( flag2) ; boolean flag3 = 5 == 9 ; System . out. println ( flag3) ; boolean flag4 = 5 < 9 ; System . out. println ( flag4) ; }
}
运行结果