Вы находитесь на странице: 1из 4

Q41.) Create a hashSet class object. Add element, remove and determine size.

Find whether hashSet is empty or not and find hashSet object is there or not.

import java.util.*;

public class HashSetDemo {


public static void main(String args[]) {

HashSet <String> h = new HashSet <String>();

h.add("Java");
h.add("is");
h.add("easy");

System.out.println("Values before remove= "+h);

boolean isremoved = h.remove("is");

System.out.println("Return value after remove= "+isremoved);

System.out.println("Values after remove= "+h);

System.out.println("Size of HashSet= "+h.size());


System.out.println("HashSet is Empty= "+h.isEmpty());
System.out.println("Check if 'is' is there in the HashSet= "+h.contains("is"));
}
}

Output:

Values before remove= [Java, is, easy]


Return value after remove= true
Values after remove= [Java, easy]
Size of HashSet= 2
HashSet is Empty= false
Check if 'is' is there in the HashSet= false
Q42.) Write a program which creates a list reference object which stores
array list into it. A box class is readily available for usage. The list has 3 boxes.
Extend the program to find if box1=box2 or box2=box3 or box3=box1.

import java.util.*;

public class Box3 {


int a,b,c;

Box3(int a,int b,int c)


{
this.a=a;
this.b=b;
this.c=c;
}

void print()
{
System.out.println("Value of a= "+a);
System.out.println("Value of a= "+b);
System.out.println("Value of a= "+c);
}

public static void main(String[] args) {


Box3 b1=new Box3(10,20,30);
Box3 b2=new Box3(10,20,30);
List <Box3> L1=new ArrayList<Box3>();
L1.add(b1);
L1.add(b2);
b1.print();
System.out.println("Does object 'b2' exists in the list=
"+L1.contains(b2));
System.out.println("Is object 'b2' equal to object 'b1'=
"+b1.equals(b2));
}

}
Output:

Value of a= 10
Value of a= 20
Value of a= 30
Does object 'b2' exists in the list= true
Is object 'b2' equal to object 'b1'= false
Q43.) Write a program which attempts to write “Hello World” to a file. After
writing, the program attempts to read the string “Hello World” from the
same file and prints it to the screen.

package javaprograms;
import java.io.*;
public class File1 {

public static void main(String args[])


{
try{
FileOutputStream fout=new
FileOutputStream("C:\\Users\\DELL\\Downloads\\test.txt");
FileInputStream fin=new
FileInputStream("C:\\Users\\DELL\\Downloads\\test.txt");
String s="Hello World";
int i=0;
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}

}
}

Output:

Hello World

Вам также может понравиться