Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

03 Java API Documentation

Lecture 3 Java API Documentation

Uploaded by

hlaomr980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

03 Java API Documentation

Lecture 3 Java API Documentation

Uploaded by

hlaomr980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Advanced Programming Applications

Lecture 3
Java API Documentation

CCS2304
Using Classes from the Java Library
• You will frequently use the classes in the Java library to
develop programs.

• The java library is known as java Application Programming


Interface (API)

• For convenience, classes in java are grouped in packages based


on their purposes.

• Documentation for this API can be downloaded or browsed


online.

• Documentation for Javafx packages is downloaded


separately.

2
Package
Built-in Packages
• A package is a collection of related classes. User-defined Packages

• If the class belongs to a certain package, the file should be in a


folder with the same name as package (directory name must
match the package name).

• A class can only be in one package.

• Placing the package declaration at the top of your source file


includes these classes in a package with the name that you
specify.
package graphics;
Ex: package graphics; Class Button {…}

• If no package is explicitly declared, Java places your classes into


a default package containing all files in the same folder.

The Java platform provides an enormous class library, organized as packages.


This library is known as the “Application Programming Interface” (API).

3
Using Classes from the Java Library

4
Using Classes from the Java Library

5
Using Classes from the Java Library

6
Using Classes from the Java Library

7
Using Classes from the Java Library

Search for your request

8
Java API Packages (a subset)
java.lang
The Java Language Package contains classes and interfaces that are required by many
Java programs. This package is imported by the compiler into all programs.

java.util
The Java Utilities Package contains utility classes and interfaces, such as date and time
manipulations, random-number processing capabilities with class Random, Data
structures
javax.swing
The Java Swing GUI Components Package contains classes and interfaces for Java’s
Swing GUI components that provide support for portable GUIs. (still functional but being
replaced by javafx)

java.net
The Java Networking Package contains classes that enable programs to communicate via
networks .
java.sql
Provides the API for accessing and processing data stored in a data source (usually a
relational database) using the JavaTM programming language..

9
Import Statements
• A Class full name is its package name.class name.
• import statements specify the packages of the classes used in
your Java programs.
Without import
javax.swing.JApplet x = …

With import
import javax.swing.JApplet;

JApplet x =

• You can have any number of import statements.


• You can import all classes in a package using (*).
Ex: import java.util.*;

• java.lang package is imported by the compiler into all programs.

10
class java.lang.Math

import java.lang.Math;

public class Test {


public static void main (String [] args) {
int a = Math.abs(-4);
System.out.println("a = “ + a);
int b = Math.round(4.6f);
int c = Math.max(4, 7);
double d = Math.random();
}
}

11
class javax.swing.JOptionPane
Package: javax.swing
Class JOptionPane
public static void showMessageDialog(Component parentComponent, Object message)

Brings up an information-message dialog titled "Message".


public static String showInpotDialog(Component parentComponent, Object message)

Shows a question-message dialog requesting input from the user.

12
class javax.swing.JOptionPane
import javax.swing.JOptionPane;

public class WelcomeInMessageDialogBox {


public static void main (String [] args) {
String name = JOptionPane.showInputDialog(null, “Plz enter your name”);
JOptionPane.showMessageDialog(null, “Welcome ” + name + “ to Java!”);
}
}

13
class java.util.Random
Constructor
Random()
Methods

public int nextInt(int n)

Returns a pseudorandom, uniformly distributed int value between 0


(inclusive) and the specified value (exclusive)

import java.util.Random;

public class Test {


public static void main (String [] args) {
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
int x = rnd.nextInt(11);
System.out.println(“x= “ + x);
}
}
}
14
class java.util.Scanner
Java.util.Scanner
public Scanner(InputStream source) Constructs a new Scanner that
produces values scanned from the specified input stream.

Hint: System.in represents the Console

public int nextInt()

Scans the next token of the input as an int.

public double nextDouble()

Scans the next token of the input as a double.

15
class java.util.Scanner
import java.util. Scanner;

class ScannerDemo {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);

System.out.println(“Please Enter first number”);


int num1 = scan.nextInt();

System.out.println(“Please Enter Second number”);


int num2 = scan.nextInt();

int sum = num1 + num2;


System.out.println(“The sum of ” + num1 +“ and ” + num2 + “ = ” + sum);
}
}

16
class java.lang.String
• The java.lang.String class encapsulate a sequence of
characters as a string.

• Constructing a String:
– String message = "Welcome to Java“;
– String message = new String("Welcome to Java“);

• Dealing with a String


– Obtaining string length and retrieving individual characters in a
string
– String concatenation (concat)
– Substrings (substring(index), substring(start, end))
– Comparisons (equals, compareTo)
– Finding a character or a substring in a string
– String conversions
o Conversions between strings and arrays
o Converting characters and numeric values to strings

17
Constructing Strings
• String newString = new String(stringLiteral);

String message = new String("Welcome to Java");

• Since strings are used frequently, Java provides a


shorthand initializer for creating a string:
– String message = "Welcome to Java";

18
Strings are Immutable
• A String object is immutable; its contents cannot be
changed.

• If the String doesn’t remain immutable, any hacker can cause a


security issue in the application by changing the reference
value.

• The String is safe for multithreading because of its


immutableness. Different threads can access a single String
instance.

• Does the following code change the contents of the string?


String s = "Java";
s = "HTML";
String s = “hello”; String s1 = “hello”;
s.toUpperCase(); String s2 = s1.toUpperCase();
System.out.println(s); System.out.println(s2);

Displayed: Displayed:
hello HELLO 19
Interned Strings
• Strings are immutable and are frequently used, to
improve efficiency and save memory.

• The JVM uses the same instance for string literals with
the same character sequence.

• Such an instance is called interned.


– It is a process where strings with the same contents are
stored as a single instance in the Java string pool, which is a
pool of strings maintained by the Java Virtual Machine
(JVM).

20
Examples
String s1 = “Welcome to Java”;
String s2 = new String(“Welcome to Java”);
String s3 = “Welcome to Java”;

System.out.println(“s1 == s2 is ” + (s1 == s2));


System.out.println(“s1 == s2 is ” + (s1 == s3));

Displayed:
s1 == s2 is false
s1 == s3 is true

• A new object is created if you use the new operator.

• If you use the string initializer, no new object is created if the


interned object is already created.

21
String Comparisons
Returns true if this string is equal to string s1.

Returns true if this string is equal to string s1


case insensitive.

Returns an integer greater than 0, equal to 0,


or less than 0 to indicate whether this string is
greater than, equal to, or less than s1.

Same as compareTo except that the


comparison is case insensitive.

Returns true if the specified subregion of this


string exactly matches the specified
subregion in string s1.

Same as the preceding method except that


you can specify whether the match is case
sensitive.

Returns true if this string starts with the


specified prefix.

Returns true if this string ends with the


specified suffix.
22
Replacing and Splitting Strings
Returns a new string with all characters
converted to lowercase.

Returns a new string with all characters


converted to uppercase.

Returns a new string with whitespace


characters trimmed on both sides.

Returns a new string that replaces all


matching characters in this string with
the new character.

Returns a new string that replaces the


first matching substring in this string
with the new substring.

Returns a new string that replaces all


matching substrings in this string with
the new substring.

Returns as array of strings consisting of


the substrings split by the delimiter.
23
Obtaining Substrings
Returns this string’s substring that
begins with the character at the
specified beginIndex and extends to the
end of the string.

Returns this string’s substring that


begins at the specified beginIndex and
extends to the character at index
endIndex -1. Note that the character at
endIndex is not part of the substring.

24
Getting String Length and Characters, and
Combining Strings
Returns the number of characters in
this string.

Returns the character at the specified


index from this string.

Returns a new string that concatenates


this string with string s1.

25
Finding a Character or a Substring in a String

26
Formatting Strings
Returns a formatted string using the specified format string
and arguments.
• The String class contains the static format method to create a
formatted string.
• The syntax to invoke this method is:
String.format(format, item1, item2, ..., itemk)
• This method is similar to the printf method except that the
format method returns a formatted string, whereas the printf
method displays a formatted string.
Ex:
String s = String.format("%7.2f%6d%-4s", 45.556, 14, "AB");
System.out.println(s);

Displays:

2 6 4

7
27
StringBuilder and StringBuffer
• The StringBuilder/StringBuffer class is an alternative to
the String class.

• A StringBuilder/StringBuffer can be used wherever a


string is used. StringBuilder/StringBuffer is more flexible
than String.

• You can add, insert, or append new contents into a string


buffer, whereas the value of a String object is fixed
once the string is created.

• StringBuffer is Thread Safe while StringBuilder is not.

28
StringBuilder Constructors
java.lang.StringBuilder

+ StringBuilder()
+ StringBuilder(capacity: int)
+ StringBuilder(s: String)

• Constructs an empty string builder with capacity 16.


• Constructs a string builder with the specified capacity.
• Constructs a string builder with the specified string.

29
Modifying Strings in the Builder

30
Examples
StringBuilder strBuilder = new StringBuilder(“Welcome to Java”);

W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

strBuilder.delete(8, 11) changes the builder to Welcome Java

strBuilder.deleteCharAt(8) changes the builder to Welcome o Java

strBuilder.reverse() changes the builder to avaJ ot emoclew

strBuilder.replace(11, 15, “HTML”) changes the builder to Welcome to HTML

strBuilder.setCharAt(0, ‘W’) sets the builder to welcome to Java

31
Wrapper Class
public void m(Object obj) {
}

Java SE 10 [2018] There is


speculation of removing
primitive data types!

Primitive value Integer myInteger = new Integer(5);


Int x = 5;
Object of class Integer
5
Primitive Type Wrapper Class

boolean Boolean int Integer


byte Byte long Long
char Character short Short
float Float double Double

32
The Integer and Double Classes

33
Methods for Parsing Strings into Numbers
• The parseInt method in the Integer class parse a numeric
string into an int value and the parseDouble method in the
Double class to parse a numeric string into a double value.

• Each numeric wrapper class has two overloaded parsing


methods to parse a numeric string into an appropriate numeric
value.
// These two methods are in the Integer class
public static int parseInt(String s)
public static int parseInt(String s, int radix)

// These two methods are in the Double class


public static double parseDouble(String s)
public static double parseDouble(String s, int radix)

34
Automatic Conversion Between Primitive
Types and Wrapper Class Types
• Converting a primitive value to a wrapper object is called
boxing. The reverse conversion is called unboxing. Java allows
primitive types and wrapper classes to be converted
automatically.

• The compiler will automatically box a primitive value that


appears in a context requiring an object and will unbox an
object that appears in a context requiring a primitive value. This
is called autoboxing and autounboxing.

Auto-boxing

Auto-unboxing

35
Any Questions?

36
Why Strings Are Immutable

37
StringBuilder and StringBuffer

38
Wrapper Class
There are certain needs for using the Wrapper class in Java as
mentioned below:
1. They convert primitive data types into objects. Objects are needed if we
wish to modify the arguments passed into a method (because primitive
types are passed by value).

2. The classes in java.util package handles only objects and hence wrapper
classes help in this case also.

3. Data structures in the Collection framework, such as ArrayList and


Vector, store only objects (reference types) and not primitive types.

4. An object is needed to support synchronization in multithreading.

Advantages of Wrapper Classes


1. Collections allowed only object data.
2. On object data we can call multiple methods compareTo(), equals(),
toString()
3. Cloning process only objects
4. Object data allowed null values.
5. Serialization can allow only object data.
39
ASCII Table

40

You might also like