0% found this document useful (0 votes)
3 views

java unit 4 tt2

The document provides a comprehensive overview of various Java programming concepts, including palindrome checking, string manipulation, the StringBuffer class, generics, and the Java Collection framework. It includes example code snippets for each topic, demonstrating practical implementations and differences between classes like String and StringBuffer. Additionally, it discusses the performance implications of using these classes and provides a generic method for adding numbers.

Uploaded by

Tushar salunkhe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java unit 4 tt2

The document provides a comprehensive overview of various Java programming concepts, including palindrome checking, string manipulation, the StringBuffer class, generics, and the Java Collection framework. It includes example code snippets for each topic, demonstrating practical implementations and differences between classes like String and StringBuffer. Additionally, it discusses the performance implications of using these classes and provides a generic method for adding numbers.

Uploaded by

Tushar salunkhe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Subject- JAVA Unit-4-

Que-1- write a java program to check whether the entered string is palindrome
or not (5 marks)

Ans= import java.util.Scanner;

class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);

System.out.println("Enter a string:");
str = sc.nextLine();

int length = str.length();

for ( int i = length - 1; i >= 0; i-- )


rev = rev + str.charAt(i);

if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");

}
}
Program Output:

Enter a string:
radar

radar is a palindrome
Que-2- What is string? Explain with example (5 marks)

Ans=In Java, a string is an object that represents a number of character


values. Each letter in the string is a separate character value that makes up
the Java string object. Characters in Java are represented by
the char class. Users can write an array of char values that will mean the
same thing as a string.

The following is an example of how character values make up the char


array ch.

char[] ch = {'t','e','c','h','t','a','r','g','e','t'};
String s2 = new String (ch);

This means the same thing as the example below.

String s2 = "techtarget";

In the example, each letter of the string is represented by a character.


Although strings created using the string class are immutable, strings
created using combinations of characters can be changed. There are
several utility string methods that can be used to alter strings,
including split(), toLowerCase(), toUpperCase(), length() and v
alueOf(). These string methods can do the following:

 split strings at a specified point, such as white spaces;


 make the string lowercase or uppercase;
 give the string length; and
 provide the value of a given character in a string.

The following shows the use of valueOf() for determining the value of a
letter in the above char array ch.
public class StringValueOfExample5 {
public static void main(String[] args) {
char[] ch =
{'t','e','c','h','t','a','r','g','e','t'};
String s2 = new String (ch);
String v = String.valueOf(ch[1]);
System.out.println(v);
}
}

The example above prints the value of the first position in the character
array ch. The exact print statement is: e.

Utility methods like valueOf() and toLowerCase() are only used with
strings that are immutable. They perform operations on strings, but they do
not change the string itself. To create mutable strings that can be changed,
the StringBuilder() and StringBuffer() classes are used.

Below are examples of string mutability using these classes.

String concatenation, which is the process of linking strings together, can


be done using the append() method to print the sentence "Ben eats
vegetables."

class Example {
public static void main(String args[]) {
StringBuilder x = new StringBuilder("Ben ");
x.append("eats vegetables");
System.out.println(x);
}
}

Reverse a string using the reverse() method to print "selbategev stae


neB."

class Example{
public static void main (String args[]) {
StringBuilder x = new StringBuilder ("Ben eats
vegetables");
x.reverse();
System.out.println(x);
}
}

Que-3- Discuss below methods of StringBuffer class (10 marks)

1. Delete =
The delete() method of the StringBuffer class deletes the string from the
specified beginIndex to endIndex-1.
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.delete(0, 2);
System.out.println(sb);
}
}
Output : llo
2. Insert=
The insert() method inserts the given string with this string at the given
position.
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now original string is changed
System.out.println(sb);
}
}
Output : HJavaello
3. Append=
The append() method concatenates the given argument with this string.
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java");
// now original string is changed
System.out.println(sb);
}
}
Output : Hello Java

4.Replace=

The replace() method replaces the given string from the specified beginIndex and
endIndex-1.

import java.io.*;
class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello");

sb.replace(0, 3, "Java");

System.out.println(sb);

Output : Javalo

5.Reverse=

The reverse() method of the StringBuilder class reverses the current string.

import java.io.* ;

class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello");

sb.reverse();

System.out.println(sb);

Output : olleH
Que-4- What is Generics class? Explain with example (5 marks)

Ans=A Generic class simply means that the items or functions in that
class can be generalized with the parameter(example T) to specify that we
can add any type as a parameter in place of T like Integer, Character,
String, Double or any other user-defined type.
Example: Single type parameter
class Solution<T>
{
T data;
public static T getData(){
return data;
}
}
public class Pair<K, V> {

private K key;
private V value;

public Pair(K key, V value) {


this.key = key;
this.value = value;
}

public K getKey() { return key; }


public V getValue() { return value; }
}

Here in this example, we can use the object or instance of this class as
many times with different Parameters as T type. If we want the data to be
of int type, the T can be replaced with Integer, and similarly for String,
Character, Float, or any user-defined type. The declaration of a generic
class is almost the same as that of a non-generic class except the class
name is followed by a type parameter section. The type parameter section
of a generic class can have one or more type parameters separated by
commas.
We can write a single generic method declaration that can be called with
arguments of different types. Based on the types of arguments passed to
the generic method, the compiler handles each method call appropriately.
Following are the rules to define Generic Methods
 All generic method declarations have a type parameter section
indicated by angle brackets <> that precedes the method’s return type.
 Each type parameter section can contain one or more type
parameters separated by commas. A type parameter or a type
variable is an identifier that specifies a generic type name.
 The type parameters can be used to declare the return type which is
known as actual type arguments.
 A generic method’s body is declared like that of any non-generic
method. The point to be noted is that type parameter can represent
only reference types, and not primitive types (like int, double, and
char).
Advantages of Java Generics
1. Type-Safety: One can hold only a single type of objects in generics.
2. Type Casting Is Not Required: There is no need to typecast.
Example:
Before Generics
List l= new ArrayList();
l.add("India");
String s = (String) l.get(0); // typecasting

After Generics, typecasting of the object is not required


List<String> l = new ArrayList<String>();
l.add("hello");
String s = l.get(0);

3. Compile -Time Checking: It checks all the errors of datatype related


to generics at the time of compile-time so the issue will not occurat the
time of runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32); //Compile Time Error

For an instance of Generic class


BaseType <Type> object = new BaseType <Type>();

Que-5- Write a java program to perform below operations of string input given
by the user.

1. Converting string into upper case=


2. public class changeCase {
3. public static void main(String[] args) {
4.
5. String str1="Great Power";
6. StringBuffer newStr=new StringBuffer(str1);
7.
8. for(int i = 0; i < str1.length(); i++) {
9.
10. //Checks for lower case character
11. if(Character.isLowerCase(str1.charAt(i))) {
12. //Convert it into upper case using toUpperCase() func
tion
13. newStr.setCharAt(i, Character.toUpperCase(str1.charAt
(i)));
14. }
15. //Checks for upper case character
16. else if(Character.isUpperCase(str1.charAt(i))) {
17. //Convert it into upper case using toLowerCase() funct
ion
18. newStr.setCharAt(i, Character.toLowerCase(str1.charAt
(i)));
19. }
20. }
21. System.out.println("String after case conversion : " + newSt
r);
22. }
23. }

Output:

String after case conversion: gREAT pOWER

2.Check whether two strings are equal=

1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }

Output:

true
true
false

Que-6- Discuss collection framework in detail (5 marks)

Ans= The Collection in Java is a framework that provides an architecture


to store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Methods of Collection interface

There are many methods declared in the Collection interface. They are as
follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this


collection.

2 public boolean It is used to insert the specified


addAll(Collection<? extends E> c) collection elements in the invoking
collection.

3 public boolean remove(Object It is used to delete an element from the


element) collection.

4 public boolean It is used to delete all the elements of


removeAll(Collection<?> c) the specified collection from the
invoking collection.
5 default boolean It is used to delete all the elements of
removeIf(Predicate<? super E> the collection that satisfy the specified
filter) predicate.

6 public boolean It is used to delete all the elements of


retainAll(Collection<?> c) invoking collection except the specified
collection.

7 public int size() It returns the total number of elements


in the collection.

8 public void clear() It removes the total number of


elements from the collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean It is used to search the specified


containsAll(Collection<?> c) collection in the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here,


the runtime type of the returned array
is that of the specified array.
14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream


parallelStream() with the collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the


collection as its source.

17 default Spliterator<E> It generates a Spliterator over the


spliterator() specified elements in the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of the


collectio

Que-7- Explain difference between string and stringbuffer class with example
(10 marks)
Ans=

Performance Test of String and StringBuffer

ConcatTest.java

1. public class ConcatTest{


2. public static String concatWithString() {
3. String t = "Java";
4. for (int i=0; i<10000; i++){
5. t = t + "Tpoint";
6. }
7. return t;
8. }
9. public static String concatWithStringBuffer(){
10. StringBuffer sb = new StringBuffer("Java");
11. for (int i=0; i<10000; i++){
12. sb.append("Tpoint");
13. }
14. return sb.toString();
15. }
16. public static void main(String[] args){
17. long startTime = System.currentTimeMillis();
18. concatWithString();
19. System.out.println("Time taken by Concating with String: "+(Syst
em.currentTimeMillis()-startTime)+"ms");
20. startTime = System.currentTimeMillis();
21. concatWithStringBuffer();
22. System.out.println("Time taken by Concating with StringBuffer: "
+(System.currentTimeMillis()-startTime)+"ms");
23. }
24. }

Output:

Time taken by Concating with String: 578ms


Time taken by Concating with StringBuffer: 0ms

Que-8- Write a generic method to perform addition of two number (5 marks)

1. Ans= public class AddNumbers<T extends Number> {


2. private T num1;
3. private T num2;
4.
5. public AddNumbers(T num1, T num2) {
6. this.num1 = num1;
7. this.num2 = num2;
8. }
9.
10. public T add() {
11. if (num1 instanceof Integer) {
12. return (T) (Integer) (num1.intValue() + num2.intValue());
13. } else if (num1 instanceof Double) {
14. return (T) (Double) (num1.doubleValue() + num2.doubleValue
());
15. } else {
16. return null;
17. }
18. }
19.
20. public static void main(String[] args) {
21. AddNumbers<Integer> intAdder = new AddNumbers<>(2, 3);
22. Integer intResult = intAdder.add();
23. System.out.println("Integer Result: " + intResult);
24.
25. AddNumbers<Double> doubleAdder = new AddNumbers<>(2.
5, 3.5);
26. Double doubleResult = doubleAdder.add();
27. System.out.println("Double Result: " + doubleResult);
28. }
29. }

Output:

Integer Result: 5
Double Result: 6.0

In this example, we have created a generic class called AddNumbers that


takes two parameters of any data type that extends the Number class. The
add() method checks the type of the parameters and returns their sum. In
the main method, we have created instances of the class with integer and
double parameters, and we have printed the results of the addition.

Que-9- Explain bounded type with example (10 marks)

Ans= There may be times when you want to restrict the types that can be
used as type arguments in a parameterized type. For example, a method
that operates on numbers might only want to accept instances
of Number or its subclasses. This is what bounded type parameters are for.

To declare a bounded type parameter, list the type parameter's name,


followed by the extends keyword, followed by its upper bound, which in
this example is Number. Note that, in this context, extends is used in a
general sense to mean either "extends" (as in classes) or "implements" (as
in interfaces).

public class Box<T> {

private T t;

public void set(T t) {


this.t = t;
}

public T get() {
return t;
}

public <U extends Number> void inspect(U u){


System.out.println("T: " +
t.getClass().getName());
System.out.println("U: " +
u.getClass().getName());
}

public static void main(String[] args) {


Box<Integer> integerBox = new Box<Integer>();
integerBox.set(new Integer(10));
integerBox.inspect("some text"); // error: this
is still String!
}
}

By modifying our generic method to include this bounded type parameter,


compilation will now fail, since our invocation of inspect still includes
a String:

Box.java:21: <U>inspect(U) in Box<java.lang.Integer>


cannot
be applied to (java.lang.String)
integerBox.inspect("10");
^
1 error
In addition to limiting the types you can use to instantiate a generic type,
bounded type parameters allow you to invoke methods defined in the
bounds:

public class NaturalNumber<T extends Integer> {

private T n;

public NaturalNumber(T n) { this.n = n; }

public boolean isEven() {


return n.intValue() % 2 == 0;
}

// ...
}

The isEven method invokes the intValue method defined in


the Integer class through n.

Multiple Bounds

The preceding example illustrates the use of a type parameter with a single
bound, but a type parameter can have multiple bounds:

<T extends B1 & B2 & B3>

A type variable with multiple bounds is a subtype of all the types listed in
the bound. If one of the bounds is a class, it must be specified first. For
example:

Class A { /* ... */ }
interface B { /* ... */ }
interface C { /* ... */ }

class D <T extends A & B & C> { /* ... */ }

If bound A is not specified first, you get a compile-time error:

class D <T extends B & A & C> { /* ... */ } //


compile-time error
Que-10- Explain importance of generics in java (5 marks)

Ans= Java is a popular programming language known for its flexibility,


reliability, and safety features. One of the key features that make Java a
versatile language is its support for generics. Generics in Java provide a way
to create type-safe classes, methods, and interfaces, which can work with
any data type. In this article, we will discuss the benefits of generics in Java.

Type safety:

One of the most significant benefits of using generics in Java is that it


enhances the type safety of your code. With generics, you can specify the
type of data that a class, method, or interface can work with. This ensures
that only the specified data types are passed to the code, preventing
runtime errors and improving the reliability of your program.

Code reuse:

Generics in Java allow you to write code that is more reusable. By specifying
a type parameter in a generic class, method, or interface, you can create
code that can work with multiple data types. This reduces code duplication,
improves code maintainability, and makes your code more efficient.

Compile-time checking:

Another significant advantage of using generics in Java is that it enables


compile-time checking of your code. This means that errors can be
detected early in the development process, rather than at runtime. This not
only improves the reliability of your program but also saves time and effort
in debugging.

Improved performance:
Generics in Java can also improve the performance of your program. By
using generics, the compiler can optimize your code, reducing the number
of casts and improving the overall performance of your program.

Greater flexibility:

Generics in Java provide greater flexibility in your programming. By


allowing you to specify the type of data that a class, method, or interface
can work with, generics make it possible to create highly adaptable and
flexible code. This can be especially useful when working with complex data
structures or when you need to write code that can work with multiple data
types.

Better documentation:

Finally, generics in Java can improve the documentation of your code. By


specifying the type parameter of a generic class, method, or interface, you
can make it clear to other developers what data types the code can work
with. This makes your code more readable, easier to understand, and more
maintainable.

Avoiding casting:

Generics in Java allow you to avoid casting, which is a common source of


bugs and errors in Java programs. By specifying the type of data that a
class, method, or interface can work with, generics eliminate the need for
casting, making your code more concise, readable, and maintainable.

Easier debugging:

Generics in Java can also make debugging easier. By providing more


information about the data types that your code can work with, generics
can help you identify errors and bugs more quickly and accurately. This can
save you time and effort in the debugging process, improving the overall
quality of your code.

Interoperability:
Generics in Java also make it easier to write code that can work with other
Java libraries and frameworks. By using generics, you can ensure that your
code is compatible with other Java code that uses generics, making it easier
to integrate your code with other software and systems.

Cleaner code:

Finally, generics in Java can help you write cleaner, more elegant code. By
using generics to create type-safe classes, methods, and interfaces, you can
avoid messy code that relies on casting, type checking, and other error-
prone techniques. This can make your code more readable, maintainable,
and efficient, and can improve the overall quality of your Java programs.

In summary, generics in Java provide a wide range of benefits, from


improving type safety and code reuse to enabling compile-time checking
and better documentation. By mastering generics, you can write more
efficient, reliable, and maintainable Java code that can work with a variety
of data types and systems. Generics in Java provide a powerful tool for
creating type-safe, reusable, and flexible code. By enabling compile-time
checking, improving performance, and providing greater flexibility, generics
can help you create more efficient, reliable, and maintainable code.
Whether you're a beginner or an experienced Java developer, mastering
generics is essential to writing high-quality Java code.

You might also like