UNIT 1 RMI Network String
UNIT 1 RMI Network String
UNIT 1 RMI Network String
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.
The RMI provides remote communication between the applications using two objects stub and
skeleton.
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests
are routed through it. When the skeleton receives the incoming request, it does the following
tasks:
AddServerIntf.java
import java.rmi.*;
public interface AddServerIntf extends Remote {
int add(int x, int y) throws RemoteException;
}
AddServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject
implements AddServerIntf{
public AddServerImpl() throws RemoteException {}
public int add(int x, int y) throws RemoteException {
return x+y;
}
}
AddServer.java
import java.rmi.*;
public class AddServer {
public static void main(String[] args) {
try{
AddServerImpl server = new AddServerImpl();
Naming.rebind("registerme",server);
System.out.println("Server is running...");
} catch (Exception e) {
System.out.println(e);
}
}
}
AddClient.java
import java.rmi.*;
public class AddClient {
public static void main(String[] args) {
try{
AddServerIntf client =
(AddServerIntf)Naming.lookup("registerme");
System.out.println("First number is :" + args[0]);
int x = Integer.parseInt(args[0]);
System.out.println("Second number is :" + args[1]);
int y = Integer.parseInt(args[1]);
System.out.println("Sum =" + client.add(x,y));
} catch (Exception e){
System.out.println(e);
}
}
}
Output:
Open a terminal
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
1. Sharing resources
Java Socket programming is used for communication between the applications running on
different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
2. Port number.
Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are being
used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write message. The ServerSocket class is used at server-side.
The accept() method of ServerSocket class blocks the console until the client is connected. After
the successful connection of client, it returns the instance of Socket at server-side.
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.When the connection is made, the server creates a socket object on its end of the
communication. The client and server can now communicate by writing to and reading from the
socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using
sockets:
After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol, so data can be sent across both streams at the same
time. There are following useful classes providing complete set of methods to implement
sockets.
Attempts to create a server socket bound to the specified port. An exception occurs if the port
is already bound by another application.
If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.
Returns the port that the server socket is listening on. This method is useful if you passed
in 0 as the port number in a constructor and let the server find a port for you.
Waits for an incoming client. This method blocks until either a client connects to the
server on the specified port or the socket times out, assuming that the time-out value has
been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely
Sets the time-out value for how long the server socket waits for a client during the
accept().
Binds the socket to the specified server and port in the SocketAddress object. Use this
method if you instantiated the ServerSocket using the no-argument constructor.
When the ServerSocket invokes accept(), the method does not return until a client connects.
After a client does connect, the ServerSocket creates a new Socket on an unspecified port and
returns a reference to this new Socket. A TCP connection now exists between the client and
server, and communication can begin.
The Socket class has five constructors that a client uses to connect to a server. One of them is
shown below:
This method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually
attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and server
have a Socket object, so these methods can be invoked by both the client and server.
Returns the input stream of the socket. The input stream is connected to the output
stream of the remote socket.
Returns the output stream of the socket. The output stream is connected to the input
stream of the remote socket
Closes the socket, which makes this Socket object no longer capable of connecting
again to any server
Client.java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
Socket client = null;
BufferedReader br = null;
try {
System.out.println(args[0] + " " + args[1]);
client = new
Socket(args[0],Integer.parseInt(args[1]));
} catch (Exception e){}
DataInputStream input = null;
PrintStream output = null;
try {
input = new
DataInputStream(client.getInputStream());
output = new PrintStream(client.getOutputStream());
br = new BufferedReader(new
InputStreamReader(System.in));
String str = input.readLine(); //get the prompt
from the server
System.out.println(str);
String filename = br.readLine();
if (filename!=null){
output.println(filename);
}
String data;
while ((data=input.readLine())!=null) {
System.out.println(data);
}
client.close();
} catch (Exception e){
System.out.println(e);
}
}
}
Server.java
import java.net.*;
import java.io.*;
Output
Create a file called testfile.txt in the folder where Client.java and Server.java is located. Add
some content.
MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
MyClient .java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
CharSequence Interface
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
By string literal
By new keyword
String Literal
For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Java String Example 1:
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String objects s1,
s2, and s3 on console using println() method.
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
4 static String format(Locale l, String format, Object... args) It returns formatted string with
given locale.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String
objects are immutable. Immutable simply means unmodifiable or unchangeable.
Example 2
class Testimmutablestring{
public static void main(String args[]){
String s="Java";
s.concat(" Program");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:
Java
Now it can be understood by the diagram given below. Here Java is not changed but a
new object is created with Java Programm. That is why String is known as
immutable.
Here Java is not changed but a new object is created with Java Programm. That is why String is
known as immutable. Two objects are created but s reference variable still refers to "Java" not to
" Java Programm ".
But if we explicitly assign it to the reference variable, it will refer to " Java Programm " object.
For example:
Testimmutablestring1.java
class Testimmutablestring1{
public static void main(String args[]){
String s="Java";
s=s.concat(" Programm");
System.out.println(s);
}
}
Output:
Java Programm
In such a case, s points to the " Java Programm". Please notice that still Java object is not
modified.
As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one
object "Java". If one reference variable changes the value of the object, it will be affected by all
the reference variables. That is why String objects are immutable in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument. Consider, if the String object is
modifiable, the value might be changed and the class that is supposed to be loaded might be
different.
2. Thread Safe:
As the String object is immutable we don't have to take care of the synchronization that is
required while sharing an object across multiple threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further errors by loading the
correct class. This leads to making the application program more secure. Consider an example of
banking software. The username and password cannot be modified by any intruder because
String objects are immutable. This can make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory. When we try to
declare a new String object, the JVM checks whether the value already exists in the String pool
or not. If it exists, the same value is assigned to the new object. This feature allows Java to use
the heap space efficiently.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
2. By Using == Operator
3. By compareTo() Method
The String class equals() method compares the original content of the string. It compares values
of string for equality. String class provides the following two methods:
o public boolean equals(Object another) compares this string to the specified object.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:
true
true
false
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
Example2.java
class Example2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
Output:
false
true
In the above program, the methods of String class are used. The equals() method returns true if
String objects are matching and both strings are of same case. equalsIgnoreCase() returns true
regardless of cases of strings.
2) By Using == operator
Example3.java
class Example3{
public static void main(String args[]){
String s1="Java";
String s2="Java";
String s3=new String("Java");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.
Class stringcomparison{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:
0
1
-1
In Java, String concatenation forms a new String that is the combination of multiple strings.
There are two ways to concatenate strings in Java:
1. By + (String concatenation) operator
2. By concat() method
Java String concatenation operator (+) is used to add strings. For Example:
Concatenation1.java
class Concatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output:
Sachin Tendulkar
In Java, String concatenation is implemented through the StringBuilder (or StringBuffer) class
and it's append method. String concatenation operator produces a new String by appending the
second operand onto the end of the first operand. The String concatenation operator can
concatenate not only String but primitive values also. For Example:
Concatenation2.java
class Concatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
The String concat() method concatenates the specified string to the end of current string. Syntax:
Concatenation3.java
class Concatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Output:
Sachin Tendulkar
The above Java program, concatenates two String objects s1 and s2 using concat() method and
stores the result into s3 object.
Output:
Hello World
In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores the
result of concatenation of s1 and s2 using append() method.
String.format() method allows to concatenate multiple strings using format specifier like %s
followed by the string values or objects.
StrFormat.java
Output:
Hello World
The String.join() method is available in Java version 8 and all the above versions. String.join()
method accepts arguments first a separator and an array of String objects.
StrJoin.java:
Output:
Hello World
In the above code snippet, the String object s stores the result of String.join("",s1,s2) method. A
separator is specified inside quotation marks followed by the String objects or array of String
objects.
4. String concatenation using StringJoiner class (Java Version 8+)
StringJoiner class has all the functionalities of String.join() method. In advance its constructor
can also accept optional arguments, prefix and suffix.
{
public static void main(String args[])
{
StringJoiner s = new StringJoiner(", "); //StringeJoiner object
s.add("Hello"); //String 1
s.add("World"); //String 2
System.out.println(s.toString()); //Displays result
}
}
Output:
Hello, World
In the above code snippet, the StringJoiner object s is declared and the constructor StringJoiner()
accepts a separator value. A separator is specified inside quotation marks. The add() method
appends Strings passed as arguments.
The Collectors class in Java 8 offers joining() method that concatenates the input elements in a
similar order as they occur.
ColJoining.java
import java.util.*;
import java.util.stream.Collectors;
public class ColJoining
{
public static void main(String args[])
{
List<String> liststr = Arrays.asList("abc", "pqr", "xyz"); //List of String array
String str = liststr.stream().collect(Collectors.joining(", ")); //performs joining operation
System.out.println(str.toString()); //Displays result
}
}
Output:
Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() method.
Substring in Java
A part of String is called substring. In other words, substring is a subset of another String. Java
String class provides the built-in substring() method that extract a substring from the given string
by using the index values passed as an argument. In case of substring() method startIndex is
inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
In case of String:
o startIndex: inclusive
o endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. System.out.println(s.substring(0,2)); //returns he as a substring
In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end
index is exclusive).
TestSubstring.java
Output:
The split() method of String class can be used to extract a substring from a sentence. It accepts
arguments in the form of a regular expression.
import java.util.*;
Output:
In the above program, we have used the split() method. It accepts an argument \\. that checks a in
the sentence and splits the string into another string. It is stored in an array of String objects
sentences.
The java.lang.String class provides a lot of built-in methods that are used to manipulate string
in Java. By the help of these methods, we can perform operations on String objects such as
trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a String if you submit any
form in window based, web based or mobile application.
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Output:
JAVA
java
Java
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
Output:
JAVA
JAVA
The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.
Stringoperation3.java
Output:
true
true
Stringoperation4.java
Output:
J
V
The String class length() method returns length of the specified String.
Stringoperation5.java
Output:
When the intern method is invoked, if the pool already contains a String equal to this String
object as determined by the equals(Object) method, then the String from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is returned.
Stringoperation6.java
Output:
Sachin
The String class valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into String.
Stringoperation7.java
Output:
1010
The String class replace() method replaces all occurrence of first sequence of character with
second sequence of character.
Stringoperation8.java
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
public append(String s) It is used to append the specified string with this string. The
synchronized append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float), append(double)
etc.
public insert(int offset, String s) It is used to insert the specified string with this string at the
synchronized specified position. The insert() method is overloaded like
StringBuffer insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public replace(int startIndex, int It is used to replace the string from specified startIndex and
synchronized endIndex, String str) endIndex.
StringBuffer
public delete(int startIndex, int It is used to delete the string from specified startIndex and
synchronized endIndex) endIndex.
StringBuffer
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number of
characters.
public String substring(int beginIndex) It is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, It is used to return the substring from the specified beginIndex
int endIndex) and endIndex.
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
The append() method concatenates the given argument with this String.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
The insert() method inserts the given String with this string at the given position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
The replace() method replaces the given String from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to
endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
The reverse() method of the StringBuilder class reverses the current String.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
The capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.
StringBufferExample6.java
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Java toString() Method
If you want to represent any object as a string, toString() method comes into existence.
If you print any object, Java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object etc.
depending on your implementation.
By overriding the toString() method of the Object class, we can return values of the object, so we
don't need to write much code.
Student.java
class Student{
int rollno;
String name;
String city;
Output:
Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects
but I want to print the values of these objects. Since Java compiler internally calls toString()
method, overriding this method will return the specified values. Let's understand it with the
example given below:
Student.java
class Student{
int rollno;
String name;
String city;
Output:
In the above program, Java compiler internally calls toString() method, overriding this method
will return the specified values of s1 and s2 objects of Student class.
The java string valueOf() method converts different types of values into string. By the help of
string valueOf() method, you can convert int to string, long to string, boolean to string, character
to string, float to string, double to string, object to string and char array to string.
Signature
Let's see an example where we are converting all primitives and objects into strings.
Output:
true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55
The Java String class trim() method eliminates leading and trailing spaces. The Unicode value
of space character is '\u0020'. The trim() method in Java string checks this Unicode value before
and after the string, if it exists then the method removes the spaces and returns the omitted string.
The string trim() method doesn't omit middle spaces.
Signature
The signature or syntax of the String class trim() method is given below:
Returns
The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.
Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:
Returns
Output:
HELLO STRING
The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.
Signature
There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:
The second method variant of toLowerCase(), converts all the characters into lowercase using
the rules of given Locale.
Returns
Output:
The Java String class substring() method returns a part of the string.
We pass beginIndex and endIndex number position in the Java substring method where
beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0,
whereas the endIndex starts from 1.
Signature
public String substring(int startIndex) // type - 1
and
public String substring(int startIndex, int endIndex) // type - 2
If we don't specify endIndex, the method will return all the characters from startIndex.
Parameters
Returns
specified string
Exception Throws
o Either starting or ending index is greater than the total number of characters present in the
string.
The Java String class startsWith() method checks if this string starts with the given prefix. It
returns true if this string starts with the given prefix; else returns false.
Signature
Parameter
offset: the index from where the matching of the string prefix starts.
Returns
true or false
The startsWith() method considers the case-sensitivity of characters. Consider the following
example.
true
true
false
Java String startsWith(String prefix, int offset) Method Example
It is an overloaded method of the startWith() method that is used to pass an extra argument
(offset) to the function. The method works from the passed offset. Let's see an example.
StartsWithExample2.java
Output:
true
false
true
Java String split()
The java string split() method splits this string against given regular expression and returns a
char array.
Signature
Parameter
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching
regex.
The given example returns total number of words in a string excluding space only. It also
includes special characters.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: