Common Classes
Overview of Common Classes:
-
Internal Class
-
Object class
-
Packaging Class
-
Mathematical Classes
-
Time Class
-
Character string
-
String Builder and String Buffer
-
DecimalFormat
I. Internal Classes
Concept: Define a complete class within a class.
In general, classes and classes are independent of each other. Internal classes mean to break this independent idea and make one class the internal information of another class, at the same level as member variables and member methods.
Benefits of internal classes:
Writing a class outside and inside will ultimately produce the same results. Why should we use an internal class instead?
With the technology of internal class, the details and internal structure can be hidden, the encapsulation is better, and the structure of the program is more reasonable! Calls between classes can be tedious if there are many classes and they are exposed!
Scanning VX for Java, Front End, Testing, python, etc.
Classification of internal classes:
1. Member internal classes (non-static internal classes)
[Reference Code]
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> NeiBuLei; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">OuterClass</span> { <span style="color:#008000 ">//member variable</span> <span style="color:#0000ff">private</span> String OuterName; <span style="color:#008000 ">//Member Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">display</span>(){ System.out.println(<span style="color:#A31515 ">" This is an external class method! "</span>"; System.out.println(OuterName); } <span style="color:#008000 ">//internal class</span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">InnerClass</span>{ <span style="color:#008000 ">//member variable</span> <span style="color:#0000ff">private</span> String InnerNme; <span style="color:#008000 ">//Construction Method </span> <span style="color:#0000ff">public</span> <span style="color:#a31515">InnerClass</span>() { InnerNme = <span style="color:#a31515">"Inner Class"</span>; } <span style="color:#008000 ">//Member Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">display</span>(){ System.out.println(<span style="color:#A31515'>'This is an internal class method! "</span>"; System.out.println(InnerNme); } } <span style="color:#008000 ">//Main Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { OuterClass outerClass = <span style="color:#0000ff">new</span> OuterClass(); outerClass.display();<span style="color:#008000 ">//This is an external class method! Null</span> <span style="color:#008000 ">//This class is an internal class and is no longer a stand-alone class, so it cannot be created directly like an external class!</span> <span style="color:#008000 ">//InnerClass innerClass = new InnerClass (); not possible </span> OuterClass.InnerClass innerClass = outerClass.new <span style="color:#a31515">InnerClass</span>();<span style="color:#008000 ">//Same member method/variable just prefixed </span> innerClass.display();<span style="color:#008000 ">//This is an internal class method!</span> } } </code></span></span>
Output results:
This is an external class method!
null
This is an internal class method!
Inner Class
Summary: The use of member internal classes (non-static internal classes) is to use the internal class as a member variable/member method of the external class, so you must rely on the object of the external class to invoke it. The usage is consistent with the member variable/member method!
2. Local Internal Classes
Local internal classes: Basic internal classes can also be defined in a single method body.
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> NeiBuLei; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">OuterClass</span> { <span style="color:#008000 ">//member variable</span> <span style="color:#0000ff">private</span> String OuterName; <span style="color:#008000 ">//Member Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">display</span>(){ <span style="color:#0000ff">class</span> <span style="color:#a31515">InnerClass</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">print</span>(){ System.out.println(<span style="color:#A31515 ">" This is a local internal class method! "</span>"; } } InnerClass innerClass = <span style="color:#0000ff">new</span> InnerClass(); innerClass.print(); } <span style="color:#008000 ">//Main Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { OuterClass outerClass = <span style="color:#0000ff">new</span> OuterClass(); outerClass.display(); } } </code></span></span>
3. Static Internal Classes
The construction of static internal classes does not depend on external class objects, and the static components in a class do not depend on any objects. They can be constructed directly from the class itself.
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> NeiBuLei; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">OuterClass</span> { <span style="color:#008000 ">//member variable</span> <span style="color:#0000ff">private</span> String OuterName; <span style="color:#008000 ">//Member Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">display</span>(){ System.out.println(<span style="color:#A31515 ">" This is an external class method! "</span>"; System.out.println(OuterName); } <span style="color:#008000 ">//Static Internal Class </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">InnerClass</span>{ <span style="color:#0000ff">private</span> String InnerName; <span style="color:#0000ff">public</span> <span style="color:#a31515">InnerClass</span>() { InnerName = <span style="color:#a31515">"Inner Class"</span>; } <span style="color:#008000 ">//Member Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">display</span>(){ System.out.println(<span style="color:#A31515'>'This is a static internal class method! "</span>"; System.out.println(InnerName); } } <span style="color:#008000 ">//Main Method </span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { OuterClass outerClass = <span style="color:#0000ff">new</span> OuterClass(); outerClass.display(); <span style="color:#008000 ">//Static internal class construction does not depend on external classes, it can be constructed directly by the class itself!</span> InnerClass innerClass = <span style="color:#0000ff">new</span> InnerClass(); innerClass.display(); } } </code></span></span>
Output results:
This is an external class method!
null
This is a static internal class method!
Inner Class
Scanning VX for Java, Front End, Testing, python, etc.
4. Anonymous Internal Class
Anonymous inner class: An inner class without a name.
Anonymous internal class is the main application and interface implementation!
Interface:
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> NeiBuLei; <span style="color:#0000ff">public</span> <span style="color:#0000ff">interface</span> <span style="color:#a31515">MyInterface</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">test</span>(); } </code></span></span>
Implementation class:
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> NeiBuLei; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">MyImplement</span> <span style="color:#0000ff">implements</span> <span style="color:#a31515">MyInterface</span>{ <span style="color:#2b91af">@Override</span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">test</span>() { System.out.println(<span style="color:#a31515">"test"</span>); } } </code></span></span>
Use of anonymous internal classes:
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> NeiBuLei; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">Test</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { <span style="color:#008000 ">//Implementation Class </span> MyInterface myInterface = <span style="color:#0000ff">new</span> MyImplement(); myInterface.test(); <span style="color:#008000 ">//Anonymous Internal Class </span> MyInterface myInterface1 = <span style="color:#0000ff">new</span> MyInterface() { <span style="color:#008000 ">//Interface cannot be new, here is the implementation class of the interface (same as the implementation class, no instance only)</span> <span style="color:#2b91af">@Override</span> <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">test</span>() { System.out.println(<span style="color:#a31515">"test"</span>); } }; myInterface.test(); <span style="color:#008000">/** * The end result is the same for both implementations! */</span> } } </code></span></span>
Benefits of anonymous internal classes:
Once we have defined the interface, its implementation class does not need to create a separate file to write its implementation. We can write the operation of this implementation class to the place we call it. It is more concise and convenient to write.
Disadvantages of anonymous internal classes:
Coupling is too high!
2. Object Classes
jdk Chinese online documentation: Java 8 Chinese Version - Online API Chinese Manual - Code Tool (matools.com)
Object class common methods:
1. Equas method
==Comparison with equals [Interview Question]+ jdk View Source
==is a comparison operator
-
==: You can judge not only the basic type but also the reference type.
-
==: If you are determining the basic type, you are determining whether the values are equal.
//==: If you are determining the basic type, you are determining whether the values are equal int x1 = 10; int x2 = 10; double x3 = 10.0; System.out.println(x1 == x2);//true System.out.println(x1 == x3);//true
-
==: If you are determining the type of reference, you are determining whether the addresses are equal, that is, whether they are the same object.
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> Equals; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">Test01</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { <span style="color:#008000 ">/==: If you are judging the type of reference, you are judging whether the addresses are equal, that is, you are judging whether the same object is </span> A a = <span style="color:#0000ff">new</span> A(); A b = a; A c = b; System.out.println(a==c);<span style="color:#008000">// ? true</span> System.out.println(b==c);<span style="color:#008000">// true</span> B obj = a; System.out.println(obj==c);<span style="color:#008000">// true</span> } } <span style="color:#0000ff">class</span> <span style="color:#a31515">B</span>{} <span style="color:#0000ff">class</span> <span style="color:#a31515">A</span> <span style="color:#0000ff">extends</span> <span style="color:#a31515">B</span>{} </code></span></span>
- The equals method is a method in the Object class and can only determine the reference type.
idea view Jdk source: mouse cursor on the method to view, enter ctrl + b directly
View all methods of a class: ctrl + F12
- The default judgment is whether the addresses are equal, and subclasses (the Object class is the parent of all classes) often override this method to determine if the contents are equal.
/* Object class equals() method source code //Default judgement of whether addresses are the same public boolean equals(Object obj) { return (this == obj); } Subclasses often override this method to determine if the content is equal The equals() method source code in String classes (overrides the parent equals() method) public boolean equals(Object anObject) { if (this == anObject) {// if it is the same object (same address) Return true; //return true } if (anObject instanceof String) {//type of judgment String anotherString = (String)anObject; //Transition down int n = value.length; if (n == anotherString.value.length) {//if the length is the same char v1[] = value; char v2[] = anotherString.value; int i = 0; While (n--!= 0) {// compare each character if (v1[i] != v2[i]) return false; i++; } return true; //Returns true if both strings are identical for each character } } return false; } */
Take an example
[Small Practice]
Write out the output:
package Equals; public class EqualsTest01 { public static void main(String[] args) { Person p1 = new Person(); p1.name = "tom"; Person p2 = new Person(); p2.name = "tom"; System.out.println(p1 == p2); //Reference Type - Determines whether the same object (address) System.out.println(p1.name.equals(p2.name));// p.name is a String type and overrides the equals() method to determine if the content is the same System.out.println(p1.equals(p2));//p1,p2 belongs to the Person class, which does not override the equals() method (inherits the parent equals() method, i.e., determines the address) String s1 = new String("abc"); String s2 = new String("abc"); System.out.println(s1.equals(s2)); System.out.println(s1 == s2); } } class Person{ public String name; }
Output results:
false
true
false
true
false
2.hashCode method
Scanning VX for Java, Front End, Testing, python, etc.
Summary: (can be viewed as an address but it is not an address in nature)
- Improving the efficiency of containers with hash structure
- Two references, if they point to the same object, the hash must be the same
- Two references, if they point to different objects, the hash values are different
- Hash values are based primarily on address numbers! Hash values cannot be exactly equivalent to addresses
- hashCode will also be overridden in subsequent collections if needed
package hashCode; public class HashCode { public static void main(String[] args) { AA aa = new AA(); AA aa2 = new AA(); AA aa3 = aa; System.out.println("aa.hashCode()="+ aa.hashCode()); System.out.println("aa2.hashCode()="+ aa2.hashCode()); System.out.println("aa3.hashCode()="+ aa3.hashCode()); } } class AA{}
aa.hashCode()=460141958
aa2.hashCode()=1163157884
aa3.hashCode()=460141958
3.toString method
Basic Introduction:
Default return: hexadecimal for full class name + @ +hash value
/* Object toString() source code //(1) getClass(). Full class name of getName() class (package name + class name) //(2)Integer.toHexString(hashCode()) converts the value of hashCode to a hexadecimal string public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } */
Subclasses often override the toString method to return the object's attribute information (shortcut: alt + insert), although we can customize it.
When we output an object, the toString() method is called by default
4.finzlize method
finzlize method: When garbage collection determines that there is no longer a reference to this object, the garbage collector calls it on the object.
- When an object is recycled, the finzlize method of the object is automatically called. Subclasses can override this method to do some resource-free operations
- When an object is recycled: When an object has no reference, the jvm considers it a garbage object, the garbage collection mechanism destroys the object, and the finzlize method is called before destroying the object.
- Calls to the garbage collection mechanism are made by the system (i.e., having its own GC algorithm) or by the System.gc() actively triggers the garbage collection mechanism.
Note: The finzlize method is rarely used in actual development, but rather for interviews
3. Packaging Classes
1. Basic data types and corresponding packaging classes:
byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
char -> Character
boolean -> Boolean
These classes are all in java.lang package
2. Significance of Packaging Class:
- Making basic data types object-oriented
- Encapsulates how strings are converted to basic data types (emphasis)
3. Common methods of packaging classes:
-
Integer.parseInt()
-
Long.paseLong()
-
Double.parseDouble()
[Reference Code]
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">Test</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { <span style="color:#008000 ">//Integer I = new Integer(10);//Create wrapper class object </span> <span style="color:#008000 ">//Integer II = 10;// Automatic Packaging </span> <span style="color:#008000 ">//System.out.println(i+10);//In use, int and Integer are virtually identical and can be used with each other </span> <span style="color:#008000">// System.out.println(ii+10);</span> <span style="color:#008000 ">//int J = ii;// Automatic unpacking </span> <span style="color:#008000">// System.out.println(j+100);</span> String a = <span style="color:#a31515">"12"</span>; String b = <span style="color:#a31515">"34"</span>; System.out.println(a+b); <span style="color:#008000">// 1234</span> <span style="color:#008000 ">//Transition: </span> <span style="color:#008000'>//String to int's unique scheme </span> <span style="color:#0000ff">int</span> c = Integer.parseInt(a); <span style="color:#0000ff">int</span> d = Integer.parseInt(b); System.out.println(c+d); <span style="color:#008000">// 46</span> <span style="color:#008000 ">//string to double type </span> String e = <span style="color:#a31515">"1.25"</span>; <span style="color:#0000ff">double</span> f = Double.parseDouble(e); System.out.println(f*6); <span style="color:#008000">// 7.5</span> <span style="color:#008000 ">//to long type </span> <span style="color:#0000ff">long</span> l = Long.parseLong(<span style="color:#a31515">"1234567"</span>); System.out.println(l); } } </code></span></span>
4. Mathematics Classes
Math class methods are static and can be directly referenced - Math. Method ();
Common mathematical class methods:
- abs(): Gets the absolute value
- max(): Maximum
- min(): Find the minimum
- pow(): exponentiation
- round(): rounding
- sqrt(): find the square root
5. Time Class
Java Common Time Classes:
-
Date Date Class
-
Calendar Calendar Class
-
SimpleDateFormat Format Time Class
Date and alendar classes in java. In util package
SimpleDateFormat class in java.text package
1.Date date
[1] new Date() can get the system time
[2] getTime() takes the long form of time and can be used to calculate the time difference
getTime() - Gets the number stored at the bottom of the computer and returns a number that represents the time in milliseconds of long type.
[Reference Code]
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">import</span> java.util.Date; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">Test</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { Date d = <span style="color:#0000ff">new</span> Date(); System.out.println(d); <span style="color:#008000 ">//System Time </span> <span style="color:#008000 ">//get... () - Get the year, month, day.... </ Span> System.out.println(d.getYear()+1900); <span style="color:#008000 ">//span calculated since 1900 </span> System.out.println(d.getMonth()+1); <span style="color:#008000 ">//month from 0 </span> System.out.println(d.getDate()); <span style="color:#008000 ">//days</span> System.out.println(d.getHours());<span style="color:#008000 ">//hour</span> <span style="color:#008000'>//getTime()'- returns long</span in milliseconds of time System.out.println(d.getTime()); } } </code></span></span>
2.Calendar Calendar
[1] get() gets a part of time
[2] set() Set Time - > Calculate Time: The system has been set up for us, there is no need to worry about how many days there are in February, the calculation time is very convenient
Note: The Calendar calendar class is an abstract class, so the new object cannot be removed. Although the abstract class cannot create objects, jdk officially provides an operation on the instance object:
Calendar rightNow = Calendar.getInstance();
We built a Calender object directly from this code
[
Scanning VX for Java, Front End, Testing, python, etc.
Reference code): get() gets a part of the time:
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> date; <span style="color:#0000ff">import</span> java.util.Calendar; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">TestCalendar</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { Calendar cal = Calendar.getInstance(); <span style="color:#008000">// System.out.println(cal);</span> <span style="color:#008000">/* Assume the day: 2021 8 10 */</span> cal.set(Calendar.DATE,cal.get(Calendar.DATE)+31); <span style="color:#008000 ">//Calculate time (in days here)</span> <span style="color:#008000 ">//Get everything in the object created by Calendar </span> System.out.println(cal.get(Calendar.YEAR)); <span style="color:#008000 ">//2021</span> System.out.println(cal.get(Calendar.MONTH)+1); <span style="color:#008000 ">//month: results from 0: October</span> System.out.println(cal.get(Calendar.DATE)); <span style="color:#008000 ">//day</span> System.out.println(cal.get(Calendar.HOUR_OF_DAY));<span style="color:#008000 ">//hour</span> System.out.println(cal.get(Calendar.MINUTE)); System.out.println(cal.get(Calendar.SECOND)); } } </code></span></span>
[Reference code]: set() Set time - > Calculate time:
Note: cal.setTime(d); convert Date to Calendar
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> date; <span style="color:#0000ff">import</span> java.util.Calendar; <span style="color:#0000ff">import</span> java.util.Date; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">TestCalendar</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { Date d = <span style="color:#0000ff">new</span> Date(); Calendar cal = Calendar.getInstance(); cal.setTime(d);<span style="color:#008000 ">//Convert Date to Calendar</span> System.out.println(cal); System.out.println(cal.get(Calendar.YEAR)); <span style="color:#008000 ">//year</span> System.out.println(cal.get(Calendar.MONTH)+1); <span style="color:#008000 ">//month: 0-based </span> System.out.println(cal.get(Calendar.DATE)); <span style="color:#008000 ">//day</span> } } </code></span></span>
3.SimpleDateFormat Format Time
Date, Calendar can also format time by reference, but it is cumbersome, and the SimpleDateFormat class is a tool class designed to help us format time. It is in java. In the text package.
[Time Format]: yyyy-MM-dd HH:mm:ss
The SimpleDateFormat class has two common methods:
[1]format(Date):
format(Date) helps us convert time to a string in the format set when the SimpleDateFormat class defines objects
[Reference Code]
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> Simple; <span style="color:#0000ff">import</span> java.text.SimpleDateFormat; <span style="color:#0000ff">import</span> java.util.Date; <span style="color:#0000ff">import</span> java.util.logging.SimpleFormatter; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">Test</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) { Date d = <span style="color:#0000ff">new</span> Date(); System.out.println(d); <span style="color:#008000 ">//Thu Aug 1208:40:08 CST 2021 is ugly </span> <span style="color:#008000 ">//Set formatting time mode, we commonly use yyyy-MM-dd HH:mm:ss mode</span> SimpleDateFormat sdf = <span style="color:#0000ff">new</span> SimpleDateFormat(<span style="color:#a31515">"yyyy-MM-dd HH:mm:ss"</span>);<span style="color:#008000 ">//time format </span> String s = sdf.format(d); <span style="color:#008000 ">//Formatting Time </span> System.out.println(s); <span style="color:#008000">// 2021-08-12 08:45:09</span> } } </code></span></span>
[2]parse(String):
parse(String) helps us convert strings to time
[Reference Code]
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> Simple; <span style="color:#0000ff">import</span> java.text.ParseException; <span style="color:#0000ff">import</span> java.text.SimpleDateFormat; <span style="color:#0000ff">import</span> java.util.Date; <span style="color:#0000ff">import</span> java.util.Scanner; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">Test2</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) <span style="color:#0000ff">throws</span> ParseException { Scanner sc = <span style="color:#0000ff">new</span> Scanner(System.in); System.out.println(<span style="color:#A31515 ">" Please enter a time (yyyy-MM-dd HH:mm:ss): "</span>"; String s = sc.nextLine(); SimpleDateFormat sdf = <span style="color:#0000ff">new</span> SimpleDateFormat(<span style="color:#a31515">"yyyy-MM-dd HH:mm:ss"</span>); Date d = sdf.parse(s); <span style="color:#008000 ">//Convert String to Time </span> System.out.println(d); <span style="color:#008000">/* Please enter a time (yyyy-MM-dd HH:mm:ss): 2021-08-12 12:25:21 Thu Aug 12 12:25:21 CST 2021 */</span> } } </code></span></span>
Note: Since the strings entered by the user are not necessarily in the format we want, it may be anything, and it is impossible to convert them to time. You cannot convert a person to time, so there is a great risk that the unhandled (exception: java.text.ParseException) will be required to handle the exception.
4. Calculate time difference
Calculation ideas:
- Formatting time
- Convert string to long type time first
- Calculate millisecond level time difference, take absolute value
- Millisecond level time difference to second level
- Time difference in seconds to minute level
- Minute level time difference converted to xx hours xx minutes
[Reference Code]
<span style="color:#23263b"><span style="background-color:#f5f5fa"><code class="language-java"><span style="color:#0000ff">package</span> Simple; <span style="color:#0000ff">import</span> java.text.ParseException; <span style="color:#0000ff">import</span> java.text.SimpleDateFormat; <span style="color:#0000ff">import</span> java.util.Date; <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#a31515">TestDiff</span> { <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> <span style="color:#a31515">main</span>(String[] args) <span style="color:#0000ff">throws</span> ParseException { String s1 = <span style="color:#a31515">"2021-08-12 12:00:00"</span>; <span style="color:#008000 ">//start time</span> String s2 = <span style="color:#a31515">"2021-08-12 14:35:00"</span>; <span style="color:#008000 ">//end time</span> <span style="color:#008000 ">//Formatting Time </span> SimpleDateFormat sdf = <span style="color:#0000ff">new</span> SimpleDateFormat(<span style="color:#a31515">"YYYY-MM-dd HH:mm:ss"</span>); <span style="color:#008000 ">//Convert string to time form </span> Date d1 = sdf.parse(s1); Date d2 = sdf.parse(s2); <span style="color:#008000 ">//Calculate time difference: Get time in milliseconds (long type) before making a difference </span> <span style="color:#0000ff">long</span> long1 = d1.getTime(); <span style="color:#0000ff">long</span> long2 = d2.getTime(); <span style="color:#0000ff">long</span> diffTime = Math.abs(long1 - long2); <span style="color:#008000 ">//sec level time difference </span> <span style="color:#0000ff">long</span> diffSec = diffTime / 1000; <span style="color:#008000 ">//Grading Time Difference </span> <span style="color:#0000ff">long</span> diffMin = diffSec / 60; <span style="color:#008000 ">//Show xx hours xx minutes </span> <span style="color:#0000ff">long</span> displayHours = diffMin / 60; <span style="color:#008000 ">//hour</span> <span style="color:#0000ff">long</span> displayMin = diffMin % 60; <span style="color:#008000 ">//min</span> System.out.println(<span style="color:#a31515">"You have been studying for:"</span>+displayHours+<span style="color:#a31515">"hour"</span>+displayMin+<span style="color:#A31515 ">" minutes "</span>"; } } </code></span></span>
6. String Classes
Common String Class Methods
Method Summary:
Types of modifiers and return values | Method Name | explain |
---|---|---|
char | charAt() | Get a character at a location |
String | concat() | The stitching of strings. Ordinary string splicing just adds up |
boolean | contains() | Determines whether the original string contains an xxx string, often used in the judgment of substrings |
boolean | endsWith() | Determines whether the original string ends with an xxx string |
boolean | startsWith() | Determines whether the original string begins with an xxx string |
boolean | equals() | Determine if the contents of both strings are the same; == Determine if the addresses are the same |
boolean | equalsIgnoreCase() | Ignore case to determine whether the contents of two strings are the same |
int | indexOf() | Calculates where the first occurrence of a given string occurs |
int | LastindexOf() | Calculates the last occurrence of a given string |
int | length() | Calculate the length of a string |
String | replace() | Replacement of string contents |
String[] | split() | String cutting, resulting in an array of strings |
String | substring() | String intercept, left closed, right open: [] |
String | trim() | Remove spaces on the left and right sides of the string, not in the middle |
static String | valueOf() | Official: Basic data type to string operation; Direct: variable + "" |
Note: String is an immutable type (final class), and almost all string operations return a new string instead of modifying it on the original basis.
[Sample Code]
public class Test { public static void main(String[] args) { String s = "My name is Li Hua"; s.concat("hhh"); // Split on string s, splice HHH System.out.println(s);// My name is Li Hua //String is an immutable data type //Almost all string operations return a new string String s1 = s.concat("hhh"); // Split on string s, splice HHH System.out.println(s1);// My name is Li Hua hhh String str1 = "Li Hua likes to watch Teacher Luo's video"; str1.replace("Li Hua", "Zhang San"); System.out.println(str3); // Li Hua likes to watch Mr. Luo's video without substituting strings for the same str1 or str1 String str2 = str1.replace("Li Hua", "Zhang San"); // Almost all string operations return a new string New string to be joined with a new variable System.out.println(str2);// Zhang San likes to watch Mr. Luo's video } }
package String; import java.util.Scanner; public class Test { public static void main(String[] args) { String s = "My name is Li Hua"; System.out.println(s.charAt(0)); // Get the character at position 0 s.concat("hhh"); System.out.println(s);// My name is Li Hua //String is an immutable data type //Almost all string operations return a new string String s1 = s.concat("hhh"); // Split on string s, splice HHH System.out.println(s1);// My name is Li Hua hhh System.out.println(s.contains("Li Hua"); // true System.out.println(s.contains("Oxford"); // false System.out.println("Invite Li Hua to an English Salon Event"); // true to determine whether to end with xxx System.out.println("Invite Li Hua to an English Salon". startsWith("Li Hua");// false decides whether to start with xxx // equals string content is the same //Li Hua, who accepts the invitation to participate in the event, must enter the verification code when he arrives at the scene // String yanZhengMa = "AAkm"; // // Scanner sc = new Scanner(System.in); // // System.out.println("Please enter the verification code ("+yanZhengMa+)"); // // String userInput = sc.nextLine(); // // if(yanZhengMa.equalsIgnoreCase("aakm"){// Ignore case to determine if the contents on both sides are the same // System.out.println("Welcome to the English Salon Event!"); // }else{ // System.out.println("You are not invited, please sign up on site!"); // } // String str = "Li Hua has a good time!"; // System.out.println(str.indexOf("happy"); // 5 calculates where the first occurrence of a string occurs String str2 = "Li Hua did well"; System.out.println (str2.length()); //6 calculates the length of the string String str3 = "Li Hua likes to watch Teacher Luo's video"; str3.replace("Li Hua", "Zhang San"); System.out.println(str3); //Li Hua likes to watch Teacher Luo's video and does not replace strings that are either invariant str3 or str3 String str4 = str3.replace("Li Hua", "Zhang San"); //Almost all string operations return a new string New string to be connected with a new variable System.out.println(str4); //Zhang San likes to watch Teacher Luo's video String str5 = "Ha-ho-ho-ho-hee-ho-no"; String[] ss = str5.split("");// cutting System.out.println(ss[0]);//haha System.out.println(ss[1]);//haha System.out.println(ss[2]);//Hip-Hop System.out.println(ss[3]); //ohno String str6 = "Good weather today"; System.out.println(str6.substring(2,4)); //Weather String Interception [] Left Close Right Open, Not Right String str7 = "Ha-ha"; System.out.println(str7.trim()); // Remove the left and right blanks int i = 10; System.out.println(String.valueOf(i)); // Basic data type to string System.out.println(i+ ");// Amateurs } }
7. String Builder and String Buffer
Disadvantages of String classes:
String is an immutable data type that produces a new string for each stitch, and sooner or later memory will be filled with the stitched strings.
Differences between String and StringBuilder and StringBuffer classes:
StringBuilder and StringBuffer: Variable strings, do not produce new objects, save memory. StringBuffer and StringBuilder are recommended for large number of string splicing, but they are implemented almost the same way as String.
StringBuffer and StringBuilder classes:
[Similarity]
They are used the same way and can be considered a class
[Difference]
-
StringBuffer thread-safe, StringBuilder non-thread-safe.
-
StringBuilder has a speed advantage over StringBuffer. StringBuilder classes are recommended in most cases, but must be used when thread security is required
String splicing method: append() method
StringBuffer and StringBuilder to String class:
StringBuilder sb = new StringBuilder("Cats like fish"); String s = sb.toString();
[Reference Code]
package String; public class TestStringBuilder { public static void main(String[] args) { StringBuilder sb = new StringBuilder();// An empty string "" StringBuilder sb2 = new StringBuilder("Cats like fish"); System.out.println(sb2);// Cats like to eat fish sb2.append(', dogs like fish'); System.out.println(sb2);// Additional cats like fish and dogs like fish sb2.insert(1,'Ha-ha'); System.out.println(sb2); // Cats like fish and dogs like fish //Operation huan'c above //Convert StringBuilder to String String s = sb2.toString(); System.out.println(s); // Cats like fish and dogs like fish //All of the above can replace StringBuilder with StringBuffer, and the result is the same } }
8. DecimalFormat
DecimalFormat: Format decimals, leaving a few decimal places. Associate with formatting time.
. Represents a decimal point
0 and # represent digits, reserve a few digits just as 0 or #
[Reference Code]
import java.text.DecimalFormat; import java.util.Scanner; public class Test { public static void main(String[] args) { double d= 10/3.0; System.out.println(d);//3.3333333333333335 //. Represents a decimal point // 0 and #for numbers //Keep two decimal formats DecimalFormat DF = new DecimalFormat ('.00'); // Or. ## String s = df.format(d); // Convert d to the format set above System.out.println(s);//3.33 } }
summary
In a flash, this term is almost over again. After a long time of busy homework, I finally integrated all the small points of knowledge I learned! Hope it will help you to study on the way forward!