Unit 2 Answers
Unit 2 Answers
StringBuffer
Purpose:String Buffer class creates strings that can be modified in terms
of length and content.
Thread Safety:it ensures that multiple threads can work on the same object
without conflict.
Performance: Slower than StringBuilder due to synchronization.
User Case: Use StringBuffer when working in a multi-threaded environment
where thread safety is necessary.
public class StringBufferExample{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("Hi");
buffer.append("Java 8");
System.out.println("StringBufferExample" +buffer);
}
}
Q. What are wrapper class and explain data conversion using valueoff()
method with example.
In Java, valueOf() method converts data from its internal form into a
human-readable form. It is used to convert data types into their
corresponding wrapper objects or String representation.
}
Class TestThis2{
Public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
18. }}
Output
111 ankit 5000
112 sumit 6000
Output:
Hello n
Hello m
Output:
Method is invoked
6. This can be used to return the current class instance from the
method.
Class B{
A4 obj;
B(A4 obj){
This.obj=o
bj; 5. }
Void display(){
System.out.println(obj.data);//using data member of A4 class 8.
}
9. }
Class A4{
Int
data=10; 12. A4(){
B b=new B(this);
b.display();
15. }
Public static void main(String args[]){
A4 a=new A4();
18. }
19. }
Output:10
Class Teststringcomparison2{
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
2. By Using == Operator
By using == operators
Class Teststringcomparison3{
Public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
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)
}
}
Output
True
False
3. By compareTo()
Assume that s1 and s2 are two different String objects. If:
s1 == s2: The method returns 0.
s1 > s2: The method returns a positive value.
s1 < s2: The method returns a negative value.
Class Teststringcomparison4{
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
Q. How to declare and initialize One Dimensional and two -dimensional
array with example?
-