search

JavaAPI

Nov 19, 2016 am 10:21 AM
java

》JavaAPI

  文档注释可以在:类,常量,方法上声明

  文档注释可以被javadoc命令所解析并且根据内容生成手册

package cn.fury.se_day01;
/**
 * 文档注释可以在:类,常量,方法上声明
 * 文档注释可以被javadoc命令所解析并且根据内容生成手册
 * 这个类用来测试文档注释
 * @author soft01
 * @version 1.0
 * @see java.lang.String
 * @since jdk1.0
 *
 */
public class APIDemo {
    public static void main(String[] args){
        System.out.println(sayHello("fury"));
    }
    /**
     * 问候语,在sayHello中被使用
     */
    public static final String INFO = "你好!";
    /**
     * 将给定的用户名上添加问候语
     * @param name 给定的用户名
     * @return  带有问候语的字符串
     */
    public static String sayHello(String name){
        return INFO+name;
    }
}

测试代码

》字符串是不变对象:字符串对象一旦创建,内容就不可更改

  》》字符串对象的重用

  **要想改变内容一定会创建新对象**

  TIP: 字符串若使用字面量形式创建对象,会重用以前创建过的内容相同的字符串对象。

  重用常量池中的字符串对象:就是在创建一个字符串对象前,先要到常量池中检查是否这个字符串对象之前已经创建过,如果是就会进行重用,如果否就会重新创建

package cn.fury.test;

public class Test{
    public static void main(String[] args) {
        String s1 = "123fury"; //01
        String s2 = s1; //02
        String s3 = "123" + "fury"; //03
        String s4 = "warrior";
        System.out.println(s1 == s2);
        System.out.println(s3 == s1);
        System.out.println(s4 == s1);
    }
}

/**
 * 01 以字面量的形式创建对象:会重用常量池中的字符串对象
 * 02 赋值运算:是进行的地址操作,所以会重用常量池中的对象
 * 03 这条语句编译后是:String s3 = "123fury";
 */

字符串对象的重用
package cn.fury.se_day01;
/**
 * 字符串是不变对象:字符串对象一旦创建,内容是不可改变的,
 *         **要想改变内容一定会创建新对象。**
 * 
 * 字符串若使用字面量形式创建对象,会重用以前创建过的内容相同的字符串对象。
 * @author soft01
 *
 */
public class StringDemo01 {
    public static void main(String[] args) {
        String s1 = "fury123";
//        字面量赋值时会重用对象
        String s2 = "fury123";
//        new创建对象时则不会重用对象
        String s3 = new String("fury123");
        /*
         * java编译器有一个优化措施,就是:
         * 若计算表达式运算符两边都是字面量,那么编译器在生成class文件时
         * 就会将结果计算完毕并保存到编译后的class文件中了。
         * 
         * 所以下面的代码在class文件里面就是:
         * String s4 = "fury123";
         */
        String s4 = "fury" + "123"; //01
        String s5 = "fury";
        String s6 = s5 + "123"; //02
        String s7 = "fury"+123; //01
        String s8 = "fu"+"r"+"y"+12+"3";
        
        String s9 = "123fury";
        String s10 = 12+3+"fury";  //编译后是String s10 = "15fury";
        String s11 = '1'+2+'3'+"fury"; //03
        String s12 = "1"+2+"3"+"fury";
        String s13 = 'a'+26+"fury"; //04
        
        System.out.println(s1 == s2); //true
        System.out.println(s1 == s3); //false
        System.out.println(s1 == s4); //true
        System.out.println(s1 == s6); //false
        System.out.println(s1 == s7); //true
        System.out.println(s1 == s8); //true
        System.out.println(s9 == s10); //false
        System.out.println(s9 == s11); //false
        System.out.println(s9 == s12); //true
        System.out.println(s9 == s13); //true
        /*
         * 用来验证03的算法
         */
        int x1 = '1';
        System.out.println(x1);
        System.out.println('1' + 1);
        /*
         * 用来验证04的算法
         */
        int x2 = 'a';
        System.out.println(x2);
        System.out.println('a' + 26);
//        System.out.println(s10);
    }
}

/*
 * 01 编译完成后:String s4 = "fury123";  因此会重用对象
 * 02 不是利用字面量形式创建对象,所以不会进行重用对象
 * 03 '1'+2  的结果不是字符串形式的12,而是字符1所对应的编码加上2后的值
 * 04 'a'+26 的结果是字符a所对应的编码值再加上26,即:123
 */

list

  》》字符串长度

    中文、英文字符都是按照一个长度进行计算

package cn.fury.se_day01;
/**
 * int length()
 * 该方法用来获取当前字符串的字符数量,
 * 无论中文还是英文每个字符都是1个长度
 * @author soft01
 *
 */
public class StringDemo02 {
    public static void main(String[] args) {
        String str = "hello fury你好Java";
        System.out.println(str.length());
        
        int [] x = new int[3];
        System.out.println(x.length);
    }
}

字符串的长度

  》》子串出现的位置

public int indexOf(String str) {
        return indexOf(str, 0);
    }

    /**
     * Returns the index within this string of the first occurrence of the
     * specified substring, starting at the specified index.
     *
     * <p>The returned index is the smallest value <i>k</i> for which:
     * <blockquote><pre class="brush:php;toolbar:false">
     * <i>k</i> >= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
     * 
     * If no such value of k exists, then {@code -1} is returned.      *      * @param   str         the substring to search for.      * @param   fromIndex   the index from which to start the search.      * @return  the index of the first occurrence of the specified substring,      *          starting at the specified index,      *          or {@code -1} if there is no such occurrence.      */     public int indexOf(String str, int fromIndex) {         return indexOf(value, 0, value.length,                 str.value, 0, str.value.length, fromIndex);     } 方法解释
package cn.fury.se_day01;
/**
 * int indexOf(String str)
 * 查看给定字符串在当前字符串中的位置
 * 首先该方法会使用给定的字符串与当前字符串进行全匹配
 * 当找到位置后,会将给定字符串中第一个字符在当前字符串中的位置返回;
 * 没有找到就返回  **-1**
 * 常用来查找关键字使用
 * @author soft01
 *
 */
public class StringDemo03 {
    public static void main(String[] args) {
        /*
         * java编程思想:  Thinking in Java
         */
        String str = "thinking in java";
        int index = str.indexOf("java");
        System.out.println(index);
        index = str.indexOf("Java");
        System.out.println(index);
        /*
         * 重载方法:
         *         从给定位置开始寻找第一次出现给定字符串的位置
         */
        index = str.indexOf("in", 3);
        System.out.println(index);
        /*
         * int lastIndexOf(String str)
         * 返回给定的字符串在当前字符串中最后一次出现的位置
         */
        int last = str.lastIndexOf("in");
        System.out.println(last);
    }
}

方法应用

  》》截取部分字符串

    String substring(int start, int end)

Open Declaration   String java.lang.String.substring(int beginIndex, int endIndex)


Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. 

Examples: 

 "hamburger".substring(4, 8) returns "urge"
 "smiles".substring(1, 5) returns "mile"
 
Parameters:beginIndex the beginning index, inclusive.endIndex the ending index, exclusive.Returns:the specified substring.Throws:IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

方法解释
package cn.fury.se_day01;
/**
 * String substring(int start, int end)
 * 截取当前字符串的部分内容
 * 从start处开始,截取到end(但是不含有end对应的字符)
 * 
 * java API有个特点,凡是使用两个数字表示范围时,通常都是“含头不含尾”
 * @author soft01
 *
 */
public class StringDemo04 {
    public static void main(String[] args) {
        String str = "www.oracle.com";
        
        //截取oracle
        String sub = str.substring(4, 10);
        System.out.println(sub);
        
        /*
         * 重载方法,只需要传入一个参数,从给定的位置开始连续截取到字符串的末尾
         */
        sub = str.substring(4);
        System.out.println(sub);
    }
}

方法应用
package cn.fury.test;

import java.util.Scanner;

/**
 * 网址域名截取
 * @author Administrator
 *
 */
public class Test{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入网址:");
        String s1 = sc.nextLine();
        int index1 = s1.indexOf(".");
        int index2 = s1.indexOf(".", index1 + 1);
        String s2 = s1.substring(index1 + 1, index2);
        System.out.println("你输入的网址是:");
        System.out.println(s1);
        System.out.println("你输入的网址的域名为:");
        System.out.println(s2);
    } 
}

实际应用

  》》去除当前字符串中两边的空白

    String trim()
    去除当前字符串中两边的空白

Open Declaration   String java.lang.String.trim()


Returns a string whose value is this string, with any leading and trailing whitespace removed. 

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than &#39;\u005Cu0020&#39; (the space character), then a reference to this String object is returned. 

Otherwise, if there is no character with a code greater than &#39;\u005Cu0020&#39; in the string, then a String object representing an empty string is returned. 

Otherwise, let k be the index of the first character in the string whose code is greater than &#39;\u005Cu0020&#39;, and let m be the index of the last character in the string whose code is greater than &#39;\u005Cu0020&#39;. A String object is returned, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m + 1). 

This method may be used to trim whitespace (as defined above) from the beginning and end of a string.
Returns:A string whose value is this string, with any leading and trailing white space removed, or this string if it has no leading or trailing white space.

方法解释
package cn.fury.se_day01;
/**
 * String trim()
 * 去除当前字符串中两边的空白
 * @author soft01
 *
 */
public class StringDemo06 {
    public static void main(String[] args) {
        String str1 = "  Keep Calm and Carry on.        ";    
        System.out.println(str1);
        String str2 = str1.trim();  //01
        System.out.println(str2);
        System.out.println(str1 == str2);  //02
    }
}

/*
 * 01 改变了内容,因此创建了新对象,所以02的输出结果为false
 */

方法应用

  》》查看指定位置的字符

    char charAt(int index)

    返回当前字符串中给定位置处对应的字符

Open Declaration   char java.lang.String.charAt(int index)


Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. 

If the char value specified by the index is a surrogate, the surrogate value is returned.

Specified by: charAt(...) in CharSequence
Parameters:index the index of the char value.Returns:the char value at the specified index of this string. The first char value is at index 0.Throws:IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

方法解释
package cn.fury.se_day01;
/**
 * char charAt(int index)
 *  返回当前字符串中给定位置处对应的字符
 * @author soft01
 *
 */
public class StringDemo07 {
    public static void main(String[] args) {
        String str = "Thinking in Java";
//        查看第10个字符是什么?
        char chr = str.charAt(9);
        System.out.println(chr);
        
        /*
         * 检查一个字符串是否为回文?
         */
    }
}

方法应用
package cn.fury.test;

import java.util.Scanner;

public class Test{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一个字符串(第三个字符必须是字符W):");
        while(true){
            String s1 = sc.nextLine();
            if(s1.charAt(2) == &#39;W&#39;){
                System.out.println("输入正确");
                break;
            }else{
                System.out.print("输入错误,请重新输入。");
            }
        }
    } 
}

实际应用
package cn.fury.se_day01;
/*
 * 判断一个字符串是否是回文数:个人觉得利用StringBuilder类中的反转方法reverse()更加简单
 */
public class StringDemo08 {
    public static void main(String[] args) {
        /*
         * 上海的自来水来自海上
         * 思路:
         *         正数和倒数位置上的字符都是一致的,就是回文
         */
        String str = "上海自水来自海上";
        System.out.println(str);
//        myMethod(str);
        teacherMethod(str);
    }

    private static void teacherMethod(String str) {
        for(int i = 0; i < str.length() / 2; i++){
            if(str.charAt(i) != str.charAt(str.length() - 1 - i)){
                System.out.println("不是回文");
                /*
                 * 方法的返回值类型是void时,可以用return来结束函数
                 * return有两个作用
                 *         1 结束方法
                 *         2 将结果返回
                 * 但是若方法返回值为void时,return也是可以单独使用的,
                 * 用于结束方法
                 */
                return;
            }
        }
        System.out.println("是回文");
    }

    private static void myMethod(String str) {
        int j = str.length() - 1;
        boolean judge = false;
        for(int i = 0; i <= j; i++){
            if(str.charAt(i) == str.charAt(j)){
                judge = true;
                j--;
            }else{
                judge = false;
                break;
            }
        }
        if(judge){
            System.out.println("是回文");
        }else
        {
            System.out.println("不是回文");
        }
    }
}

实际应用2_回文数的判断

 》》开始、结束字符串判断

     boolean startsWith(String star)

     boolean endsWith(String str)

    前者是用来判断当前字符串是否是以给定的字符串开始的,
    后者是用来判断当前字符串是否是以给定的字符串结尾的。

package cn.fury.se_day01;
/**
 * boolean startsWith(String star)
 * boolean endsWith(String str)
 * 前者是用来判断当前字符串是否是以给定的字符串开始的,
 * 后者是用来判断当前字符串是否是以给定的字符串结尾的。
 * @author soft01
 *
 */
public class StringDemo09 {
    public static void main(String[] args) {
        String str = "thinking in java";
        System.out.println(str.startsWith("th"));
        System.out.println(str.endsWith("va"));
    }
}

方法应用

  》》大小写转换

    String toUpperCase()

    String toLowerCase()

    作用:忽略大小写
    应用:验证码的输入

package cn.fury.se_day01;
/**
 * 将一个字符串中的英文部分转换为全大写或者全小写
 * 只对英文部分起作用
 * String toUpperCase()
 * String toLowerCase()
 * 
 * 作用:忽略大小写
 * 应用:验证码的输入
 * @author soft01
 *
 */
public class StringDemo10 {
    public static void main(String[] args) {
        String str = "Thinking in Java你好";
        System.out.println(str);
        System.out.println(str.toUpperCase());
        System.out.println(str.toLowerCase());
    }
}

方法应用
package cn.fury.test;

import java.util.Scanner;

public class Test{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入验证码(F1w3):");
        while(true){
            String s1 = sc.nextLine();
            if(s1.toLowerCase().equals("f1w3")){
                System.out.println("验证码输入正确");
                break;
            }else{
                System.out.print("验证码码输入错误,请重新输入:");
            }
        }
    }
}

实际应用_验证码判断

 》》静态方法valueOf()

    该方法有若干的重载,用来将其他类型数据转换为字符串 ;常用的是将基本类型转换为字符串

package cn.fury.test;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        int x = 123;
        System.out.println(x);
        String s1 = "123";
        String s2 = String.valueOf(x);    //02
        String s3 = x + "";    //01
        System.out.println(s1 == s2);
        System.out.println(s1.equals(x));
        System.out.println("===========");
        System.out.println(s1.equals(s3));
        System.out.println(s1.equals(s2));
    }
}

/**
 * 01 02 的效果是一样的,但是02的速度快
 */

方法应用

》利用StringBuilder进行字符串的修改

  StringBuilder内部维护了一个可变的字符数组,从而保证了无论修改多少次字符串内容,都是在这个数组中完成;当然,若数组内容被超出,会扩容;但是与字符串的修改相比较,内存上的消耗是明显要少很多的。

package cn.fury.se_day01;
/**
 * StringBuilder内部维护了一个可变的字符数组
 * 从而保证了无论修改多少次字符串内容,都是在这个数组中完成
 * 当然,若数组内容被超出,会扩容;但是与字符串的修改相比较,内存上的消耗是明显要少很多的
 * 其提供了用于修改字符串内容的常用修改方法:
 *         增:append
 *         删:delete
 *         改:replace
 *         插:insert
 * @author soft01
 *    
 */
public class StringBuilderDemo01 {
    public static void main(String[] args) {
        System.out.println("===start===");
        String str = "You are my type.";
        System.out.println(str);
        
        /*
         * 若想修改字符串,可以先将其变换为一个
         * StringBuilder类型,然后再改变内容,就不会再创建新的对象啦
         */
        System.out.println("===one===");
        StringBuilder builder = new StringBuilder(str);
        //追加内容
        builder.append("I must stdy hard so as to match you.");
        //获取StringBuilder内部表示的字符串
        System.out.println("===two===");
        str = builder.toString();
        System.out.println(str);
        //替换部分内容
        System.out.println("===three===");
        builder.replace(16, builder.length(),"You are my goddness.");
        str = builder.toString();
        System.out.println(str);
        //删除部分内容
        System.out.println("===four===");
        builder.delete(0, 16);
        str = builder.toString();
        System.out.println(str);
        //插入部分内容
        System.out.println("===five===");
        builder.insert(0, "To be living is to change world.");
        str = builder.toString();
        System.out.println(str);
        
        //翻转字符串
        System.out.println("===six===");
        builder.reverse();
        System.out.println(builder.toString());
        //利用其来判断回文
    }
}

常用方法应用
package cn.fury.se_day01;

public class StringBuilderDemo02 {
    public static void main(String[] args) {
//        StringBuilder builder = new StringBuilder("a"); //高效率
//        for(int i = 0; i < 10000000; i++){
//            builder.append("a");
//        }
        String str = "a";  //低效率
        for(int i = 0; i < 10000000; i++){
            str += "a";
        }
    }
}

/*
 * 疑问:字符串变量没改变一下值就会重新创建一个对象吗??
 *             答案:是的,因为字符串对象是不变对象
 */

与字符串连接符“+”的效率值对比

》作业

  生成一个包含所有汉字的字符串,即,编写程序输出所有汉字,每生成50个汉字进行换行输出。在课上案例“测试StringBuilder的append方法“的基础上完成当前案例。

package cn.fury.work.day01;
/**
 * 生成一个包含所有汉字的字符串,即,编写程序输出所有汉字,每生成50个汉字进行换
 * 行输出。在课上案例“测试StringBuilder的delete方法“的基础上完成当前案例。
 * @author soft01
 *
 */
public class Work03 {
    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder();
        /*
         * 中文范围(unicode编码):
         * \u4e00 ------ \u9fa5
         */
        System.out.println(builder.toString());
        System.out.println("=======");
        char chr1 = &#39;\u4e00&#39;;
        System.out.println(chr1);
        String str = "\u4e00";
        System.out.println(str);
        
        for(char chr = &#39;\u4e00&#39;, i = 1; chr <= &#39;\u9fa5&#39;; chr++,i++){
            builder.append(chr);
            if(i % 50 == 0){
                builder.append("\n");
            }
        }
        
        System.out.println(builder.toString());
    }
}


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software