有图的笔记可以直接看码云
l
或L
(默认为int
)、单精度浮点型需加f
或F
(默认为double
)String
类型转换图(必记)
float d1 = n1 + 1.1;//错,因为浮点默认是double
int n2 = 1.1;//错,因为不可大到小
byte
、short
和char
之间不会相互自动转换byte b2 = n2;//错,变量赋值需判断类型,整型比byte”高一级“ byte b1 = 10; char c1 = b1;//错,byte不可自动转char
byte
、short
和char
之间可以计算,但需先转换为int
byte b1 = 1; byte b3 = 2; short s1 = 1; short s2 = b2 + s1;//错 int s2 = b2 + s1;//对
boolean
不参与转换boolean pass = true; int num = pass;//错
char
可以保存int
的常量值,但不可以保存int
变量byte
和short
、char
类型在进行运算时,当做int
处理int y = (int)8.8; char c1 = 100;//正确 int m = 100; char c2 = m;//错
String
int n1 = 100; float f1 = 1.1f; double d1 = 4.5; boolean b1 =true; String s1 = n1 + ""; String s2 = f1 + ""; String s3 = d1 + ""; String s4 = b1 + "";
Stirng
转基本型String s5 = "123"; int num1 = Integer.parseInt(s5); double num2 = Double.parseDouble(s5); float num3 = Float.parseFloat(s5); long num4 = Long.parseLong(s5); byte num5 = Byte.parseByte(s5); short num6 = Short.parseShort(s5); boolean b = Boolean.parseBoolean("true");
String
转char
String s1 = "Hello"; char c1 = s1.charAt(0); System.out.println(c1);//输出 H
n3 = 30 n5 = 8
public class myHomework2 { public static void main(String args[]) { char c1='\n'; char c2='\t'; char c3='\r'; char c4='\\'; char c5='1'; char c6='2'; char c7='3'; System.out.println(c1); System.out.println(c2); System.out.println(c3); System.out.println(c4); System.out.println(c5); System.out.println(c6); System.out.println(c7); } }
"\t"
写成'\t'
否则会显示数字
System.out.println('a'+'b');
相当于97+98故显示195public class myHomework3 { public static void main(String args[]) { String book1="小学语文",book2="初中物理"; char sex1='男',sex2='女'; double price1=17.2,price2=8.29; System.out.println(book1+"\t"+book2); System.out.println(sex1+"\t"+sex2); System.out.println(price1+"\t"+price2); } }
public class myHomework4 { public static void main(String argsp[]) { String name="张三",hobby="玩游戏"; int age=12; float grade=59; char sex='男'; System.out.println("姓名\t\t年龄\t成绩\t性别\t爱好\n" +name+"\t\t"+age+"\t"+grade+"\t"+sex+"\t"+hobby); } }