This is the 21st day of my participation in the August Text Challenge.More challenges in August
preface
This article is learning Java in the process of knowledge summary, I hope to give you some quick reference.
Hello World
Configure the environment
If the uncompressed JDK package is in /home/cunyu/soft/jdk-11.0.7, add the following configuration to the /etc/profile file:
JAVA_HOME = /home/cunyu/soft/jdk11.07.
PATH = $JAVA_HOME/bin:$PATH
Copy the code
The command line runs the program
#compile
javac HelloWorld.java
#run
java HelloWorld
Copy the code
object-oriented
Classes and objects
public class Item{
/ / item name
String name;
/ / price
int price;
public static void main(String[] args){
Item hp = new Item();
hp.name = "Blood bottle";
hp.price = 50;
Item shoes = new Item();
shoes.name = "Straw sandals";
shoes.price = 300;
Item sword = new Item();
sword.name = "Sword";
sword.price = 530; }}Copy the code
methods
public class Item{
/ / item name
String name;
/ / price
int price;
/ / health
float hp;
public legendary(a){
System.out.println("Super god");
}
public float getHp(a){
return hp;
}
public void recovery(float blood){ hp += blood; }}Copy the code
variable
Basic data types
There are eight basic data types
- The integrated
byte
.One byte, eight bitsshort
.Two bytes, 16 bitsint
.Four bytes, 32 bitslong
.8 bytes, 64 bits
- floating-point
float
.Four bytes, 32 bitsdouble
.8 bytes, 64 bits
- character
char
.Two bytes, 16 bits
- The Boolean
boolean
.1 a
literals
The way we assign values to primitive datatype variables is called literals;
Type conversion
Transformation rules
From small to reach automatic turn, from large to small forced turn;
- Conversion from high precision to low precision may lead to overflow;
- Low precision can be converted to high precision;
- Conversions between different data types require casts;
Naming rules and suggestions
- Variable names can only be used
Letters, digits, _, and $
; - The first character of a variable can only be
Letters, $, _
.Can’t bedigital
; - Variable names cannot use keywords, but can contain keywords;
- Use full words, not abbreviations;
block
The part that {} contains in Java is called a block;
scope
- Field, property, Field
When a variable is declared under a class, it is called a Field, or an attribute, a member variable, or a Field, scoped to the entire class from where it was declared;
- parameter
When a variable is declared on a method, it is called a parameter and is scoped to all code in the method, which is inaccessible to other methods and classes.
- A local variable
When a variable is declared in a method, it is called a local variable and is scoped from the declared position to the end of the block.
Final modifier
When a variable is declared with a final modifier, that variable has one and only one assignment;
The operator
Arithmetic operator
+, -, ×, /, %, ++, --
- When different arithmetic units (any length more than
int
), the final return result is calculated according to the longest length; - When different arithmetic units (any length does not exceed
int
) when the final result is returned according toint
Calculation; + + and -
In the front case, we do the calculation first and then evaluate it;After, value first, then calculate;
Relational operator
>, >=, <, <=, ==! =
Logical operator
&, &&, | | |,! , ^
- The difference between long circuit and short circuit: long circuit will operate on both sides of the value of the operator, short circuit when the left side of the operator is false, the right side of the operator is not calculated;
An operator
-
Integer. ToBinaryString (), |, &, ^ ~, < <, > >, > > >
-
>> and >>> difference
>>
It moves all the bits of a positive number to the right and fills in the front0
, will shift all the bits of the negative number to the right and fill in first1
;>>>
Will take the first digit of the negative binary1
Move it to the right, and fill in the front0
, resulting in a positive negative number when unsigned to the right;>>
The positive and negative values of the numbers remain the same.>>>
It’s going to be positive;
Ternary operator
Expression? Value 1:2
, returns 1 when the expression is true; When the expression is false, the value 2 is returned;
Control process
switch
switch
Can be used inByte, short, int, char, String, enum
;- There should be one at the end of each expression
break
; - use
String
The real use of positive numbers is by converting them tohash
Value;
An array of
Create an array
- An array is a fixed length container containing the same type of data.
- If a variable represents an array, it is called a reference.
// Declare a reference
int[] arr;
// Create an array of length 10 and point to it with a reference arr
Copy the code
Initializing an array
- Allocation space is synchronized with assignment
// Allocate an array of length 5 without assigning a value
int[] a = new int[5];
// If there is no assignment, then the default value is used as an array of type int. The default value is 0
System.out.println(a[0]);
// Perform the assignment
a[0] = 100;
a[1] = 101;
a[2] = 103;
a[3] = 120;
a[4] = 140;
Copy the code
- Allocate space and assign
Method 1: allocate space and assign
int[] arr1 = new int[] {100.102.444.836.3236};
2 / / way
int[] arr2 = {100.102.444.836.3236};
// Allocate space and specify content
int[] arr3 = neew int[5] {100.102.444.836.3236};
Copy the code
Sort an array
Selection sort
- Train of thought
First, find the smallest element in the unsorted array and store it in the actual position of the sorted array. Then, find the smallest element from the remaining unsorted elements and place it in the starting position of the sorted array, and so on until all the elements of the array are sorted.
- implementation
/** * select sort *@paramSource unsorted array */
public void selectSort(int[] source){
// Array length
int size = source.lenth;
for(int i = 0; i < size; i++){
for(int j = i + 1; j < size; j++){
// Make an exchange, from small to large
if(source[i] > source[j]){
// Make swaps, from large to small
// if(source[i] < source[j])
inttmp = source[i]; source[i] = source[j]; source[j] = tmp; }}}}Copy the code
Bubble sort
- Train of thought
Through the double-layer loop, the inner loop will compare the two adjacent numbers, the largest number bubble (pairwise exchange) form to the end of the array, each time a maximum value to the end of the array, the outer loop is realized in turn the current maximum transmission, the final realization of sorting;
- implementation
/** * bubble sort *@paramSource unsorted array */
public void bubbleSort(int[] source){
// Array length
int size = source.length;
for(int i = 0; i < size - 1; i++){
for(int j = 0; j < size - 1 - i; j++){
if(source[j] > source[j + 1]) {int tmp = source[j];
source[j] = source[j + 1];
source[j + 1] = tmp; }}}}Copy the code
Copy an array
Once the array is allocated space, it is no longer mutable. When we need to add, delete, change and check the original array, we need to copy the array.
- Copies the value of one array to another
/ * * *@paramSRC Source array *@paramSrcPos The starting position of the source array to copy *@paramDest Destination array *@paramDestPos The starting position of the destination array *@paramLength Indicates the replication length */
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Copy the code
- Merge array
import java.util.Arrays;
** * Created with IntelliJ IDEA. * Version: 1.0 * Author: cunyu * Email: [email protected] * Website: The rain away * https://cunyu1943.github.io * public: village Date: 2020/5/6 at 10:58 * Project: mavenDemo * Package: PACKAGE_NAME * Class: MergeArr * Desc: merge array */
public class MergeArr {
public static void main(String[] args) throws Exception {
int[] arr1 = {1.5.7.9};
int[] arr2 = {0.4.11.45};
int destSize = arr1.length + arr2.length;
int[] mergeArr = new int[destSize];
merge(arr1, arr2, mergeArr);
System.out.println(Arrays.toString(mergeArr));
}
/** * merge array **@paramArr1 source array 1 *@paramArr2 source array 2 *@paramDestArr merged array */
public static void merge(int[] arr1, int[] arr2, int[] destArr) {
// Merge array 1 into the final array
System.arraycopy(arr1, 0, destArr, 0, arr1.length);
// Merge array 2 into the final array
System.arraycopy(arr2, 0, destArr, arr1.length, arr2.length); }}Copy the code
Arrays
methods | function |
---|---|
copyOfRange |
Copy an array |
toString() |
Convert to string |
sort |
The sorting |
binarySearch |
search |
equals |
Check whether it is the same |
fill |
fill |
import java.util.Arrays;
** * Created with IntelliJ IDEA. * Version: 1.0 * Author: cunyu * Email: [email protected] * Website: The rain away * https://cunyu1943.github.io * public: village Date: 2020/5/6 afternoon 1:27 * Project: mavenDemo * Package: PACKAGE_NAME * Class: ArraysOperation * Desc: Arrays common operations */
public class ArraysOperation {
public static void main(String[] args) throws Exception {
int[] arr = {1.9.8.49};
/ / copy
int[] newArr = Arrays.copyOfRange(arr, 0, arr.length);
// Convert to a string
System.out.println(Arrays.toString(newArr));
/ / sorting
Arrays.sort(newArr);
/ / search
System.out.println(Arrays.binarySearch(newArr, 8));
// Compare for equality
System.out.println(Arrays.equals(arr, newArr));
/ / fill
Arrays.fill(arr, 10); System.out.println(Arrays.toString(arr)); }}Copy the code
Classes and objects
inheritance
class Item{
String name;
int price;
}
public class Armor extends Item{
int ac;
public static void main(String[] args) {
Armor a1 = new Armor();
Armor a2 = new Armor();
// Attributes related to cloth armor
a1.name = "Cloth armour";
a1.price = 300;
a1.hjdj =15;
// Attributes associated with the mail
a2.name = Chain mail;
a2.price = 500;
a2.hjdj =40;
}
Copy the code
Method overloading
** Method overload ** means the same method name but different parameter type;
A constructor
The process of building an object from a class is called instantiation, and instantiation is done through constructors; The constructor name is the same as the class name, but there is no return type. By default, a constructor with no arguments is provided. This represents the current object.
public class Hero{
String name;
float hp;
float armor;
int moveSpeed;
Hero(String name, float hp, float armor, int moveSpeed){
this.name = name;
this.hp = hp;
this.armor = armor;
this.moveSpeed = moveSpeed; }}Copy the code
Access modifier
- Common modifiers
symbol | instructions |
---|---|
private |
private |
package/friendly/default |
By default, |
protected |
The protected |
public |
public |
- Modifier scope
Their own | Like the steamed stuffed bun | Different types of steamed buns | With the class | Other classes | |
---|---|---|---|---|---|
private |
access | Can’t inherit | Can’t inherit | Don’t have access to | Don’t have access to |
package/friendly/default |
access | inheritance | Can’t inherit | access | Don’t have access to |
protected |
access | inheritance | inheritance | access | Don’t have access to |
public |
access | inheritance | inheritance | access | access |
- Decorator usage scenarios
- Attributes are usually used with
private
Encapsulation; - Methods are generally used
public
Easy to call; - Methods that can be inherited, usually with
protected
; package
Less use;- Principle: scope of action as small as possible;
- Attributes are usually used with
Class attribute
-
Definition: When an attribute of a class is modified static, it is called a class attribute. When an attribute is declared as a class attribute, all objects share a value.
-
Object properties: also called instance properties, non-static properties;
-
Object properties vs. class properties:
- The value of the object attribute may vary from object to object, but the value of the class attribute of all objects is the same;
- If a property is not the same for all objects, it should be designed as an object property because it follows the object.
- If an object is shared by all objects alike, the property should be designed as a class property.
-
access
Object. Class attributes
:teemo.hp
;Class. Class attributes
:Hero.hp
, recommended use;
Class method
- Class method: also known asA static method,
static
Accessor class methods,No objectIt can be accessed directly if it exists in a methodNo object properties are invoked, can be designed as a class method; - Object method: also called instance method, non-static method, access to an object method, must be built on the premise of an object, if a method access object properties, then the method must be designed as an object method;
- Class method invocation:
Object. Class method
:teemo.die()
;Class. Class method
:Hero.battleWin()
, recommended use;
Property initialization
- How an object property is initialized :
- Class when the property is declared;
- Class in the constructor;
- Initialization block;
public class Hero{
// declare simultaneous initialization
public String name = "teemo";
protected float hp;
float maxHP;
// Initialize block initialization
{
maxHP = 999;
}
// init in the constructor
public Hero(a){
hp = 100; }}Copy the code
- How a class attribute is initialized :
- Class when the property is declared;
- Static initialization block;
public class Hero{
public String name;
protected float hp;
float maxHP;
// Initialize at declaration time
public static int itemCapacity = 10;
// Statically initialize the block
static{
itemCapacity = 20; }}Copy the code
-
Property initialization block execution order:
Static initializer block -> non-static initializer block -> constructor;
The singleton pattern
- define: also called
Singleton
Pattern, refers to in a class inJVM
, there is only one instance; - Singleton pattern classification:
- The hungry type: create an instance anyway, pass
public static
的getInstance
Method gets an object, each time the same object, belonging toImmediately load, whether the object is used or not; - LanHanShi: only on call
getInstance
Method, each time the same object is retrieved, belonging toLazy loading, is loaded only when the object is used, and hasThread safety;
- The hungry type: create an instance anyway, pass
- Singleton pattern has three elements :
- Privatization of constructors;
- Static attributes point to instances;
public staic
thegetInstance
methods, ** returns the static attribute ** from the previous element;
/** ** hungry */
public class Earth{
// Private constructor that cannot be instantiated externally via new
private Earth(a){}// Define class attributes while initializing
private static Earth instance = new Earth();
// Private static method, used to get objects
public static Earth getInstance(a){
return instance;
}
public static void main(String[] args){
Earth earth1 = Earth.getInstance();
Earth earth2 = Earth.getInstance();
// true
System.out.println(earth1 == earth2)
}
}
Copy the code
/** ** */
public class Earth{
// Private constructor that cannot be instantiated externally via new
private Earth(a){}// Define class attributes
private static Earth instance;
// Private static method, used to get objects
public static Earth getInstance(a){
// Instance does not refer to any object, instantiate it
if(instance == null){
instance = new Earth();
}
return instance;
}
public static void main(String[] args){
Earth earth1 = Earth.getInstance();
Earth earth2 = Earth.getInstance();
// true
System.out.println(earth1 == earth2)
}
}
Copy the code
Enumerated type
- Enumerations are a special class that makes it easy to define constants, usually in all uppercase;
public enum Heros{
TANK,
WIZARD,
ASSASSIN,
WARRIOR,
ASSIST,
RANGED,
PUSH,
FARMING
}
public class Demo{
public static void main(String[] args){
for(Heros hero : Heros.values()){ System.out.println(hero); }}}Copy the code
Interfaces and Inheritance
interface
- Interface cannot be used for instantiation;
- Interface has no constructor;
- The methods in the interface are abstract methods.
- Cannot contain member variables, in addition to
static
和final
Variables; - Interfaces support multiple inheritance;
Transformation of object
Upward transition (subclass to parent, implementation class to interface)
Hero hero = new Hero();
AdHero ad = new AdHero();
hero = ad;
Copy the code
Downward transition (parent to child, interface to implementation class)
Hero hero = new Hero();
AdHero ad = new AdHero();
ad = (AdHero)hero;
Copy the code
rewrite
A subclass can inherit an object method from its parent class, and then provide that method repeatedly. This is called overriding the method, also called override.
class Item{
String name;
int price;
public void buy(a){
System.out.println("Buy");
}
public void effect(a){
System.out.println("Effective after use"); }}public class LifePotion extends Item{
@override
public void effect(a){
System.out.println("Blood bottle returns blood after use."); }}Copy the code
polymorphism
- Operator polymorphisms: The same operator has different effects in different situations, such as
+
The two sides are plastic, then representsNumbers together; If any of them is a string, representsString conjunction; - Conditions required for a class to be polymorphic :
- Superclass (interface) references refer to subclass objects;
- The called method undergoes rewriting;
public interface Mortal{
public void die(a);
}
Copy the code
public class Hero{
public String name;
protected float hp;
public Hero(String name, float hp){
this.name = name;
}
public void kill(Mortal m){
m.die();
}
public static void main(String[] args){
Hero hero = new Hero("Zhaoyun".1000.0 f);
APHero ap = new APHero("Angela".400.0 f);
ADHero ad = new ADHero("Hou yi".450.0 f);
ADAPHero adap = new ADAPHero("Chang e".600.0 f); hero.kill(ad); hero.kill(ap); hero.kill(adap); }}Copy the code
public class ADHero extends Hero implements Mortal{
@override
public void die(a){
System.out.println("AD was killed."); }}Copy the code
public class APHero extends Hero implements Mortal{
@override
public void die(a){
System.out.println("AP was killed."); }}Copy the code
public class ADAPHero extends Hero implements Mortal{
@override
public void die(a){
System.out.println("ADAP was killed."); }}Copy the code
hidden
- Definition: When a parent class and a subclass have an attribute or method of the same name, the parent class’s attribute or method of the same name is formally missing but still exists; That is, the hidden attributes and methods will not be overwritten. When the parent class reference points to the child class object, the hidden attributes or methods will still be called by the parent class, and no dynamic binding will occur.
public class Test {
public static void main(String[] args) {
Circle circle = new Circle();// Class references refer to class objects
Shape shape = new Circle();// Superclass references refer to subclass objects (there will be hiding and overwriting)
System.out.println(circle.name);
circle.printType();
circle.printName();
// These are all methods and references that call the Circle class
System.out.println(shape.name);// Call the hidden name attribute of the parent class
shape.printType();// Call the method of subclass printType
shape.printName();// Call the printName method hidden by the parent class}}class Shape {
public String name = "shape";
public Shape(a){
System.out.println("shape constructor");
}
public void printType(a) {
System.out.println("this is shape");
}
public static void printName(a) {
System.out.println("shape"); }}class Circle extends Shape {
public String name = "circle"; // The superclass attribute is hidden
public Circle(a) {
System.out.println("circle constructor");
}
// Override the parent instance method
public void printType(a) {
System.out.println("this is circle");
}
// Hide static methods from the parent class
public static void printName(a) {
System.out.println("circle"); }}Copy the code
The input result is as follows:
shape constructor
circle constructor
circle
this is circle
circle
shape
this is circle
shape
Copy the code
Object class
toString()
All classes inherit from Object, so all classes have a toString() method that returns a string representation of the current Object;
finalize()
When an object does not have any reference to point to, it meets the conditions of garbage collection. When garbage collection is performed, the Finalize () method of the object will be called by the VIRTUAL machine JVM, and there is no need for the developer to actively call it.
equals()
Used to determine whether two objects have the same content;
= =
A method that is not part of the Object class and is used to determine whether two objects are the same (that is, whether two references refer to the same Object);
hashCode()
The hash value used to return an object;
getClass()
Class object of an object, used mainly for reflection mechanism;
final
- decorator :
final
When modifying a class, it means that the current class does not allow inheritance. - Modification methods :
final
When modifying a method, it means that the method cannot be overridden. - Decorates primitive type variables :
final
When modifying a primitive type variable, it means that the variable has only one assignment; - Modified reference :
final
When modifying a reference, it means that the reference has only one chance to point to an object.
An abstract class
-
Definition: to declare a method in a class that has no concrete implementation and is an “empty” method. When a class has abstract methods, the class must be declared as abstract and cannot be instantiated directly.
-
Differences between interfaces and abstract classes:
- A subclass can implement multiple interfaces, but can inherit only one abstract class;
- Abstract classes can be defined
Public, Package, protected, private, static and non-static properties, final and non-final properties
, butAttributes declared in an interface can only bePublic, static, and final
;
The inner class
-
It can be divided into the following four categories:
- Non-static inner class: defined directly in a class,Can directly access the external class
private
attribute.Inner class instantiation syntax:Inner class object name = new outer class ().new inner class ();
;
package charactor; public class Hero { private String name; / / name float hp; / / health float armor; / / armor int moveSpeed; // Move speed // A non-static inner class is meaningful only if an outer class object exists // Combat scores are only meaningful if a hero object exists class BattleScore { int kill; int die; int assit; public void legendary(a) { if (kill >= 8) System.out.println(name + "Divine!"); else System.out.println(name + "Not yet divine!"); }}public static void main(String[] args) { Hero garen = new Hero(); garen.name = "Galen"; // Instantiate the inner class // BattleScore objects are only meaningful if a hero object exists // So instantiation must be based on an external class object BattleScore score = garen.new BattleScore(a); score.kill = 9; score.legendary(); }}Copy the code
- Static inner classDeclare a static inner class in a class,You cannot access instance properties and methods of an external class, only private static members of the external class.You don’t need an instance of an external class as a base, you can instantiate it directly with the following syntax:
Static inner class object name = new Outer class. Static inner class ();
package charactor; public class Hero { public String name; protected float hp; private static void battleWin(a){ System.out.println("battle win"); } // Enemy crystal static class EnemyCrystal{ int hp=5000; // If the crystal has 0 health, victory is declared public void checkIfVictory(a){ if(hp==0){ Hero.battleWin(); Static inner classes do not have direct access to the object properties of the outer class System.out.println(name + " win this game"); }}}public static void main(String[] args) { // Instantiate the static inner class Hero.EnemyCrystal crystal = newHero.EnemyCrystal(); crystal.checkIfVictory(); }}Copy the code
- An anonymous classIn:Declare a class and instantiate it simultaneouslyWhen an external local variable is used, the variable must be modified to
final
;
package charactor; public abstract class Hero { String name; / / name float hp; / / health float armor; / / armor int moveSpeed; // Move speed public abstract void attack(a); public static void main(String[] args) { ADHero adh=new ADHero(); // By printing adh, you can see that the object adh belongs to the ADHero class adh.attack(); System.out.println(adh); Hero h = new Hero(){ // Implement the attack on the spot public void attack(a) { System.out.println("A new line of attack."); }}; h.attack();// By printing h, you can see that the object h belongs to a class name automatically assigned by the system, Hero$1System.out.println(h); }}Copy the code
- Local class: can be regarded as an anonymous class with a name, the difference between the anonymous class is that the inner class must be declared in the position of the member, that is, the equal position with attributes and methods, while the local class and anonymous class, directly declared in the code block, can be anywhere;
package charactor; public abstract class Hero { String name; / / name float hp; / / health float armor; / / armor int moveSpeed; // Move speed public abstract void attack(a); public static void main(String[] args) { // The difference with anonymous classes is that local classes have custom class names class SomeHero extends Hero{ public void attack(a) { System.out.println( name+ "A new line of attack."); } } SomeHero h =new SomeHero(); h.name ="Diviner"; h.attack(); }}Copy the code
- Non-static inner class: defined directly in a class,Can directly access the external class
-
practice
public abstract class Item{
public abstract void disposable(a);
public static void main(String[] args) throws Exception{
Item item = new Item(){
public void disposable(a){
System.out.println("Disposable"); }}}}Copy the code
The default method
The default method is added from JDK8, which means that concrete methods can be added to the interface (i.e. the default method, declared as default), not only abstract methods.
The final practice
public abstract class Animal{
protected int legs;
protected Animal(int legs){
this.legs = legs;
}
public abstract void eat(a);
public void walk(int legs){
if(legs > 0){
System.out.println("With" + legs + "Walk on one leg.")}}}class Spider extends Animal{
protected Spider(int legs){
super(legs);
}
@Override
public void eat(a){
System.out.println("Spiders eat."); }}public interface Pet{
String name;
public void setName(String name);
public String getName(a);
public void play(a);
}
class Cat extends Animal implements Pet{
String name;
protected Cat(String name){
super(4);
this.name = name;
}
public Cat(a){
this.name = "";
}
@Override
public void eat(a){
System.out.println("The cat is eating the fish.");
}
@Override
public void setName(String name){
this.name = name;
}
@Override
public String getName(a){
return this.name;
}
@Overrid
public void play(a){
System.out.println("The cat is playing with wool."); }}class Fish extends Animal implements Pet{
private String name;
protected Fish(a){
super(0);
}
@Override
public void setName(String name){
this.name = name;
}
@Override
public String getName(a){
return this.name;
}
@Override
public void walk(int legs){
System.out.println("Fish have no legs. They can only swim.");
}
@Override
public void play(a){
System.out.println("Fish chasing tadpoles on water.");
}
@Override
public void eat(a){
System.out.println("Fish eat grass"); }}Copy the code
Numbers and Strings
Split open a case using the
- Basic data types and corresponding encapsulation classes
Basic data types | Wrapper class |
---|---|
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
char |
Character |
boolean |
Boolean |
graph TD
A[Number] --- B[Byte]
A[Number] --- C[Short]
A[Number] --- D[Integer]
A[Number] --- E[Long]
A[Number] --- F[Float]
A[Number] --- G[Double]
- Automatic packing: passes without calling the constructor
=
automaticallyBasic types are converted to encapsulated classesA process called automatic boxing; - Automatic unpacking: You do not need to invoke the corresponding method
=
automaticallyThe wrapper class is converted to a primitive typeThe process is called automatic unpacking; int
Maximum and minimum values of a type:The maximum :Integer.MAX_VALUE
;The minimum value :Integer.MIN_VALUE
;
public class TestNumber{
public static void main(String[] args) throws Exception{
byte byteNum1 = 3;
// Automatic boxing
Byte byteNumClass1 = byteNum1;
// Automatic unpacking
Byte byteNumClass2 = new Byte(byteNum1);
bytebyteNum2 = byteNumClass2; }}Copy the code
String conversion
Numeral to string
- use
String
Class static methodsvalueOf
; - Now wrap the base type into an object and call
toString
Methods; - through
+
The number and""
Connected;
public class Demo{
public void main(String[] args) throws Exception{
int num = 200;
1 / / method
String numString1 = String.valueOf(num);
2 / / method
Integer numClass = new Integer(num);
String numString2 = numClass.toString();
3 / / method
String numString3 = num + ""; }}Copy the code
String to number
- Static methods through each wrapper class
parseXxx
To change;
public class Demo{
public void main(String[] args) throws Exception{
String numString1 = "34";
int num1 = Integer.parseInt(numString1);
String numString2 = "35.34";
floatnum2 = Float.parseFloat(numString2); }}Copy the code
Formatted output
character | meaning |
---|---|
%s |
string |
%d |
digital |
%n |
Line feed (platform independent) |
public class TestNumber {
public static void main(String[] args) {
String name =Caleb "ROM.";
int kill = 8;
String title="Super god";
String sentenceFormat ="%s earned the title % N after making % D kills in a row";
// Printf and format have the same effect
// Format the output with printf
System.out.printf(sentenceFormat,name,kill,title);
// Use format to format outputSystem.out.format(sentenceFormat,name,kill,title); }}Copy the code
- A newline
DOS and Windows
, the end of each line is\r\n
;Linux
, the end of each line is\n
;Mac
, the end of each line is\r
;
- Common formatting methods
import java.util.Locale;
public class TestNumber {
public static void main(String[] args) throws Exception{
int year = 2020;
// Total length, left alignment, complement 0, thousands separator, decimal number, localized expression
// Print the numbers directly
System.out.format("%d%n",year);
// The total length is 8, right aligned by default
System.out.format("%8d%n",year);
// Total length is 8, left justified
System.out.format("%-8d%n",year);
// The total length is 8, not enough to complement 0
System.out.format("%08d%n",year);
// Thousands separator
System.out.format("%,8d%n",year*10000);
// Number of decimal places
System.out.format("%.2f%n",Math.PI);
// Thousands separator for different countries
/ / French
System.out.format(Locale.FRANCE,"%,.2f%n",Math.PI*10000);
/ / the U.S.
System.out.format(Locale.US,"%,.2f%n",Math.PI*10000);
/ / the UK
System.out.format(Locale.UK,"%,.2f%n",Math.PI*10000); }}Copy the code
string
- The way a string is created
- When a literal is present, the virtual machine automatically creates a string.
- call
String
Constructor to create; - Created from a character array;
- through
+
String concatenation;
public class TestString {
public static void main(String[] args) {
// The literal is created
String garen ="Galen";
// constructor created
String teemo = new String("Timothy");
// Create from an array of characters
char[] cs = new char[] {'cui'.' ' '.', '};
String hero = new String(cs);
// String concatenation with + plus signString hero3 = garen + teemo; }}Copy the code
-
Strings are final, cannot be inherited, and, once created, cannot be changed (cannot increase length, cannot decrease length, cannot insert characters, cannot delete characters, cannot modify characters);
-
Common methods
methods | Introduction to the |
---|---|
charAt(int index) |
Gets an index position character |
toCharArray() |
Converts a string to an array of characters |
subString(int start, int end) |
Get the index location in[start, end) Substring of |
split(String str) |
Splits a string into an array of strings based on a separator |
trim() |
Remove the leading and trailing Spaces |
toLowerCase() |
All lowercase |
toUpperCase() |
All caps |
indexOf |
The index position at which a character or substring first appears |
lastIndexOf |
The index position of the last occurrence of a character or substring |
contains |
Whether the string contains substrings |
replaceAll |
Replaces the target string with the specified string |
replaceFirst |
Replaces the first target string with the specified string |
startsWith |
Determines whether the string starts as a substring |
endsWith |
Determines whether a string ends in a substring |
- String comparison
Equals () is used to compare whether strings refer to the same object.
Note the exceptions:
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String str2 = new String(str1);
// Check if it is the same string object
System.out.println( str1 == str2); // false
// Check if it is the same string object
System.out.println(str1.equals(str2)); // true
// In this case, when the compiler encounters a string literal, it will use it instead of creating it again
String str3 = "the light";
System.out.println( str1 == str3); // true}}Copy the code
StringBuffer
Unlike String, StringBuffer is a variable length String. It performs better when you need to manipulate strings frequently, as follows:
methods | function |
---|---|
append |
additional |
delete |
delete |
insert |
insert |
reverse |
reverse |
length |
The length of the content |
capacity |
Total space |
public class TestString {
public static void main(String[] args) {
String str1 = "let there ";
// Create a StringBuffer object based on str1
StringBuffer sb = new StringBuffer(str1);
// Append at the end
sb.append("be light");
System.out.println(sb);
// Delete the characters between 4 and 10
sb.delete(4.10);
System.out.println(sb);
// Insert there at position 4
sb.insert(4."there ");
System.out.println(sb);
/ / reverse
sb.reverse();
System.out.println(sb);
// Content length
System.out.println(sb.length());
/ / total spaceSystem.out.println(sb.capacity()); }}Copy the code
The date of
Date formatting
SimpleDateFormat
Class common methods
methods | function |
---|---|
format |
Date transfer string |
parse |
String transfer date |
import java.text.SimpleDateFormat;
import java.util.Date;
/** * date to string */
public class TestDate {
public static void main(String[] args) throws Exception{
/ / y represent the years
/ / M on behalf of the month
/ / d on behalf of the day
//H stands for 24 base hours
//h stands for 12 base hours
//m stands for minutes
/ / s representative seconds
//S stands for milliseconds
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS" );
Date d= new Date();
String str = sdf.format(d);
System.out.println("The current time is formatted as yyyY-MM-DD HH: MM :ss SSS:"+str);
SimpleDateFormat sdf1 =new SimpleDateFormat("yyyy-MM-dd" );
Date d1= new Date();
String str1 = sdf1.format(d1);
System.out.println("Output of the current time formatted in YYYY-MM-DD:"+str1); }}Copy the code
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String[] args) {
SimpleDateFormat sdf =new SimpleDateFormat("yyyy/MM/dd HH:mm:ss" );
String str = "2020/5/1 12:12:12";
try {
Date d = sdf.parse(str);
System.out.printf("The string %s is converted from the format YYYY /MM/ DD HH: MM :ss %n to the date object: %s",str,d.toString());
} catch (ParseException e) {
// TODO Auto-generated catch blocke.printStackTrace(); }}}Copy the code
conclusion
The above is all the content of this article, mainly the summary of the basic content in the process of learning Java, if you think it is helpful to you, then like to pay attention to me!