Question
stringlengths 1
113
| Answer
stringlengths 22
6.98k
|
|---|---|
Can you provide an example of Java String getChars() Method?
|
FileName: StringGetCharsExample.java
public class StringGetCharsExample{
public static void main(String args[]){
String str = new String("hello javatpoint how r u");
char[] ch = new char[10];
try{
str.getChars(6, 16, ch, 0);
System.out.println(ch);
}catch(Exception ex){System.out.println(ex);}
}}
Output:
javatpoint
|
What is Java String indexOf()?
|
The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
Signature
There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given below:
1) int indexOf(int ch) - It returns the index position for the given char value
2) int indexOf(int ch, int fromIndex) - It returns the index position for the given char value and from index
3) int indexOf(String substring) - It returns the index position for the given substring
4) int indexOf(String substring, int fromIndex) - It returns the index position for the given substring and from index
Parameters
ch: It is a character value, e.g. 'a'
fromIndex: The index position from where the index of the char value or substring is returned.
substring: A substring to be searched in this string.
Returns
Index of the searched string or character.
Internal Implementation
public int indexOf(int ch) {
return indexOf(ch, 0);
}
|
Can you provide an example of Java String indexOf() Method?
|
FileName: IndexOfExample.java
public class IndexOfExample{
public static void main(String args[]){
String s1="this is index of example";
//passing substring
int index1=s1.indexOf("is");//returns the index of is substring
int index2=s1.indexOf("index");//returns the index of index substring
System.out.println(index1+" "+index2);//2 8
//passing substring with from index
int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index
System.out.println(index3);//5 i.e. the index of another is
//passing char value
int index4=s1.indexOf('s');//returns the index of s char value
System.out.println(index4);//3
}}
Output:
2 8
5
3
We observe that when a searched string or character is found, the method returns a non-negative value. If the string or character is not found, -1 is returned. We can use this property to find the total count of a character present in the given string. Observe the following example.
FileName: IndexOfExample5.java
public class IndexOfExample5
{
// main method
public static void main(String argvs[])
{
String str = "Welcome to JavaTpoint";
int count = 0;
int startFrom = 0;
for(; ;)
{
int index = str.indexOf('o', startFrom);
if(index >= 0)
{
// match found. Hence, increment the count
count = count + 1;
// start looking after the searched index
startFrom = index + 1;
}
else
{
// the value of index is - 1 here. Therefore, terminate the loop
break;
}
}
System.out.println("In the String: "+ str);
System.out.println("The 'o' character has come "+ count + " times");
}
}
Output:
In the String: Welcome to JavaTpoint
The 'o' character has come 3 times
|
Can you provide an example of Java String indexOf(String substring) Method?
|
The method takes substring as an argument and returns the index of the first character of the substring.
FileName: IndexOfExample2.java
public class IndexOfExample2 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// Passing Substring
int index = s1.indexOf("method"); //Returns the index of this substring
System.out.println("index of substring "+index);
}
}
Output:
index of substring 16
|
Can you provide an example of Java String indexOf(String substring, int fromIndex) Method?
|
The method takes substring and index as arguments and returns the index of the first character that occurs after the given fromIndex.
FileName: IndexOfExample3.java
public class IndexOfExample3 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// Passing substring and index
int index = s1.indexOf("method", 10); //Returns the index of this substring
System.out.println("index of substring "+index);
index = s1.indexOf("method", 20); // It returns -1 if substring does not found
System.out.println("index of substring "+index);
}
}
Output:
index of substring 16
index of substring -1
|
Can you provide an example of Java String indexOf(int char, int fromIndex) Method?
|
The method takes char and index as arguments and returns the index of the first character that occurs after the given fromIndex.
FileName: IndexOfExample4.java
public class IndexOfExample4 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// Passing char and index from
int index = s1.indexOf('e', 12); //Returns the index of this char
System.out.println("index of char "+index);
}
}
Output:
index of char 17
|
What is Java String intern()?
|
The Java String class intern() method returns the interned string. It returns the canonical representation of string.
It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool.
Signature
The signature of the intern() method is given below:
public String intern()
Returns
interned string
|
What is The need and working of the String.intern() Method?
|
When a string is created in Java, it occupies memory in the heap. Also, we know that the String class is immutable. Therefore, whenever we create a string using the new keyword, new memory is allocated in the heap for corresponding string, which is irrespective of the content of the array. Consider the following code snippet.
String str = new String("Welcome to JavaTpoint.");
String str1 = new String("Welcome to JavaTpoint");
System.out.println(str1 == str); // prints false
The println statement prints false because separate memory is allocated for each string literal. Thus, two new string objects are created in the memory i.e. str and str1. that holds different references.
We know that creating an object is a costly operation in Java. Therefore, to save time, Java developers came up with the concept of String Constant Pool (SCP). The SCP is an area inside the heap memory. It contains the unique strings. In order to put the strings in the string pool, one needs to call the intern() method. Before creating an object in the string pool, the JVM checks whether the string is already present in the pool or not. If the string is present, its reference is returned.
String str = new String("Welcome to JavaTpoint").intern(); // statement - 1
String str1 = new String("Welcome to JavaTpoint").intern(); // statement - 2
System.out.println(str1 == str); // prints true
In the above code snippet, the intern() method is invoked on the String objects. Therefore, the memory is allocated in the SCP. For the second statement, no new string object is created as the content of str and str1 are the same. Therefore, the reference of the object created in the first statement is returned for str1. Thus, str and str1 both point to the same memory. Hence, the print statement prints true.
|
Could you provide an example of Java String intern() Method Example?
|
FileName: InternExample.java
public class InternExample{
public static void main(String args[]){
String s1=new String("hello");
String s2="hello";
String s3=s1.intern();//returns string from pool, now it will be same as s2
System.out.println(s1==s2);//false because reference variables are pointing to different instance
System.out.println(s2==s3);//true because reference variables are pointing to same instance
}}
Output:
false
true
|
What are the Points to Remember at intern() method?
|
Following are some important points to remember regarding the intern() method:
1) A string literal always invokes the intern() method, whether one mention the intern() method along with the string literal or not. For example,
String s = "d".intern();
String p = "d"; // compiler treats it as String p = "d".intern();
System.out.println(s == p); // prints true
2) Whenever we create a String object using the new keyword, two objects are created. For example,
String str = new ("Hello World");
Here, one object is created in the heap memory outside of the SCP because of the usage of the new keyword. As we have got the string literal too ("Hello World"); therefore, one object is created inside the SCP, provided the literal "Hello World" is already not present in the SCP.
|
What is Java String isEmpty()?
|
The Java String class isEmpty() method checks if the input string is empty or not. Note that here empty means the number of characters contained in a string is zero.
Signature
The signature or syntax of string isEmpty() method is given below:
public boolean isEmpty()
Returns
true if length is 0 otherwise false.
Since
1.6
Internal implementation
public boolean isEmpty() {
return value.length == 0;
}
|
Could you provide an example of Java String isEmpty() method example?
|
FileName: StringIsEmptyExample.java
public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="javatpoint";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}}
Output:
true
false
|
Could you provide an examples of Empty Vs. Null Strings?
|
Earlier in this tutorial, we have discussed that the empty strings contain zero characters. However, the same is true for a null string too. A null string is a string that has no value.
String str = ""; // empty string
String str1 = null; // null string. It is also not containing any characters.
The isEmpty() method is not fit for checking the null strings. The following example shows the same.
FileName: StringIsEmptyExample3.java
public class StringIsEmptyExample3
{
// main method
public static void main(String argvs[])
{
String str = null;
if(str.isEmpty())
{
System.out.println("The string is null.");
}
else
{
System.out.println("The string is not null.");
}
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at StringIsEmptyExample3.main(StringIsEmptyExample3.java:7)
Here, we can use the == operator to check for the null strings.
FileName: StringIsEmptyExample4.java
class StringIsEmptyExample4
{
// main method
public static void main(String argvs[])
{
String str = null;
if(str == null)
{
System.out.println("The string is null.");
}
else
{
System.out.println("The string is not null.");
}
}
}
Output:
The string is null.
|
Could you provide an example of Blank Strings?
|
Blank strings are those strings that contain only white spaces. The isEmpty() method comes in very handy to check for the blank strings. Consider the following example.
FileName: StringIsEmptyExample5.java
public class StringIsEmptyExample5
{
// main method
public static void main(String argvs[])
{
// a blank string
String str = " ";
int size = str.length();
// trim the white spaces and after that
// if the string results in the empty string
// then the string is blank; otherwise, not.
if(size == 0)
{
System.out.println("The string is empty. \n");
}
else if(size > 0 && str.trim().isEmpty())
{
System.out.println("The string is blank. \n");
}
else
{
System.out.println("The string is not blank. \n");
}
str = " Welcome to JavaTpoint. ";
size = str.length();
if(size == 0)
{
System.out.println("The string is empty. \n");
}
if(size > 0 && str.trim().isEmpty())
{
System.out.println("The string is blank. \n");
}
else
{
System.out.println("The string is not blank. \n");
}
}
}
Output:
The string is blank.
The string is not blank.
|
What is Java String join()?
|
The Java String class join() method returns a string joined with a given delimiter. In the String join() method, the delimiter is copied for each element. The join() method is included in the Java string since JDK 1.8.
There are two types of join() methods in the Java String class.
Signature
The signature or syntax of the join() method is given below:
public static String join(CharSequence delimiter, CharSequence... elements)
and
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
Parameters
delimiter : char value to be added with each element
elements : char value to be attached with delimiter
Returns
joined string with delimiter
Exception Throws
NullPointerException if element or delimiter is null.
Since
1.8
Internal Implementation
// type - 1
public static String join(CharSequence delimiter, CharSequence... elements)
{
Objects.requireNonNull(elements);
Objects.requireNonNull(delimiter);
StringJoiner jnr = new StringJoiner(delimiter);
for (CharSequence c: elements)
{
jnr.add(c);
}
return jnr.toString();
}
// type - 2
public static String join(CharSequence delimiter, CharSequence... elements)
{
Objects.requireNonNull(elements);
Objects.requireNonNull(delimiter);
StringJoiner jnr = new StringJoiner(delimiter);
for (CharSequence c: elements)
{
jnr.add(c);
}
return jnr.toString();
}
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
{
Objects.requireNonNull(elements);
Objects.requireNonNull(delimiter);
StringJoiner jnr = new StringJoiner(delimiter);
for (CharSequence c: elements)
{
joiner.add(c);
}
return jnr.toString();
}
|
Could you provide Java String join() Method Example?
|
FileName: StringJoinExample.java
public class StringJoinExample{
public static void main(String args[]){
String joinString1=String.join("-","welcome","to","javatpoint");
System.out.println(joinString1);
}}
Output:
welcome-to-javatpoint
|
What is Java String lastIndexOf()?
|
The Java String class lastIndexOf() method returns the last index of the given character value or substring. If it is not found, it returns -1. The index counter starts from zero.
Signature
There are four types of lastIndexOf() method in Java. The signature of the methods are given below:
1) int lastIndexOf(int ch) - It returns last index position for the given char value
2) int lastIndexOf(int ch, int fromIndex) - It returns last index position for the given char value and from index
3) int lastIndexOf(String substring) - It returns last index position for the given substring
4) int lastIndexOf(String substring, int fromIndex) - It returns last index position for the given substring and from index
Parameters
ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string
Returns
last index of the string
Internal Implementation
The internal implementation of the four types of the lastIndexOf() method is mentioned below.
The internal implementation of the four types of the lastIndexOf() method is mentioned below.
1. int lastIndexOf(int ch)
public int lastIndexOf(int ch)
{
return lastIndexOf(ch, value.length - 1);
}
2. int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(int ch, int fromIndex)
{
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT)
{
// handling most of the cases here
// negative value means invalid code point
final char[] val = this.value;
int j = Math.min(fromIndex, val.length - 1);
for (; jj >= 0; j--)
{
if (val[i] == ch)
{
return j;
}
}
return -1;
}
else
{
return lastIndexOfSupplementary(ch, fromIndex);
}
}
// internal implementation of the method lastIndexOfSupplementary()
private int lastIndexOfSupplementary(int c, int fIndex)
{
if (Character.isValidCodePoint(c))
{
final char[] val = this.value;
char h = Character.highSurrogate(c);
char l = Character.lowSurrogate(c);
int j = Math.min(fIndex, value.length - 2);
for (; j >= 0; j--)
{
if (val[j] == h && val[j + 1] == l)
{
return j;
}
}
}
return -1;
}
3. int lastIndexOf(String subString)
public int lastIndexOf(String subString)
{
return lastIndexOf(subString, value.length);
}
4. int lastIndexOf(String substring, int fromIndex)
public int lastIndexOf(String substring, int fromIndex)
{
public int lastIndexOf(String str, int fromIndex)
{
return lastIndexOf(value, 0, value.length, str.value, 0, str.value.length, fromIndex);
}
}
// src the characters that are being searched.
// srcOffset provides the offset of the src string.
// srcCount number of the source string.
// tar the characters that are being searched for.
// fromIndex the index to start search from.
static int lastIndexOf(char[] src, int srcOffset, int srcCount, String tar, int fromIndex)
{
return lastIndexOf(src, srcOffset, srcCount, tar.value, 0, tar.value.length, fromIndex);
}
static int lastIndexOf(char[] src, int srcOffset, int srcCount, char[] tar, int tarOffset, int tarCount, int fromIndex)
{
int rightIndex = srcCount - tarCount;
if (fromIndex < 0)
{
return -1;
}
if (fromIndex > rightIndex)
{
fromIndex = rightIndex;
}
// an Empty string is always a match.
if (tarCount == 0)
{
return fromIndex;
}
int lastStrIndex = tarOffset + tarCount - 1;
char lastStrChar = tar[strLastIndex];
int min = srcOffset + tarCount - 1;
int j = min + fromIndex;
startLookForLastChar:
while (true)
{
while (j >= min && src[j] != lastStrChar)
{
j = j - 1;
}
if (j < min)
{
return -1;
}
int i = j - 1;
int begin = i - (tarCount - 1);
int m = lastStrIndex - 1;
while (i > begin)
{
if (source[i--] != target[m--])
{
j = j + 1;
continue startLookForLastChar;
}
}
return begin - srcOffset + 1;
}
}
|
Can you provide an example of Java String lastIndexOf() method?
|
FileName: LastIndexOfExample.java
public class LastIndexOfExample{
public static void main(String args[]){
String s1="this is index of example";//there are 2 's' characters in this sentence
int index1=s1.lastIndexOf('s');//returns last index of 's' char value
System.out.println(index1);//6
}}
Output:
6
|
Can provide an example of Java String lastIndexOf(int ch, int fromIndex) Method?
|
Here, we are finding the last index from the string by specifying fromIndex.
FileName: LastIndexOfExample2.java
public class LastIndexOfExample2 {
public static void main(String[] args) {
String str = "This is index of example";
int index = str.lastIndexOf('s',5);
System.out.println(index);
}
}
Output:
3
|
Could you provide an example of Java String lastIndexOf(String substring) Method?
|
It returns the last index of the substring.
FileName: LastIndexOfExample3.java
public class LastIndexOfExample3 {
public static void main(String[] args) {
String str = "This is last index of example";
int index = str.lastIndexOf("of");
System.out.println(index);
}
}
Output:
19
|
Can you provide an example of Java String lastIndexOf(String substring, int fromIndex) Method?
|
It returns the last index of the substring from the fromIndex.
FileName: LastIndexOfExample4.java
public class LastIndexOfExample4 {
public static void main(String[] args) {
String str = "This is last index of example";
int index = str.lastIndexOf("of", 25);
System.out.println(index);
index = str.lastIndexOf("of", 10);
System.out.println(index); // -1, if not found
}
}
Output:
19
-1
|
What is Java String length()?
|
The Java String class length() method finds the length of a string. The length of the Java string is the same as the Unicode code units of the string.
Signature
The signature of the string length() method is given below:
public int length()
Specified by
CharSequence interface
Returns
Length of characters. In other words, the total number of characters present in the string.
Internal implementation
public int length() {
return value.length;
}
The String class internally uses a char[] array to store the characters. The length variable of the array is used to find the total number of elements present in the array. Since the Java String class uses this char[] array internally; therefore, the length variable can not be exposed to the outside world. Hence, the Java developers created the length() method, the exposes the value of the length variable. One can also think of the length() method as the getter() method, that provides a value of the class field to the user. The internal implementation clearly depicts that the length() method returns the value of then the length variable.
|
Could you provide Java String length() method example?
|
FileName: LengthExample.java
public class LengthExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="python";
System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string
System.out.println("string length is: "+s2.length());//6 is the length of python string
}}
Output:
string length is: 10
string length is: 6
|
What is Java String replace()?
|
The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.
Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char values.
Signature
There are two types of replace() methods in Java String class.
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
The second replace() method is added since JDK 1.5.
Parameters
oldChar : old character
newChar : new character
target : target sequence of characters
replacement : replacement sequence of characters
Returns
replaced string
Exception Throws
NullPointerException: if the replacement or target is equal to null.
Internal implementation
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
public String replace(CharSequence target, CharSequence replacement)
{
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
|
Can you provide an example of Java String replace(char old, char new) method?
|
FileName: ReplaceExample1.java
public class ReplaceExample1{
public static void main(String args[]){
String s1="javatpoint is a very good website";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}}
Output:
jevetpoint is e very good website
|
Could you provide Java String replace(CharSequence target, CharSequence replacement) method example?
|
FileName: ReplaceExample2.java
public class ReplaceExample2{
public static void main(String args[]){
String s1="my name is khan my name is java";
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
System.out.println(replaceString);
}}
Output:
my name was khan my name was java
|
What is Java String replaceAll()?
|
The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
Signature
public String replaceAll(String regex, String replacement)
Parameters
regex : regular expression
replacement : replacement sequence of characters
Returns
replaced string
Exception Throws
PatternSyntaxException: if the syntax of the regular expression is not valid.
Internal implementation
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
|
Could you provide Java String replaceAll() example: replace character?
|
Let's see an example to replace all the occurrences of a single character.
FileName: ReplaceAllExample1.java
public class ReplaceAllExample1{
public static void main(String args[]){
String s1="javatpoint is a very good website";
String replaceString=s1.replaceAll("a","e");//replaces all occurrences of "a" to "e"
System.out.println(replaceString);
}}
Output:
jevetpoint is e very good website
|
Could you provide Java String replaceAll() example: replace word?
|
Let's see an example to replace all the occurrences of a single word or set of words.
FileName: ReplaceAllExample2.java
public class ReplaceAllExample2{
public static void main(String args[]){
String s1="My name is Khan. My name is Bob. My name is Sonoo.";
String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"
System.out.println(replaceString);
}}
Output:
My name was Khan. My name was Bob. My name was Sonoo.
|
Java String replaceAll() example: remove white spaces?
|
Let's see an example to remove all the occurrences of white spaces.
FileName: ReplaceAllExample3.java
public class ReplaceAllExample3{
public static void main(String args[]){
String s1="My name is Khan. My name is Bob. My name is Sonoo.";
String replaceString=s1.replaceAll("\\s","");
System.out.println(replaceString);
}}
Output:
MynameisKhan.MynameisBob.MynameisSonoo.
|
What is Java String split()?
|
The java string split() method splits this string against given regular expression and returns a char array.
|
Could you provide Java String split() method example?
|
The given example returns total number of words in a string excluding space only. It also includes special characters.
public class SplitExample{
public static void main(String args[]){
String s1="java string split method by javatpoint";
String[] words=s1.split("\\s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:words){
System.out.println(w);
}
}}
java
string
split
method
by
javatpoint
|
Could you provide Java String split() method with regex and length example?
|
public class SplitExample2{
public static void main(String args[]){
String s1="welcome to split world";
System.out.println("returning words:");
for(String w:s1.split("\\s",0)){
System.out.println(w);
}
System.out.println("returning words:");
for(String w:s1.split("\\s",1)){
System.out.println(w);
}
System.out.println("returning words:");
for(String w:s1.split("\\s",2)){
System.out.println(w);
}
}}
returning words:
welcome
to
split
world
returning words:
welcome to split world
returning words:
welcome
to split world
|
What is Java String startsWith()?
|
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.
|
Could you provide Java String startsWith() method example?
|
The startsWith() method considers the case-sensitivity of characters. Consider the following example.
FileName: StartsWithExample.java
public class StartsWithExample
{
// main method
public static void main(String args[])
{
// input string
String s1="java string split method by javatpoint";
System.out.println(s1.startsWith("ja")); // true
System.out.println(s1.startsWith("java string")); // true
System.out.println(s1.startsWith("Java string")); // false as 'j' and 'J' are different
}
}
Output:
true
true
false
|
Can you provide an example of Java String startsWith(String prefix, int offset) Method?
|
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.
FileName: StartsWithExample2.java
public class StartsWithExample2 {
public static void main(String[] args) {
String str = "Javatpoint";
// no offset mentioned; hence, offset is 0 in this case.
System.out.println(str.startsWith("J")); // True
// no offset mentioned; hence, offset is 0 in this case.
System.out.println(str.startsWith("a")); // False
// offset is 1
System.out.println(str.startsWith("a",1)); // True
}
}
Output:
true
false
true
|
What is Java String substring()?
|
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.
There are two types of substring methods in Java string.
|
Can you provide an example of Java String substring() method?
|
FileName: SubstringExample.java
public class SubstringExample{
public static void main(String args[]){
String s1="javatpoint";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vatpoint
}}
Output:
va
vatpoint
|
Can you provide an example of Applications of substring() Method
|
1) The substring() method can be used to do some prefix or suffix extraction. For example, we can have a list of names, and it is required to filter out names with surname as "singh". The following program shows the same.
FileName: SubstringExample3.java
public class SubstringExample3
{
// main method
public static void main(String argvs[])
{
String str[] =
{
"Praveen Kumar",
"Yuvraj Singh",
"Harbhajan Singh",
"Gurjit Singh",
"Virat Kohli",
"Rohit Sharma",
"Sandeep Singh",
"Milkha Singh"
};
String surName = "Singh";
int surNameSize = surName.length();
int size = str.length;
for(int j = 0; j < size; j++)
{
int length = str[j].length();
// extracting the surname
String subStr = str[j].substring(length - surNameSize);
// checks whether the surname is equal to "Singh" or not
if(subStr.equals(surName))
{
System.out.println(str[j]);
}
}
}
}
Output:
Yuvraj Singh
Harbhajan Singh
Gurjit Singh
Sandeep Singh
Milkha Singh
2) The substring() method can also be used to check whether a string is a palindrome or not.
FileName: SubstringExample4.java
public class SubstringExample4
{
public boolean isPalindrome(String str)
{
int size = str.length();
// handling the base case
if(size == 0 || size == 1)
{
// an empty string
// or a string of only one character
// is always a palindrome
return true;
}
String f = str.substring(0, 1);
String l = str.substring(size - 1);
// comparing first and the last character of the string
if(l.equals(f))
{
// recursively finding the solution using the substring() method
// reducing the number of characters of the by 2 for the next recursion
return isPalindrome(str.substring(1, size - 1));
}
return false;
}
// main method
public static void main(String argvs[])
{
// instantiating the class SubstringExample4
SubstringExample4 obj = new SubstringExample4();
String str[] =
{
"madam",
"rock",
"eye",
"noon",
"kill"
};
int size = str.length;
for(int j = 0; j < size; j++)
{
if(obj.isPalindrome(str[j]))
{
System.out.println(str[j] + " is a palindrome.");
}
else
{
System.out.println(str[j] + " is not a palindrome.");
}
}
}
}
Output:
madam is a palindrome.
rock is not a palindrome.
eye is a palindrome.
noon is a palindrome.
kill is not a palindrome.
|
What is Java String toCharArray()?
|
The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
|
Can you provide an example of Java String toCharArray() method?
|
public class StringToCharArrayExample{
public static void main(String args[]){
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}
}}
Output:
hello
|
What is Java String toLowerCase()?
|
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.
The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It internally uses the default locale.
|
Can you provide an example of Java String toLowerCase() method?
|
public class StringLowerExample{
public static void main(String args[]){
String s1="JAVATPOINT HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}}
Output:
javatpoint hello string
|
Could you provide Java String toLowerCase(Locale locale) Method Example?
|
This method allows us to pass locale too for the various langauges. Let's see an example below where we are getting string in english and turkish both.
import java.util.Locale;
public class StringLowerExample2 {
public static void main(String[] args) {
String s = "JAVATPOINT HELLO stRIng";
String eng = s.toLowerCase(Locale.ENGLISH);
System.out.println(eng);
String turkish = s.toLowerCase(Locale.forLanguageTag("tr")); // It shows i without dot
System.out.println(turkish);
}
}
Output:
javatpoint hello string
javatpo?nt hello str?ng
|
What is Java String toUpperCase()?
|
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.
The toUpperCase() method works same as toUpperCase(Locale.getDefault()) method. It internally uses the default locale.
|
Can you provide an example of Java String toUpperCase() method?
|
public class StringUpperExample{
public static void main(String args[]){
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}}
Output:
HELLO STRING
|
What is Java String trim()?
|
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.
|
Can you provide an example of Java String trim() Method?
|
FileName: StringTrimExample.java
public class StringTrimExample{
public static void main(String args[]){
String s1=" hello string ";
System.out.println(s1+"javatpoint");//without trim()
System.out.println(s1.trim()+"javatpoint");//with trim()
}}
Output
hello string javatpoint
hello stringjavatpoint
|
What is Java String valueOf()?
|
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.
|
Could you provide an example of Java String valueOf() method?
|
public class StringValueOfExample{
public static void main(String args[]){
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
}}
Output:
3010
|
Could you provide Java String valueOf(boolean bol) Method Example?
|
This is a boolean version of overloaded valueOf() method. It takes boolean value and returns a string. Let's see an example.
public class StringValueOfExample2 {
public static void main(String[] args) {
// Boolean to String
boolean bol = true;
boolean bol2 = false;
String s1 = String.valueOf(bol);
String s2 = String.valueOf(bol2);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
true
false
|
Could you provide Java String valueOf(char ch) Method Example?
|
This is a char version of overloaded valueOf() method. It takes char value and returns a string. Let's see an example.
public class StringValueOfExample3 {
public static void main(String[] args) {
// char to String
char ch1 = 'A';
char ch2 = 'B';
String s1 = String.valueOf(ch1);
String s2 = String.valueOf(ch2);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
A
B
|
Can you provide an example of Java String valueOf(float f) and valueOf(double d)?
|
This is a float version of overloaded valueOf() method. It takes float value and returns a string. Let's see an example.
public class StringValueOfExample4 {
public static void main(String[] args) {
// Float and Double to String
float f = 10.05f;
double d = 10.02;
String s1 = String.valueOf(f);
String s2 = String.valueOf(d);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
10.05
10.02
|
Can you provide an example of Java String valueOf() Complete?
|
Let's see an example where we are converting all primitives and objects into strings.
public class StringValueOfExample5 {
public static void main(String[] args) {
boolean b1=true;
byte b2=11;
short sh = 12;
int i = 13;
long l = 14L;
float f = 15.5f;
double d = 16.5d;
char chr[]={'j','a','v','a'};
StringValueOfExample5 obj=new StringValueOfExample5();
String s1 = String.valueOf(b1);
String s2 = String.valueOf(b2);
String s3 = String.valueOf(sh);
String s4 = String.valueOf(i);
String s5 = String.valueOf(l);
String s6 = String.valueOf(f);
String s7 = String.valueOf(d);
String s8 = String.valueOf(chr);
String s9 = String.valueOf(obj);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
System.out.println(s8);
System.out.println(s9);
}
}
Output:
true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55
|
What is Java Regex?
|
The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.
It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.
|
What are the java.util.regex package?
|
The Matcher and Pattern classes provide the facility of Java regular expression. The java.util.regex package provides following classes and interfaces for regular expressions.
1.MatchResult interface
2.Matcher class
3.Pattern class
4.PatternSyntaxException class
|
Wha is Matcher class?
|
Matcher class Method
Method: boolean matches()
Description: test whether the regular expression matches the pattern.
Method: boolean find()
Description: finds the next expression that matches the pattern.
Method: boolean find(int start)
Description: finds the next expression that matches the pattern from the given start number.
Method: String group()
Description: returns the matched subsequence.
Method: int start()
Description: returns the starting index of the matched subsequence.
Method: int end()
Description: returns the ending index of the matched subsequence.
Method: int groupCount()
Description: returns the total number of the matched subsequence.
|
What is Pattern class?
|
It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.
Pattern Class Method
Method: static Pattern compile(String regex)
Description: compiles the given regex and returns the instance of the Pattern.
Method: Matcher matcher(CharSequence input)
Description: creates a matcher that matches the given input with the pattern.
Method: static boolean matches(String regex, CharSequence input)
Description: It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern.
Method: String[] split(CharSequence input)
Description: splits the given input string around matches of given pattern.
Method: String pattern()
Description: returns the regex pattern.
|
Could you provide Example of Java Regular Expressions?
|
There are three ways to write the regex example in Java.
import java.util.regex.*;
public class RegexExample1{
public static void main(String args[]){
//1st way
Pattern p = Pattern.compile(".s");//. represents single character
Matcher m = p.matcher("as");
boolean b = m.matches();
//2nd way
boolean b2=Pattern.compile(".s").matcher("as").matches();
//3rd way
boolean b3 = Pattern.matches(".s", "as");
System.out.println(b+" "+b2+" "+b3);
}}
Output
true true true
|
Could you provide Regular Expression . Example?
|
The . (dot) represents a single character.
import java.util.regex.*;
class RegexExample2{
public static void main(String args[]){
System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
}}
|
What are the Regex Character classes?
|
Regex Character Class methods
Method: [abc]
Description: a, b, or c (simple class)
Method: [^abc]
Description: Any character except a, b, or c (negation)
Method: [a-zA-Z]
Description: a through z or A through Z, inclusive (range)
Method: [a-d[m-p]]
Description: a through d, or m through p: [a-dm-p] (union)
Method: [a-z&&[def]]
Description: d, e, or f (intersection)
Method: [a-z&&[^bc]]
Description: a through z, except for b and c: [ad-z] (subtraction)
Method: [a-z&&[^m-p]]
Description: a through z, and not m through p: [a-lq-z](subtraction)
|
Could you provide Regular Expression Character classes Example?
|
import java.util.regex.*;
class RegexExample3{
public static void main(String args[]){
System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)
System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)
System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more than once)
}}
|
What are the Regex Quantifiers?
|
The quantifiers specify the number of occurrences of a character.
Regex Description methods
Method: X?
Description: X occurs once or not at all
Method: X+
Description: X occurs once or more times
Method: X*
Description: X occurs zero or more times
Method: X{n}
Description: X occurs n times only
Method: X{n,}
Description: X occurs n or more times
Method: X{y,z}
Description: X occurs at least y times but less than z times
|
Could you provide Regular Expression Character classes and Quantifiers Example?
|
import java.util.regex.*;
class RegexExample4{
public static void main(String args[]){
System.out.println("? quantifier ....");
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)
System.out.println("+ quantifier ....");
System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)
System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)
System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than once)
System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)
System.out.println("* quantifier ....");
System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or more times)
}}
|
What are the Regex Metacharacters?
|
The regular expression metacharacters work as shortcodes.
Regex Metacharacters
Regex: .
Description: Any character (may or may not match terminator)
Regex: \d
Description: Any digits, short of [0-9]
Regex:
Description:
Regex: \D
Description: Any non-digit, short for [^0-9]
Regex: \s
Description: Any whitespace character, short for [\t\n\x0B\f\r]
Regex: \S
Description: Any non-whitespace character, short for [^\s]
Regex: \w
Description: Any word character, short for [a-zA-Z_0-9]
Regex: \W
Description: Any non-word character, short for [^\w]
Regex: \b
Description: A word boundary
Regex: \B
Description: A non word boundary
|
Can you provide an example of Regular Expression Metacharacters?
|
import java.util.regex.*;
class RegexExample5{
public static void main(String args[]){
System.out.println("metacharacters d....");\\d means digit
System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)
System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)
System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than once)
System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)
System.out.println("metacharacters D....");\\D means non-digit
System.out.println(Pattern.matches("\\D", "abc"));//false (non-digit but comes more than once)
System.out.println(Pattern.matches("\\D", "1"));//false (digit)
System.out.println(Pattern.matches("\\D", "4443"));//false (digit)
System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)
System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)
System.out.println("metacharacters D with quantifier....");
System.out.println(Pattern.matches("\\D*", "mak"));//true (non-digit and may come 0 or more times)
}}
|
What is Exception Handling in Java?
|
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked exceptions.
|
What is Exception in Java?
|
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
|
What is Exception Handling?
|
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
|
What is the Advantage of Exception Handling?
|
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.
|
What are the Types of Java Exceptions?
|
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1.Checked Exception
2.Unchecked Exception
3.Error
|
What is the Difference between Checked and Unchecked Exceptions?
|
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
|
What is Java Exception Keywords?
|
Java provides five keywords that are used to handle the exception. The following table describes each.
Java Exception Keywords
Keyword: try
Description: The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.
Keyword: catch
Description: The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
Keyword: finally
Description: The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
Keyword: throw
Description: The "throw" keyword is used to throw an exception.
Keyword: throws
Description: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
|
Can you provide an example of Java Exception Handling Example?
|
et's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
|
What are Common Scenarios of Java Exceptions?
|
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
|
What is the purpose of Java try block?
|
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
|
What is the function of a catch block in Java?
|
Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try block.
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed.
|
what is the Problem without exception handling?
|
Let's try to understand the problem if we don't use a try-catch block.
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
|
what is Java Multi-catch block?
|
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.
Points to remember
-At a time only one exception occurs and at a time only one catch block is executed.
-All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
|
What is Java Nested try block?
|
In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement in try block, context of that exception is pushed onto the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.
|
Why use nested try block?
|
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
|
What is Java finally block?
|
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.
The finally block follows the try-catch block.
|
Why use Java finally block?
|
-finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
-The important statements to be printed can be placed in the finally block.
|
What is Java throw Exception?
|
In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead of runtime and we can create custom exceptions making the code recovery and debugging easier.
|
What is Java throw keyword?
|
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception. We will discuss custom exceptions later in this section.
We can also define our own set of conditions and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException if we divide a number by another number. Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
throw new exception_class("error message");
Let's see the example of throw IOException.
throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception is the sub class of Throwable and the user-defined exceptions usually extend the Exception class.
|
What is Java Exception Propagation?
|
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.
|
Can you give me an example of Exception Propagation?
|
Exception Propagation Example
TestExceptionPropagation1.java
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
|
What is Java throws keyword?
|
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that he is not checking the code before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name{
//method code
}
|
What is the Advantage of Java throws keyword?
|
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
|
Can you give me an example of Java throws?
|
Let's see the example of Java throws clause which describes that checked exceptions can be propagated by throws keyword.
Testthrows1.java
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
|
What is the Difference between throw and throws in Java?
|
Difference between throw and throws in Java
Basis of Differences: Definition
Throw: Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code.
Throws: Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.
Basis of Differences: Type of exception Using throw keyword, we can only propagate unchecked exception i.e., the checked exception cannot be propagated using throw only.
Throw: Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only.
Throws:
Basis of Differences: Syntax
Throw: The throw keyword is followed by an instance of Exception to be thrown.
Throws: The throws keyword is followed by class names of Exceptions to be thrown.
Basis of Differences: Declaration
Throw: throw is used within the method.
Throws: throws is used with the method signature.
Basis of Differences: Internal implementation
Throw: We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions.
Throws: We can declare multiple exceptions using throws keyword that can be thrown by the method. For example, main() throws IOException, SQLException.
|
What is the Difference between final, finally and finalize in Java?
|
Difference between final, finally and finalize
The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these keywords has a different functionality. The basic difference between final, finally and finalize is that the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object class.
Along with this, there are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:
Key: Definition
Final: final is the keyword and access modifier which is used to apply restrictions on a class, method or variable.
Finally: finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not.
Finalize: finalize is the method in Java which is used to perform clean up processing just before object is garbage collected.
Key: Applicable to
Final: Final keyword is used with the classes, methods and variables.
Finally: Finally block is always related to the try and catch block in exception handling.
Finalize: finalize() method is used with the objects.
Key: Functionality
Final: (1) Once declared, final variable becomes constant and cannot be modified.
(2) final method cannot be overridden by sub class.
(3) final class cannot be inherited.
Finally: (1) finally block runs the important code even if exception occurs or not.
(2) finally block cleans up all the resources used in try block
Finalize: finalize method performs the cleaning activities with respect to the object before its destruction.
Key: Execution
Final: Final method is executed only when we call it.
Finally: Finally block is executed as soon as the try-catch block is executed.
It's execution is not dependant on the exception.
Finalize: finalize method is executed just before the object is destroyed.
|
Can you give an example of Java final?
|
FinalExampleTest.java
public class FinalExampleTest {
//declaring final variable
final int age = 18;
void display() {
// reassigning value to age variable
// gives compile time error
age = 55;
}
public static void main(String[] args) {
FinalExampleTest obj = new FinalExampleTest();
// gives compile time error
obj.display();
}
}
|
Can you give me an example of Java finally?
|
Let's see the below example where the Java code throws an exception and the catch block handles that exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.
FinallyExample.java
public class FinallyExample {
public static void main(String args[]){
try {
System.out.println("Inside try block");
// below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
// handles the Arithmetic Exception / Divide by zero exception
catch (ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
// executes regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
|
Can you give me an example of Java finalize?
|
FinalizeExample.java
public class FinalizeExample {
public static void main(String[] args)
{
FinalizeExample obj = new FinalizeExample();
// printing the hashcode
System.out.println("Hashcode is: " + obj.hashCode());
obj = null;
// calling the garbage collector using gc()
System.gc();
System.out.println("End of the garbage collection");
}
// defining the finalize method
protected void finalize()
{
System.out.println("Called the finalize() method");
}
}
|
What is Exception Handling with Method Overriding in Java?
|
There are many rules if we talk about method overriding with exception handling.
Some of the rules are listed below:
-If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
-If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
-If the superclass method does not declare an exception
Rule 1: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.
|
What is Java Custom Exception?
|
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java programs.
|
Why use custom exceptions?
|
Java exceptions cover almost all the general type of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.
Following are few of the reasons to use custom exceptions:
-To catch and provide specific treatment to a subset of existing Java exceptions.
-Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem.
In order to create custom exception, we need to extend Exception class that belongs to java.lang package.
Consider the following example, where we create a custom exception named WrongFileNameException:
public class WrongFileNameException extends Exception {
public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}
Note: We need to write the constructor that takes the String as the error message and it is called parent class constructor.
|
What is Java Inner Classes (Nested Classes)?
|
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.
Additionally, it can access all the members of the outer class, including private data members and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
|
What is the Advantage of Java inner classes?
|
There are three advantages of inner classes in Java. They are as follows:
1.Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
2.Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
3.Code Optimization: It requires less code to write.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.