Home > Java > javaTutorial > body text

Common classes that you must know in java

零下一度
Release: 2017-07-20 16:35:57
Original
1379 people have browsed it

Why do package classes appear?

Basic data types do not have the characteristics of objects. For example, basic types cannot call methods and have simple functions. In order for basic data types to also have the characteristics of objects, Java provides a wrapper class for each basic data type, so that basic data types can be manipulated like objects. Each basic type has a corresponding packaging class:

1. Packaging class

I believe that all of you are very familiar with basic data types, such as int, float, double, boolean, Char et al. Basic data types do not have the characteristics of objects. For example, basic types cannot call methods and have simple functions. . . , In order for basic data types to also have the characteristics of objects, Java provides a wrapper class for each basic data type, so that we can operate basic data types like objects.

Correspondence between basic types and packaging classes:

Note: There are two packaging classes with special names. One is Integer and the other is Character, other basic data types are capitalized.

The packaging class mainly provides two categories of methods:

1. Methods for converting this type and other basic types

2. Converting strings to this type and Methods for converting wrapper classes to each other ;>>>>>>>>>>>>>>>>>>

Basic types in Java Conversion between basic types and packaging classes

It is often necessary to convert between basic types and packaging classes, taking Integer as an example (the operations of other packaging classes are similar):

1 Integer a=new Integer(3);//定义Integer包装类对象,值为32 int b=a+5;//将对象和基本类型进行运算
Copy after login

After the introduction of the automatic boxing and unboxing mechanism in JDK1.5, the conversion between wrapper classes and basic types becomes easier and more convenient.
So what are packing and unboxing? Let’s take a look at them separately:

Boxing:

Convert the basic type into a packaging class so that it has the properties of an object, which can be divided into manual boxing and automatic boxing.

1 int i=10;//定一个int基本数据类型2 Integer x=new Integer(i);//手动装箱3 Integer y=i;//自动装箱
Copy after login

1 Double n=i;//类型不同不能自动装箱2 Double m=new Double(i);//不同类型可以通过手动装箱
Copy after login
Unboxing:
Contrary to boxing, the packaging class object is converted into a basic type value, which can be divided into manual Unboxing and automatic unboxing.

1 Integer j=new Integer(8);//定义Integer包装类对象,值为82 int n=j.intValue();//手动拆箱3 int m=j;//自动拆箱
Copy after login

1 double x=j.doubleValue();//不同类型手动拆箱2 double y=j;//不同类型可以自动拆箱
Copy after login
Note
:

different types cannot be automatically boxed, but different types can be automatically unpacked box. >>>>>>>>>>>>>>>>>>>>> ;>>>>>>>>>>>>>>>

The difference between basic types and strings in Java Conversion

In program development, we often need to convert between basic data types and strings.

Among them,

basic types are converted to strings

There are three methods:

1. Use the toString() method of the wrapper class

2. Use String The valueOf() method of the class

3. Add an empty string to the basic type, and the result is the string corresponding to the basic type data

The code is as follows:

1 //将基本类型转化为字符串2 int x=10;3 String str1=Integer.toString(x);//方法一4 String str2=String.valueOf(x);//方法二5 String str3=x+"";//方法三,本质利用系统自动转换类型
Copy after login

Let’s look at it again, there are two ways to convert character
strings into basic types
:

1. Call the parseXxx static method of the packaging class

2 . Call the valueOf() method of the wrapper class to convert it to a basic type of wrapper class, which will automatically unbox it

The code is as follows:

1 //将字符串转换为基本类型2 String str="8";3 int n=Integer.parseInt(str);//方法一4 int y=Integer.valueOf(str);//方法二
Copy after login

Note: Strings are converted to basic types If the string contains other characters in the type, an exception will be thrown when the program is running. Therefore, it is best to use try-catch statements to capture and process when using this method.
PS: The conversion between other basic types and strings is not listed one by one here, the methods are similar.

2. Date and SimpleDateFormat classes


In program development, we often need to process date and time related data. At this time, we can use the Date class in the java.util package. The main function of this class is to

get the current time

. Let’s take a look at the use of the Date class:

1 Date d=new Date();//使用默认的构造方法创建Date对象2 System.out.println(d);
Copy after login

使用 Date 类的默认无参构造方法创建出的对象就代表当前时间,我们可以直接输出 Date 对象显示当前的时间,显示的结果如下:

其中, Thu 代表 星期四, Jul 代表 七月,06 代表 06 号, CST 代表 China Standard Time (中国标准时间,也就是北京时间,东八区)。

从上面的输出结果中,我们发现,默认的时间格式不是很友好,与我们日常看到的日期格式不太一样,如果想要按指定的格式进行显示,如 2017-07-06 13:31:28 ,那该怎么做呢?

此时就到了 java.text 包中的 SimpleDateFormat 类大显身手的时候了!!可以使用 SimpleDateFormat 来对日期时间进行格式化,如可以将日期转换为指定格式的文本,也可将文本转换为日期。

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

1. 使用 format() 方法将日期转换为指定格式的文本

1 //使用 format() 方法将日期转换为指定格式的文本2 Date d=new Date();//使用默认的构造方法创建Date对象3 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//指定日期格式4 String today=sdf.format(d);5 System.out.println(today);
Copy after login

运行结果:

结果分析:

代码中的 “yyyy-MM-dd HH:mm:ss” 为预定义字符串, yyyy 表示四位年, MM 表示两位月份, dd 表示两位日期, HH 表示小时(使用24小时制), mm 表示分钟, ss 表示秒,这样就指定了转换的目标格式,最后调用 format() 方法将时间转换为指定的格式的字符串。

2. 使用 parse() 方法将文本转换为日期

Common classes that you must know in java
 1                 //创建日期格式的字符串 2         String day="2017年07月06日 13:42:10"; 3         //创建SimpleDateFormat对象,指定字符串的日期格式 4         SimpleDateFormat sd=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); 5         //调用parse方法,将字符串转化为日期 6         Date date; 7         try { 8             date = sd.parse(day); 9             System.out.println(date);10         } catch (ParseException e) {11             // TODO Auto-generated catch block12             e.printStackTrace();13         }
Copy after login
Common classes that you must know in java

运行结果:

结果分析:

代码中的 “yyyy年MM月dd日 HH:mm:ss” 指定了字符串的日期格式,调用 parse() 方法将文本转换为日期。因为将字符串转换为Date类型可能会抛出异常,所以要用try-catch语句捕获。

一定要注意哦:

1、 调用 SimpleDateFormat 对象的 parse() 方法时可能会出现转换异常,即 ParseException ,因此需要进行异常处理。

2、 使用 Date 类时需要导入 java.util 包,使用 SimpleDateFormat 时需要导入 java.text 包。


三、Calendar 类的应用

Date 类最主要的作用就是获得当前时间,同时这个类里面也具有设置时间以及一些其他的功能,但是由于本身设计的问题,这些方法却遭到众多批评,不建议使用,更推荐使用 Calendar 类进行时间和日期的处理。

java.util.Calendar 类是一个抽象类,可以通过调用 getInstance() 静态方法获取一个 Calendar 对象,此对象已由当前日期时间初始化,即默认代表当前时间,如 Calendar c = Calendar.getInstance();

那么如何使用 Calendar 获取年、月、日、时间等信息呢?我们来看下面的代码:

Common classes that you must know in java
 1 public static void main(String[] args)  { 2         // TODO Auto-generated method stub 3          Calendar c = Calendar.getInstance();//创建Calendar对象 4          int year = c.get(Calendar.YEAR);//获取年 5          int month = c.get(Calendar.MONTH)+1;//获取月份,0表示一月份 6          int day = c.get(Calendar.DAY_OF_MONTH);//获取日期 7          int hour = c.get(Calendar.HOUR_OF_DAY);//获取小时 8          int minute = c.get(Calendar.MINUTE);//获取分钟 9          int second = c.get(Calendar.SECOND);//获取秒10          System.out.println("当前时间:"+year+"-"+month+"-"+day+"-"+hour+":"+minute+":"+second);11     
12     }
Copy after login
Common classes that you must know in java

运行结果:

结果分析:

调用 Calendar 类的 getInstance() 方法获取一个实例,然后通过调用 get() 方法获取日期时间信息,参数为需要获得的字段的值, Calendar.Year 等为 Calendar 类中定义的静态常量。

注意:其中有两个特别的参数:DAY_OF_MONTH和HOUR_OF_DAY,千万不要写成DAY和HOUR了;MONTH获取的月份,0表示一月

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Calendar 类提供了 getTime() 方法,用来获取 Date 对象,完成 Calendar 和 Date 的转换,还可通过 getTimeInMillis() 方法,获取此 Calendar 的时间值,以毫秒为单位。如下所示:

1  Date date=c.getTime();//将Calendar对象转换为Date对象2          Long time=c.getTimeInMillis();//获取当前毫秒数3          System.out.println("当前时间:"+date);4          System.out.println("当前毫秒数"+time);
Copy after login

运行结果:

总结:

 1.通过调用 getInstance() 静态方法获取一个 Calendar 对象---对象初始化

  Calendar c = Calendar.getInstance();

2.通过调用 get() 方法获取日期时间信息

  int month=c.get(Calendar.MONTH)+1;----0表示1月份

3.提供 getTime() 方法,用来获取 Date 对象

  Date date=c.getTime();----将Calender对象转换为Date对象

4.通过 getTimeInMillis() 方法,获取此 Calendar 的时间值

  long time=c.getTimeInMillis();----获取当前毫秒


四、使用 Math 类操作数据

Math 类位于 java.lang 包中,包含用于执行基本数学运算的方法, Math 类的所有方法都是静态方法,所以使用该类中的方法时,可以直接使用类名.方法名,如: Math.round();

常用的方法:

下面用代码来实现:

Common classes that you must know in java
 1 public static void main(String[] args)  { 2         double a=12.81; 3         int b=(int)a;//强制类型转换 4         System.out.println("强制类型转换:"+b); 5         long c=Math.round(a);//调用round方法,进行四舍五入 6         System.out.println("四舍五入:"+c); 7         double d=Math.floor(a);//调用floor方法,返回小于参数的最大整数 8         System.out.println("floor方法:"+d); 9         double e=Math.ceil(a);//调用ceil方法,返回大于参数的最小整数10         System.out.println("ceil方法:"+e);11         double x=Math.random();//调用random方法,产生[0,1)之间的随机数12         System.out.println("随机数:"+x);13         int y=(int)(Math.random()*100);//产生[0,100)之间的随机数14         System.out.println("[0,100)之间的随机数:"+y);15 
16     }
Copy after login
Common classes that you must know in java

运行结果:

注意:要注意Math各个方法返回值类型,可以用强制类型转换来转为自己想要的类型。

PS: Math 类还提供了许多其他方法,各位小伙伴们可以按需去API文档查找想要知道的方法。

The above is the detailed content of Common classes that you must know in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!