JAVA--String str=""与new String()的区别

目录

常量池:

使用String直接赋值:

使用new String创建字符串:

String拼接字符串:

String.intern():

总结:


常量池:

       常量池(constant pool)指的是在编译期被确定,并被保存在已编译的.class文件中的一些数据。它包括了关于类、方法、接口等中的常量,也包括字符串常量。

       在常量池中存储字符串常量的内存空间,即字符串常量池,当需要使用字符串时,先去字符串池中查看该字符串是否已经存在,如果存在,则可以直接使用,如果不存在,初始化,并将该字符串放入字符串常量池中。

       从字符串角度思考:其对象的引用都是存储在栈中的,如果是编译期已经创建好(直接赋值字符串)的就存储在常量池中,如果是运行期(new出来的)才能确定的就存储在堆中。对于equals相等的字符串,在常量池中永远只有一份在堆中有多份

 

使用String直接赋值:

String str = “abc”可能创建一个或者不创建对象。如果”abc”在字符串池中不存在,会在java字符串池中创建一个String对象(”abc”),然后str指向这个内存地址,无论以后用这种方式创建多少个值为”abc”的字符串对象,始终只有一个内存地址被分配;如果“abc” 在字符串池中存在, str直接指向这个内存地址。

实例:

String str = "abc";

String str1 = "abc";

String str2 = "abc";

System.out.println(str==str1);//true

System.out.println(str==str2);//true

使用new String创建字符串:

String str = new String(“abc”)至少会创建一个对象,也有可能创建两个。因为用到new关键字,肯定会在堆中创建一个String对象,如果字符池中已经存在”abc”,则不会在字符串池中创建一个String对象,如果不存在,则会在字符串常量池中也创建一个对象。

实例:

String str = new String("abc");

String str1 = new String("abc");

String str2 = new String("abc");

System.out.println(str==str1);//false

System.out.println(str==str2);//false

String拼接字符串:

除了直接使用=赋值,也会用到字符串拼接,字符串拼接又分为变量拼接已知字符串拼接

只要拼接内容存在变量,那么该拼接后的新变量就是在堆内存中新建的一个对象实体。

实例:

String str = "abc";//在常量池中创建abc

String str1 = "abcd";//在常量池中创建abcd

String str2 = str+"d";//拼接字符串,此时会在堆中新建一个abcd的对象,因为str2编译之前是未知的

String str3 = "abc"+"d";//拼接之后str3还是abcd,所以还是会指向字符串常量池的内存地址

System.out.println(str1==str2);//false

System.out.println(str1==str3);//true

 

String.intern():

       当调用 intern 方法时,如果常量池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到常量池中,并返回此 String 对象的引用。

实例:

String s1=new String("abc");

String s2=s1.intern();

System.out.println( s1==s2 ); //false

System.out.println( s1+" "+s2 ); // abc abc

System.out.println( s2==s1.intern() ); //true

s1==s1.intern()为false说明原来的“abc”仍然存在;

 

总结:

  1. String str=“abc”String str=new String(“abc”); 产生几个对象?

     前者1或0后者2或1,先看字符串常量池,如果字符串常量池中没有,都在常量池中创建一个,如果有,前者直接引用,后       者在堆内存中还需创建一个“abc”实例对象。

      2.对于基础类型的变量和常量:变量和引用存储在栈中,常量存储在常量池中。

      3.为了提升jvm(JAVA虚拟机)性能和减少内存开销,避免字符的重复创建 项目中还是不要使用new String去创建字符串,最好使用String直接赋值

      4.关于equals()和==:对于String类简单来说,equals()就是比较两字符串的内容是否相等,如果相等返回true;而==是比较两字符串的地址是否相同,也就是是否是同一个字符串的引用,如果是返回true。

      5.String字符串是不可变的

 

可参考:

https://www.cnblogs.com/guozhenqiang/p/5633269.html

https://blog.csdn.net/weixin_41098980/article/details/80060200

https://blog.csdn.net/u014082714/article/details/50087563

 

  • 26
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
实验1 分析成绩单 1. 实验目的:掌握字符输入、输出流用法。 2. 实验代码: Fenxi: import java.util.*; public class Fenxi{ public static double getTotalScore(String s){ Scanner scanner=new Scanner(s); scanner.useDelimiter("[^0123456789.]+"); double totalScore=0; while(scanner.hasNext()){ try{ double score=scanner.nextDouble(); totalScore=totalScore+score; } catch(InputMismatchException exp){ String t=scanner.next(); } } return totalScore; } } AnalysisResult: import java.io.*; import java.util.*; public class AnalysisResult{ public static void main(String args[]){ File fRead=new File("score.txt"); File fWrite=new File("scoreAnalysis.txt"); try{ Writer out= new FileWriter(fWrite,true);//以尾加方式创建指向文件fWrite的out流 BufferedWriter bufferWrite=new BufferedWriter(out); //创建指向out的bufferWrite流 Reader in=new FileReader(fRead); //创建指向文件fRead的in流 BufferedReader bufferRead=new BufferedReader(in); //创建指向in的bufferRead流 String str=null; while ((str=bufferRead.readLine())!=null){ double totalScore =Fenxi.getTotalScore(str); str=str+"总分:"+totalScore; System.out.println(str); bufferWrite.write(str); bufferWrite.newLine(); } bufferRead.close(); bufferWrite.close(); } catch(IOException e){ System.out.println(e.toString()); } } } 3. 结果截图: 4. 实验分析: 1. 改进程序,使得能统计出每个学生的平均成绩。 答: 2. 现在有如下格式的货物明细(文本格式)goods.txt 品名:电视,length:102 cm,width:89 cm,height:56 cm. 品名:轿车,length:4502 cm,width:178 cm,height:156 cm. 品名:桌子,length:125 cm,width:78 cm,height:68 cm. 答: CalculateVolume.java import java.io.*; import java.util.*; public class CalculateVolume{ public static void main(String args[]){ File fRead=new File("goods.txt"); File fWrite=new File("goodsVolume.txt"); try{Writer out=new FileWriter(fWrite,true); BufferedWriter bufferWrite=new BufferedWriter(out); Reader in=new FileReader(fRead); BufferedReader bufferRead=new BufferedReader(in); String str=null; while((str=bufferRead.readLine())!=null){ double s=Jisuan.getVolume(str); str=str+"体积:"+s+"cm^3"; System.out.println(str); bufferWrite.write(str); bufferWrite.newLine(); } bufferRead.close()
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import java.util.Scanner; public class Student { public static final String DRIVER="sun.jdbc.odbc.JdbcOdbcDriver"; public static final String URL="jdbc:odbc:student"; public static final String USERNAME="root";//用户名 public static final String PASSWORD="root";//密码 private static String name;//当前登录管理员的名字 private static int userid;//当前登录管理员的主键 //获得 jdbc 链接 public Connection connection(){ try { Class.forName(DRIVER); Connection con=DriverManager.getConnection(URL, USERNAME, PASSWORD); return con; } catch (Exception e) { e.printStackTrace(); } return null; } //管理员登陆 public boolean login() throws Exception{ Scanner sc = new Scanner(System.in); System.out.print("输入用户名:"); String username = sc.next(); System.out.print("输入密码:"); String password = sc.next(); //查找该用户 String sql = "select username,id from muser where username='" + username + "' and password='" + password + "'"; Connection connection = connection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); if (rs.next()) { name = rs.getString(1); userid = rs.getInt(2); return true; } return false; } //添加学生 //添加学生 public void addstudent(){ System.out.print("请依次输入学号,姓名,年龄,地址(用逗号隔开):"); Scanner scanner = new Scanner(System.in); String[] str = scanner.next().split(","); /**********************begin 验证学号是否重复*************************/ String sql = "select * from student where 1=1 and stuno="+str[0]; try { Connection connection = connection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); if(rs.next()){ System.out.println("该学号已经存在,请更换"); return; } } catch (SQLException ex) { } /**********************end 验证学号是否重复*************************/ String sql1 = "insert into student(stuno,stuname,stuage,stuaddress) values(?,?,?,?)"; Connection co

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值