search
HomeJavajavaTutorialHow to use Java API?
How to use Java API?Apr 23, 2023 pm 08:19 PM
javaapi

    1.API

    1.1API Overview

    • What is API

    API (Application Programming Interface): Application Programming Interface

    • The API

    in java refers to the one provided in the JDK Java classes with various functions encapsulate the underlying implementation. We don't need to care about how these classes are implemented. We only need to learn how to use these classes. We can learn how to use these APIs through the help documentation.

    1.2 Specific use of API help documentation

    • Open the help documentation

    How to use Java API?

    • Find the input box in the Index tab

    How to use Java API?

    • ##Enter Random

      # in the input box

    How to use Java API?##Look at which package the class is under

    How to use Java API?

      Look at the description of the class

    How to use Java API?

    ##See the construction method

    How to use Java API?

    Look at member methods

    2.String classHow to use Java API?

    2.1String class overview

    String The class represents a string, and all string literals in a Java program (such as "abc") are implemented as instances of this class. That is, all double-quoted strings in Java programs are objects of the String class. The String class is under the java.lang package, so there is no need to import the package when using it!

    2.2 Characteristics of the String class

    Strings are immutable and their values ​​cannot be changed after creation
    • Although String values ​​are immutable, but they can be shared
    • A string is effectively equivalent to a character array (char[]), but the underlying principle is a byte array (byte[] )
    • 2.3Construction method of String class

    Commonly used construction methods

    How to use Java API?

    Sample code
    • public class StringDemo01 {
    • public static void main(String[] args) {
    //public String(): Create a blank string object without any content

    String s1 = new String();
    System.out.println("s1:" s1);

    // public String(char[] chs): Create a string object based on the contents of the character array
    char[] chs = {'a', 'b', 'c'};
    String s2 = new String (chs);
    System.out.println("s2:" s2);

    //public String(byte[] bys): Create a string object based on the contents of the byte array
    byte[] bys = {97, 98, 99};
    String s3 = new String(bys);
    System.out.println("s3:" s3);

    / /String s = "abc"; Create a string object by direct assignment, the content is abc
    String s4 = "abc";
    System.out.println("s4:" s4);
    }
    }

    The specific execution results are as follows:

    2.4 The difference between the two ways of creating string objectsHow to use Java API?

    Create through the construction method
    • String objects created through new, each time new will apply for a memory space, although the content is the same, the address value is different

    Create by direct assignment
    • A string given in "" mode, as long as the character sequence is the same (order and case), no matter how many times it appears in the program code , the JVM will only create a String object and maintain it in the string pool
    2.5 Comparison of strings

    2.5.1 The role of ==

    Compare basic data types: Compare specific values
    • Compare reference data types: Compare object address values
    • 2.5.2 The role of the equals method

    Method introduction
    • public boolean equals(String s) Compares whether the contents of two strings are the same and distinguishes the size

    Sample code

      public class StringDemo02 {
      public static void main(String[] args) {
      //Constructor method to get the object
      char[] chs = {'a' , 'b', 'c'};
      String s1 = new String(chs);
      String s2 = new String(chs);

      //Get the object by direct assignment
      String s3 = "abc";
      String s4 = "abc";

      //Compare whether the string object addresses are the same
      System.out.println(s1 == s2);
      System.out.println(s1 == s3);
      System.out.println(s3 == s4);
      System.out.println("--------");

      //Compare whether the string contents are the same
      System.out.println(s1.equals(s2));
      System.out.println(s1.equals(s3));
      System.out.println(s3.equals(s4));
      }
      }

      The specific execution results are as follows:

      How to use Java API?

      ##2.6 User Login Case

      2.6.1 Case Requirements

      If the user name and password are known, please use a program to simulate user login. A total of three opportunities will be given. After logging in, corresponding prompts will be given

      2.6.2 Code implementation

       <br>

      /*

      Ideas:
      1: Known username and password, definition Two strings can be represented
      2: Enter the user name and password to log in with the keyboard, and use Scanner to implement
      3: Compare the user name and password entered with the keyboard with the known user name and password, and give Corresponding tips. To compare the contents of strings, use the equals() method to implement
      4: Use a loop to achieve multiple opportunities. The number of times here is clear. Use a for loop to implement it, and when the login is successful, use break to end the loop
      */
      public class StringTest01 {
      public static void main(String[] args) {
      //If the username and password are known, just define two string representations
      String username = "itheima";
      String password = "czbk";

      //Use a loop to achieve multiple opportunities. The number of times here is clear. Use a for loop to implement it. When the login is successful, use break to end the loop
      for (int i=0; i
      //Enter the username and password to log in with the keyboard, use Scanner to implement
      Scanner sc = new Scanner(System.in);

      System.out.println("Please enter the user name:");
      String name = sc.nextLine();

      System.out.println("Please enter the password:");
      String pwd = sc.nextLine();

      //Compare the user name and password entered by the keyboard with the known user name and password, and give corresponding prompts. String content comparison is implemented using the equals() method
      if (name.equals(username) && pwd.equals(password)) {
      System.out.println("Login successful");
      break;
      } else {
      if(2-i == 0) {
      System.out.println("Your account is locked, please contact the administrator");
      } else {
      //2,1,0
      //i,0,1,2
      System.out.println("Login failed, you still have" (2 - i) "second chances") ;
      }
      }
      }
      }
      }

      The specific execution results are as follows:

      How to use Java API?

      2.8 Help Document View String common methods

      ##3.StringBuilder class
      Method name

      Description

      public boolean equals(Object anObject)

      Compare the contents of strings, strictly case-sensitive (username and password)

      public char charAt(int index)

      Returns the char value at the specified index

      public int length()

      Return the length of this string

      3.1 Overview of StringBuilder class

      StringBuilder is a variable string class. We can think of it as a container. The variable here means that the content in the StringBuilder object is variable

      3.2 The difference between the StringBuilder class and the String class

        String class: the content is immutable
      • StringBuilder class: the content is mutable Change
      • 3.3Construction method of StringBuilder class

        Commonly used construction methods
      Method nameDescription

      How to use Java API?

      • Sample code

      public class StringBuilderDemo01 {
      public static void main(String[] args) {
      //public StringBuilder(): Create a blank variable string object without any content
      StringBuilder sb = new StringBuilder();
      System.out.println("sb:" sb);
      System.out.println("sb.length():" sb.length());

      //public StringBuilder(String str): Create variable characters based on the content of the string String object
      StringBuilder sb2 = new StringBuilder("hello");
      System.out.println("sb2:" sb2);
      System.out.println("sb2.length():" sb2 .length());
      }
      }

      The specific execution results are as follows:

      How to use Java API?

      3.4 StringBuilder class addition and reverse method

      • Add and reverse method

      How to use Java API?

      • Example code

      public class StringBuilderDemo01 {
      public static void main(String[] args) {
      //Create object
      StringBuilder sb = new StringBuilder();
      //Chain programming
      sb.append("hello").append("world").append("java").append(100);

      System.out.println(" sb:" sb);

      //public StringBuilder reverse(): Returns the reverse character sequence
      sb.reverse();
      System.out.println("sb:" sb);
      }
      }

      The specific execution results are as follows:

      How to use Java API?

      3.5 StringBuilder and String conversion

      • Convert StringBuilder to String

      public String toString(): Convert StringBuilder to String

      • String conversion can be achieved through toString() For StringBuilder

      public StringBuilder(String s): Converting String to StringBuilder can be achieved through the constructor

      • Sample code

      public class StringBuilderDemo02 {
      public static void main(String[] args) {
      String s = sb.toString();
      System.out.println(s);
      String s = "hello";
      StringBuilder sb = new StringBuilder(s);
      System.out.println(sb);
      }
      }

      Specific execution The results are as follows:

      How to use Java API?

      3.6 String splicing upgraded version case

      3.6.1 Case requirements

      Define a method to put int array The data is spliced ​​into a string according to the specified format and returned, the method is called, and the result is output on the console. For example, the array is int[] arr = {1,2,3};, and the output result after executing the method is: [1, 2, 3]

      3.6.2 Code Implementation

       <br>

      /*
      Idea:
      1: Define an array of type int, and use static initialization to complete the initialization of the array elements
      2: Define a method for splicing the data in the int array into a format according to the specified format A string is returned.
      Return value type String, parameter list int[] arr
      3: Use StringBuilder in the method to splice as required, and convert the result into String return
      4: Call the method and use a variable to receive the result
      5: Output results
      */
      public class StringBuilderTest01 {
      public static void main(String[] args) {
      //Define an array of int type and use static initialization to complete the array elements Initialization
      int[] arr = {1, 2, 3};

      //Call the method and use a variable to receive the result
      String s = arrayToString(arr);

      //Output results
      System.out.println("s:" s);

      }

      //Define a method to convert the data in the int array as specified The format is spliced ​​into a string and returns
      /*
      two clear: Return value type: String
      Parameters: int[] arr
      */
      public static String arrayToString(int[] arr ) {
      //Use StringBuilder in the method to splice as required, and convert the result into String and return
      StringBuilder sb = new StringBuilder();

      sb.append("[");

      for(int i=0; iif(i == arr.length-1) {
      sb.append(arr[i]);
      } else {
      sb.append(arr[i]).append(", ");
      }
      }

      sb.append("]");

      String s = sb.toString();

      return s;
      }
      }

      The specific execution results are as follows:

      How to use Java API?

      3.7 View the help documentation for common methods of StringBuilder

      ##Method name

      Description

      public StringBuilder append (any type)

      Add data and return the object itself

      public StringBuilder reverse()

      Returns the reverse character sequence

      public int length()

      Returns the length, the actual stored value

      public String toString()

      You can convert StringBuilder into String through toString()

      The above is the detailed content of How to use Java API?. For more information, please follow other related articles on the PHP Chinese website!

      Statement
      This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
      如何快速把你的 Python 代码变为 API如何快速把你的 Python 代码变为 APIApr 14, 2023 pm 06:28 PM

      提到API开发,你可能会想到DjangoRESTFramework,Flask,FastAPI,没错,它们完全可以用来编写API,不过,今天分享的这个框架可以让你更快把现有的函数转化为API,它就是Sanic。Sanic简介Sanic[1],是Python3.7+Web服务器和Web框架,旨在提高性能。它允许使用Python3.5中添加的async/await语法,这可以有效避免阻塞从而达到提升响应速度的目的。Sanic致力于提供一种简单且快速,集创建和启动于一体的方法

      如何进行XXL-JOB API接口未授权访问RCE漏洞复现如何进行XXL-JOB API接口未授权访问RCE漏洞复现May 12, 2023 am 09:37 AM

      XXL-JOB描述XXL-JOB是一个轻量级分布式任务调度平台,其核心设计目标是开发迅速、学习简单、轻量级、易扩展。现已开放源代码并接入多家公司线上产品线,开箱即用。一、漏洞详情此次漏洞核心问题是GLUE模式。XXL-JOB通过“GLUE模式”支持多语言以及脚本任务,该模式任务特点如下:●多语言支持:支持Java、Shell、Python、NodeJS、PHP、PowerShell……等类型。●WebIDE:任务以源码方式维护在调度中心,支持通过WebIDE在线开发、维护。●动态生效:用户在线通

      PHP8.0中的API客户端库:GuzzlePHP8.0中的API客户端库:GuzzleMay 14, 2023 am 08:54 AM

      随着网络技术的发展,Web应用程序和API应用程序越来越普遍。为了访问这些应用程序,需要使用API客户端库。在PHP中,Guzzle是一个广受欢迎的API客户端库,它提供了许多功能,使得在PHP中访问Web服务和API变得更加容易。Guzzle库的主要目标是提供一个简单而又强大的HTTP客户端,它可以处理任何形式的HTTP请求和响应,并且支持并发请求处理。在

      让机器人学会咖啡拉花,得从流体力学搞起!CMU&amp;MIT推出流体模拟平台让机器人学会咖啡拉花,得从流体力学搞起!CMU&amp;MIT推出流体模拟平台Apr 07, 2023 pm 04:46 PM

      机器人也能干咖啡师的活了!比如让它把奶泡和咖啡搅拌均匀,效果是这样的:然后上点难度,做杯拿铁,再用搅拌棒做个图案,也是轻松拿下:这些是在已被ICLR 2023接收为Spotlight的一项研究基础上做到的,他们推出了提出流体操控新基准FluidLab以及多材料可微物理引擎FluidEngine。研究团队成员分别来自CMU、达特茅斯学院、哥伦比亚大学、MIT、MIT-IBM Watson AI Lab、马萨诸塞大学阿默斯特分校。在FluidLab的加持下,未来机器人处理更多复杂场景下的流体工作也都

      Vue3 Composition API怎么优雅封装第三方组件Vue3 Composition API怎么优雅封装第三方组件May 11, 2023 pm 07:13 PM

      前言对于第三方组件,如何在保持第三方组件原有功能(属性props、事件events、插槽slots、方法methods)的基础上,优雅地进行功能的扩展了?以ElementPlus的el-input为例:很有可能你以前是这样玩的,封装一个MyInput组件,把要使用的属性props、事件events和插槽slots、方法methods根据自己的需要再写一遍://MyInput.vueimport{computed}from&#39;vue&#39;constprops=define

      设计API接口时,要注意这些地方!设计API接口时,要注意这些地方!Jan 09, 2023 am 11:10 AM

      本篇文章给大家带来了关于API的相关知识,其中主要介绍了设计API需要注意哪些地方?怎么设计一个优雅的API接口,感兴趣的朋友,下面一起来看一下吧,希望对大家有帮助。

      Windows 11 正在获得一项新的 API 支持的功能来解决网络问题Windows 11 正在获得一项新的 API 支持的功能来解决网络问题Apr 20, 2023 pm 02:28 PM

      当您的WindowsPC出现网络问题时,问题出在哪里并不总是很明显。很容易想象您的ISP有问题。然而,Windows笔记本电脑上的网络并不总是顺畅的,Windows11中的许多东西可能会突然导致Wi-Fi网络中断。随机消失的Wi-Fi网络是Windows笔记本电脑上报告最多的问题之一。网络问题的原因各不相同,也可能因Microsoft的驱动程序或Windows而发生。Windows是大多数情况下的问题,建议使用内置的网络故障排除程序。在Windows11

      SpringBoot怎么实现api加密SpringBoot怎么实现api加密May 15, 2023 pm 11:10 PM

      SpringBoot的API加密对接在项目中,为了保证数据的安全,我们常常会对传递的数据进行加密。常用的加密算法包括对称加密(AES)和非对称加密(RSA),博主选取码云上最简单的API加密项目进行下面的讲解。下面请出我们的最亮的项目rsa-encrypt-body-spring-boot项目介绍该项目使用RSA加密方式对API接口返回的数据加密,让API数据更加安全。别人无法对提供的数据进行破解。SpringBoot接口加密,可以对返回值、参数值通过注解的方式自动加解密。什么是RSA加密首先我

      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

      AI Hentai Generator

      AI Hentai Generator

      Generate AI Hentai for free.

      Hot Article

      R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
      2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
      Repo: How To Revive Teammates
      4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
      Hello Kitty Island Adventure: How To Get Giant Seeds
      4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

      Hot Tools

      Dreamweaver Mac version

      Dreamweaver Mac version

      Visual web development tools

      Safe Exam Browser

      Safe Exam Browser

      Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

      Zend Studio 13.0.1

      Zend Studio 13.0.1

      Powerful PHP integrated development environment

      SAP NetWeaver Server Adapter for Eclipse

      SAP NetWeaver Server Adapter for Eclipse

      Integrate Eclipse with SAP NetWeaver application server.

      SublimeText3 English version

      SublimeText3 English version

      Recommended: Win version, supports code prompts!