JAVA基础编程——String

这里的String可以类比为C/C++中的string,不过由于这两种编程语言的区别,在一些方法接口上可能存在一些区别。

String类的实例化

JAVA和C/C++中的string都可以进行直接赋值,此种操作使得string看起来就像是一种基本数据类型,但其实string是类,也就是引用数据类型。

也就是说JAVA中的String类型,可以通过直接赋值或者new的方式进行实例化操作:

public class Demo {
	public static void main(String args[]) {
	    String str1 = "Hello";
		String str2 = new String("world.");
		
		System.out.println(str1 + " " + str2);
	}
}

结果为:

Hello world.

从上面的例子可以看出,直接赋值或是通过new进行实例化都是可以的。这是因为String中存在一个构造方法:

public String(String original)

而两种实例化方法的区别可从下面的代码中得到:

public class Demo {
	public static void main(String args[]) {
	    String str1 = "Hello";
		String str2 = "Hello";
				
		System.out.println(str1 == str2);
		System.out.println(str1.equals(str2));
		
		String str3 = new String("Hello");
		String str4 = new String("Hello");
				
		System.out.println(str3 == str4);
		System.out.println(str3.equals(str4));
		
		System.out.println(str1 == str3);
		System.out.println(str1.equals(str3));
	}
}

先看结果:

true
true
false
true
false
true

从上面的结果可以看出:

  • 直接赋值相同的字符串指向的是同一块堆内存
  • new实例化相同的字符串指向的不是同一块堆内存
  • 直接赋值和new实例化相同的字符串虽然内容相同,但指向的堆内存却并不相同

这一点跟C/C++是类似的,C/C++中,直接赋值的字符串会先在内存的常量空间中由系统分配空间进行字符串存储,然后将对应变量指向该内存。而利用构造方法实例化则意味着会重新开辟空间进行字符串存储,然后将对应变量指向该内存,虽然堆内存内容一样,但栈内存却并不相同。

JAVA中,若想要使用new实例化的同时还能够节约内存,可以使用String类的intern方法,该方法会将对应的字符串存入对象池,当后续存在直接赋值同样的字符串操作时,可以将其栈内存直接指向该堆内存,达到节约内存的效果。

public class Demo {
	public static void main(String args[]) {
	    String str1 = new String("Hello").intern();
		String str2 = "Hello";
		
		System.out.println(str1 == str2);
		System.out.println(str1.equals(str2));
	}
}

结果为:

true
true

同时JAVA和C/C++还有一点是类似的,C/C++中的字符串常量会在内存空间中分配内存进行存储,且该内存空间由于存储的是常量字符串,所以无法被主动释放。JAVA中同样也有这个特性,每个用“”表示的字符串在直接赋值或者其它操作之前都会为其分配堆内存,最终不存在应用的堆内存空间将称为垃圾空间。这也要求在实际代码中,String的内容最好不要有过多的修改,以免占用不必要的内存空间。

String的比较

在整数值的比较中,如果两个整数值相同,那么比较的结果便是相同。而在String的比较中却不一样:

public class Demo {
	public static void main(String args[]) {
	    String str1 = "Hello";
		String str2 = new String("Hello");
		
		String str3 = str2;
		
		System.out.println(str1 == str2);
		System.out.println(str2 == str3);
		System.out.println(str1 == str3);
	}
}

结果为:

false
true
false

上面这段代码所要表达的意思是:因为String属于引用数据类型,而比较操作比较的是栈内存中的内容,而str1和str2是两个变量名,指向的两个不同的堆内存,那么其栈内存对应的内容必不相同,因此str1和str2不相同,而str2和str3指向相同的堆内存,因此相同,而str1和str3也不相同。

因此,String类型的比较可以使用String类方法equals进行,语法为:

public boolean equals(Object anObject)

代码实例为:

public class Demo {
	public static void main(String args[]) {
	    String str1 = "Hello";
		String str2 = new String("Hello");
				
		System.out.println(str1.equals(str2));
		System.out.println("Hello".equals(str2));
	}
}

结果为:

true
true

从上面的代码可以看出,两次比较的结果都是true。第一次结果为true还可以理解,是将两个变量指向的堆内存内容进行比较。那么第二次为比较结果是为什么?毕竟equals方法是String的类方法,而这里并没有将Hello这个字符串实例化给对应的String对象。

其实JAVA和C/C++中都没有定义字符串这一数据类型,但是在JAVA中创造了String这一特殊类,同时规定所有的字符串要求使用“”声明,但是String仍然不属于基本数据类型,只是引用数据类型,因此实际上以“”引用的字符串数据实际上是作为String类型的匿名对象形式存在的。这样也就能够解释为什么“Hello”.equals(str2)是合理的。

String的常用方法

这里只说明一下String的常用方法,包括返回值、方法名、参数类型等。

String() // Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes) // Constructs a new String by decoding the specified array of bytes using the default charset.
String(byte[] ascii, int hibyte) // Deprecated.This method does not properly convert bytes into characters.
String(byte[] bytes, int offset, int length) // Constructs a new String by decoding the specified subarray of bytes using the default charset.
String(byte[] ascii, int hibyte, int offset, int count) // Deprecated.This method does not properly convert bytes into characters.
String(byte[] bytes, int offset, int length, String charsetName) // Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] bytes, int offset, int length, Charset charset) // Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] bytes, String charsetName) // Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] bytes, Charset charset) // Constructs a new String by decoding the specified array of bytes using the specified charset.
String(char[] value) // Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
String(char[] value, int offset, int count) // Allocates a new String that contains characters from a subarray of the character array argument.
String(int[] codePoints, int offset, int count) // Allocates a new String that contains characters from a subarray of the Unicode code point array argument.
String(String original) // Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer) // Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
String(StringBuilder builder) // Allocates a new string that contains the sequence of characters currently contained in the string builder argument.

char charAt(int index) // Returns the char value at the specified index.
IntStream chars() // Returns a stream of int zero-extending the char values from this sequence.
int codePointAt(int index) // Returns the character (Unicode code point) at the specified index.
int codePointBefore(int index) // Returns the character (Unicode code point) before the specified index.
int codePointCount(int beginIndex, int endIndex) // Returns the number of Unicode code points in the specified text range of this String.
IntStream codePoints() // Returns a stream of code point values from this sequence.
int compareTo(String anotherString) // Compares two strings lexicographically.
int compareToIgnoreCase(String str) // Compares two strings lexicographically, ignoring case differences.
String concat(String str) // Concatenates the specified string to the end of this string.
boolean //contains(CharSequence s) // Returns true if and only if this string contains the specified sequence of char values.
boolean contentEquals(CharSequence cs) // Compares this string to the specified CharSequence.
boolean contentEquals(StringBuffer sb) // Compares this string to the specified StringBuffer.
static StringcopyValueOf(char[] data) // Equivalent to valueOf(char[]).
static StringcopyValueOf(char[] data, int offset, int count) // Equivalent to valueOf(char[], int, int).
Optional<String> describeConstable() // Returns an Optional containing the nominal descriptor for this instance, which is the instance itself.
boolean endsWith(String suffix) // Tests if this string ends with the specified suffix.
boolean equals(Object anObject) // Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString) // Compares this String to another String, ignoring case considerations.
static String format(String format, Object... args) // Returns a formatted string using the specified format string and arguments.
static String format(Locale l, String format, Object... args) // Returns a formatted string using the specified locale, format string, and arguments.
String formatted(Object... args) // Formats using this string as the format string, and the supplied arguments.
byte[] getBytes() // Encodes this String into a sequence of bytes using the default charset, storing the result into a new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) // Deprecated.This method does not properly convert characters into bytes.
byte[] getBytes(String charsetName) // Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
byte[] getBytes(Charset charset) // Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) // Copies characters from this string into the destination character array.
int hashCode() // Returns a hash code for this string.
String indent(int n) // Adjusts the indentation of each line of this string based on the value of n, and normalizes line termination characters.
int indexOf(int ch) // Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex) // Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str) // Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex) // Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
String intern() // Returns a canonical representation for the string object.
boolean isBlank() // Returns true if the string is empty or contains only white space codepoints, otherwise false.
boolean isEmpty() // Returns true if, and only if, length() is 0.
static Stringjoin(CharSequence delimiter, CharSequence... elements) // Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
static Stringjoin(CharSequence delimiter, Iterable<? extends CharSequence> elements) // Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
int lastIndexOf(int ch) // Returns the index within this string of the last occurrence of the specified character.
int lastIndexOf(int ch, int fromIndex) // Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
int lastIndexOf(String str) // Returns the index within this string of the last occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex) // Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
int length() // Returns the length of this string.
Stream<String> lines() // Returns a stream of lines extracted from this string, separated by line terminators.
boolean matches(String regex) // Tells whether or not this string matches the given regular expression.
int offsetByCodePoints(int index, int codePointOffset) // Returns the index within this String that is offset from the given index by codePointOffset code points.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) // Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len) // Tests if two string regions are equal.
String repeat(int count) // Returns a string whose value is the concatenation of this string repeated count times.
String replace(char oldChar, char newChar) // Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement) // Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement) // Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement) // Replaces the first substring of this string that matches the given regular expression with the given replacement.
String resolveConstantDesc(MethodHandles.Lookup lookup) // Resolves this instance as a ConstantDesc, the result of which is the instance itself.
String[] split(String regex) // Splits this string around matches of the given regular expression.
String[] split(String regex, int limit) // Splits this string around matches of the given regular expression.
boolean startsWith(String prefix) // Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset) // Tests if the substring of this string beginning at the specified index starts with the specified prefix.
String strip() // Returns a string whose value is this string, with all leading and trailing white space removed.
String stripIndent() // Returns a string whose value is this string, with incidental white space removed from the beginning and end of every line.
String stripLeading() // Returns a string whose value is this string, with all leading white space removed.
String stripTrailing() // Returns a string whose value is this string, with all trailing white space removed.
Char SequencesubSequence(int beginIndex, int endIndex) // Returns a character sequence that is a subsequence of this sequence.
String substring(int beginIndex) // Returns a string that is a substring of this string.
String substring(int beginIndex, int endIndex) // Returns a string that is a substring of this string.
char[] toCharArray() // Converts this string to a new character array.StringtoLowerCase()Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale) // Converts all of the characters in this String to lower case using the rules of the given Locale.
String toString() // This object (which is already a string!)
String toUpperCase() // Converts all of the characters in this String to upper case using the rules of the default locale.
String toUpperCase(Locale locale) // Converts all of the characters in this String to upper case using the rules of the given Locale.
<R> R transform(Function<? super String,? extends R> f) // This method allows the application of a function to this string.
String translateEscapes() // Returns a string whose value is this string, with escape sequences translated as if in a string literal.
String trim() // Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020' (the space character).
static String valueOf(boolean b) // Returns the string representation of the boolean argument.
static String valueOf(char c) // Returns the string representation of the char argument.
static String valueOf(char[] data) // Returns the string representation of the char array argument.
static String valueOf(char[] data, int offset, int count) // Returns the string representation of a specific subarray of the char array argument.
static String valueOf(double d) // Returns the string representation of the double argument.
static String valueOf(float f) // Returns the string representation of the float argument.
static String valueOf(int i) // Returns the string representation of the int argument.
static String valueOf(long l) // Returns the string representation of the long argument.
static String valueOf(Object obj) // Returns the string representation of the Object argument.

总的来说,String类的方法接口与C/C++类似,基本能够通过方法名判断出来,结合注释大致就能猜到用法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值