Que. Give Difference Between Final, Finally and Finalize. Ans
Que. Give Difference Between Final, Finally and Finalize. Ans
Patel
String s1 = “VIRAL”;
String s2 = “VIRAL”;
String s3 = “PATEL”;
String s4 = “VIRAL”;
String s5 = “viral”;
For other classes equals method compare only references. If values of two objects are
same still return false.
Example :
class Myclass1 class Cmp1
{ {
int a; public static void main(String args[])
{
Myclass1(int a) Myclass1 obj1 = new Myclass1(5);
{ Myclass1 obj2 = new Myclass1(5);
this.a = a; Myclass1 obj3 = obj1; // create new reference of obj1
} System.out.println(obj1.equals(obj2)); //display false
} // because references are of different objects
System.out.println(obj1.equals(obj3)); // display true
// because references are of same object
}
}
The second is used to access a member of the superclass that has been hidden (override) by a
member of a subclass.
Example :
For example, given a subclass called B and a superclass called A, is A’s constructor called before
B’s.
} }
Abstract class can extend another java class and An interface can extend another interface only.
implement multiple java interfaces.
Abstract class have private, protected or public Members (variables and methods) of a Java
members. interface are public by default.
The method which we define in child class The method which we implement in child class
(inherited from the abstract class) is not necessary (implements interface) must have to be public so
to be public. we must have to write public keyword before it.
abstract class A interface A
{ {
abstract void disp(); void disp();
} }
class B extends A //correct class B implements A //correct
{ {
void disp() { … } public void disp() { … }
} }
Que. Explain Package in Java. How to create and use package in java.
Ans. Packages are containers for classes that are used to keep the class name space
compartmentalized. JAVA API provides a large number of classes grouped into different
packages according to functionality. (Prof. Viral S. Patel)
To create package simply include a package command as the first statement in a java source
file.
General form of the package statement : package pkg;
To execute the program in package, package have to be in current directory, or a subdirectory
of the current directory and also have to specify a directory path or paths by setting the
CLASSPATH environmental variable.
The easiest way to try the examples shown in this book is to simply create the package
directories below your current development directory, put the .class files into the appropriate
directories and then execute the programs from the development directory.
we can also create package in current directory from command line by using command.
Example: Suppose MyJavaFile.java have fist statement ‘package p1’ and then ‘Demo’ class.
By using command (Prof. Viral S. Patel)
javac –d . MyJavaFile.java
java p1.Demo
Java package can be accessed either using a fully qualified class name or using import
statement that can be used to search a list of packages for a particular class.
import pkg1[.pkg2][.pkg3].classname;
Example :
package p1; import p1.A;
Que. How Java restricts the access of classes and methods at package level using access
modifiers ?
Ans. Java addresses four categories of visibility for class members:
■ Subclasses in the same package
■ Non-subclasses in the same package
■ Subclasses in different packages
■ Non-subclass in different package
The Four types of access specifiers – default, private, public, and protected, provide a variety of
ways to produce the many levels of access required by these categories.
A class has only two possible access levels: default and public.
When a class is declared as public, it is accessible by any other code.
If a class has default access, then it can only be accessed by other code within its same
package.
Que. How default access modifier is different than public modifier ? (2)
Ans. In same package there in no difference but in different package subclass/non subclass
concept public data members or public functions can be access but default not access. Default
modifier allow to access only for same package classes.
String s="Sachin";
s.concat(" Tendulkar"); //concat() method appends the string at the end
System.out.println(s); //will print Sachin because strings are immutable objects
Output: Sachin
Now it can be understood by the diagram given below. Here ‘Sachin’ is not changed but a new
object is created with ‘Sachin Tendulkar’. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
For example:
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
In such case, s points to the "Sachin Tendulkar". Please notice that still ‘sachin’ object is not
modified.
Because java uses the concept of string literal. Suppose there are 5 reference variables, all referes
to one object "sachin". If one reference variable changes the value of the object, it will be
affected to all the reference variables. That is why string objects are immutable in java.
String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more memory StringBuffer is fast and consumes less memory
when we concat too many strings because when we concat strings.
every time it creates new instance.
String class overrides the equals( ) method of StringBuffer class doesn’t override the
Object class. So you can compare the contents equals( ) method of Object class.
of two strings by equals( ) method.
length( ) : calculate length of a string means the number of characters that it contains.
Syntax : int length( )
Example :
class A
{
public static void main(String args[])
{
String s1 = "VSP";
System.out.println(s1.length( ));
}
}
Output : 3
charAt( ) : extract a single character from a String.
Syntax : char charAt(int index)
Example :
class A
{
public static void main(String args[])
{
char ch = “VSP”.charAt(1);
System.out.println(ch);
}
}
Output : S
getChars( ) : Extract more than one character at a time (substring) and store in char array.
Syntax : void getChars(int startIndex, int endIndex, char arr[ ], int arrStartIndex)
The substring contains the characters from ‘startIndex’ to ‘endIndex’–1. The array that
will receive the characters is specified by ‘arr’. The index within ‘arr’ at which the
substring will be copied is passed in ‘arrStartIndex’.
Example :
class A
{
public static void main(String args[])
{
String s = "Prof Viral Patel";
int start = 5;
int end = 10;
char arr[] = new char[end - start];
s.getChars(start, end, arr, 0);
System.out.println(arr);
}
}
Output : Viral
toCharArray( ) : convert all the characters in a String object into a character array
Syntax : char[ ] toCharArray( )
Example :
class A
{
public static void main(String args[])
{
String s = "Prof Viral Patel";
char arr[] = s.toCharArray( );
System.out.println(arr);
}
}
Output : Prof Viral Patel
equals( ) and equalsIgnoreCase( ) :To compare two strings for equality.
Syntax : boolean equals(Object str)
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It
returns true if the strings contain the same characters in the same order, and false
otherwise. The comparison is case-sensitive.
To perform a comparison that ignores case differences, call equalsIgnoreCase( ).
When it compares two strings, it considers A-Z to be the same as a-z.
Example :
class A
{
public static void main(String args[])
{
String s1 = "Prof";
String s2 = "viral";
String s3 = "VIRAL";
String s4 = "viral";
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s2.equals(s4));
System.out.println(s2.equalsIgnoreCase(s3));
}
}
Output : false
false
true
true
startsWith( ) and endsWith( ) :
Syntax : boolean startsWith(String str)
boolean endsWith(String str)
boolean startsWith(String str, int startIndex)
startsWith( ) method determines whether a given String begins with a specified string.
Conversely, endsWith( ) determines whether the String in question ends with a specified string.
Example :
class A
{
public static void main(String args[])
{
System.out.println("Foobar".endsWith("bar"));
System.out.println("Foobar".startsWith("Foo"));
System.out.println("Foobar".startsWith("bar",3));
}
}
Output : true
true
true
compareTo( ) and compareToIgnoreCase( ): To compare two strings as one is less than, equal
to, or greater than the another.
Syntax : int compareTo(String str)
int compareToIgnoreCase(String str)
s1.compareTo(s2)
if s1 > s2 It returns positive value.
if s1 = s2 It returns 0 value.
if s1 < s2 It returns negative value.
Example :
class A
{
public static void main(String args[])
{
String s1 = “ABC”; // ASCII value of A 65
String s2 = “XYZ”; // ASCII value of X 88
System.out.println(s1.compareTo(s2)); // 65-88
}
}
Output : -23
compareToIgnoreCase( ) method returns the same results as compareTo( ), except that case
differences are ignored.
IndexOf( ) and lastIndexOf( ) : indexOf( ) Searches for the first occurrence of a character or
substring. lastIndexOf( ) Searches for the last occurrence of a character or substring.
Syntax :
int indexOf(int ch)
int lastIndexOf(int ch)
We can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
Example :
class A
{
public static void main(String args[])
{
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println( s.indexOf('t')); // 7
System.out.println(s.lastIndexOf('t')); // 65
System.out.println(s.indexOf("the")); // 7
System.out.println(s.lastIndexOf("the")); // 55
System.out.println(s.indexOf('t', 10)); // 11
System.out.println(s.lastIndexOf('t', 60)); // 55
System.out.println(s.indexOf("the", 10)); // 44
System.out.println(s.lastIndexOf("the", 60)); // 55
}
}
Output : ViralPatel
replace( ) : The replace( ) method replaces all occurrences of one character in the invoking
string with another character.
Syntax : String replace(char original, char replacement)
Example :
class A
{
public static void main(String args[])
{
String s1 = “Viraj”.replace(‘j’,’l’ );
System.out.println(s1);
}
}
Output : Viral
trim( ) : The trim( ) method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed.
Syntax : Stirng trim( )
Example :
class A
{
public static void main(String args[])
{
String s1 = “ Prof Viral S Patel ”.trim( );
System.out.println(s1);
}
}
Example :
class A
{
public static void main(String args[])
{
String s1 = “Prof Viral S Patel”;
String upper = s1.toUpperCase( );
System.out.println(upper);
String lower = s1.toLowerCase( );
System.out.println(lower);
}
}
length() : calculate length of a string means the number of characters that it contains.
capacity() : the total allocated capacity (memory space) can be found through this method.
Syntax : int length()
int capacity()
Example :
class A
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("VSP");
System.out.println(s.length());
System.out.println(s.capacity());
}
}
Output : 3
19
setLength() : To set the length of the buffer within a StringBuffer object. When we increase the
size of the buffer, null characters are added to the end of the existing buffer. If we call
setLength( ) with a value less than the current value returned by length( ), then the characters
stored beyond the new length will be lost.
Syntax : void setLength(int len)
Example :
class A
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer(“Viral”);
s.setLength(3);
System.out.println(s);
}
Output : Vir
ensureCapacity() : It is used to set the size of the buffer. This is useful if we know in advance
that we will be appending a large number of small strings to a StringBuffer.
Syntax : void ensureCapacity(int capacity)
Example :
class A
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer(“Viral”);
System.out.println(s.capacity()); // (5 + 16 = 21)
s.ensureCapacity(22); // (ensure capacity = old capacity * 2 + 2 = 21 * 2 + 2 = 44)
System.out.println(s.capacity());
}
}
Output : 21
44
charAt() : extract a single character from a String.
setCharAt() : set character at particular index of String.
Syntax : char charAt(int index)
void setCharAt(int index, char ch)
Example :
class A
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer(“VSP”);
char ch = s.charAt(1);
System.out.println(ch);
s.setCharAt(1,’I’);
System.out.println(s);
}
}
Output : S
VIP
getChars() : Extract more than one character at a time (substring) and store in char array.
Syntax : void getChars(int startIndex, int endIndex, char arr[ ], int arrStartIndex)
The substring contains the characters from ‘startIndex’ to ‘endIndex’–1. The array that
will receive the characters is specified by ‘arr’. The index within ‘arr’ at which the
substring will be copied is passed in ‘arrStartIndex’.
Example :
class A
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("Prof Viral Patel");
int start = 5;
int end = 10;
char arr[] = new char[end - start];
s.getChars(start, end, arr, 0);
System.out.println(arr);
}
Output : Viral
append() : This method concatenates the given argument with current string. After the
concatenation has been performed, the compiler inserts a call to toString( ) to turn the
modifiable StringBuffer back into a constant String.
Syntax : StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
Example :
class A
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("Hello ");
s.append("Prof ").append(“VSP”); // s.append("Prof ").append(“VSP”).toString();
System.out.println(s);
}
}
Output : Hello Prof VSP
insert() : Inserts one string into another.
Syntax : StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
Example :
class A
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("Hello VSP");
s.insert(6, "Prof ");
System.out.println(s);
}
}
Output : Hello Prof VSP
reverse() : reverse the characters within a StringBuffer object
Syntax : StringBuffer reverse( )
Example :
class A
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("VSP");
s.reverse();
System.out.println(s);
}
}
Output : PSV
delete () : deletes a sequence of characters from the invoking object
deleteCharAt () : deletes the character from the specified index
Syntax : StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
Example :
class A
{
public static void main(String args[])
{