Thursday 12 October 2023

String Handling in Java

String Handling

Java implements strings as objects of type String.

Java provides a full complement of features that make string handling convenient. For example, Java has methods to compare two strings, search for a substring, concatenate two strings, and change the case of letters within a string.

 

Strings are immutable. That is, once a String object has been created, the characters that comprise that string cannot be changed. The original string is left unchanged.

 

 To create mutable strings (ie strings whose content can be changed), Java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they are created.

 

String objects can be constructed in several ways, making it easy to obtain a string when needed.


String Constructors

String s = new String(); //default

 

char ch[] = { 'a', 'b', 'c' };

String s = new String(ch); //converting array of characters to string

 

char ch[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

String s = new String(ch, 2, 3);  //s="cde"   from second position to 3 characters

 

String(String strObj)   //copy constructor

   

    char c[] = {'J', 'a', 'v', 'a'};

    String s1 = new String(c);

    String s2 = new String(s1);

 

byte ascii[] = {65, 66, 67, 68, 69, 70 };

String s1 = new String(ascii);       //s1=ABCDEF

 

byte ascii[] = {65, 66, 67, 68, 69, 70 };

String s1 = new String(ascii,3,2);       //s1=DE

 

String(StringBuffer strBufObj)    //StringBuffer is a pre-defined class in Java

 

// Construct one String from another.

class MakeString

{

  public static void main(String args[])

  {

char c[] = {'J', 'a', 'v', 'a'};

String s1 = new String(c);

String s2 = new String(s1);

System.out.println(s1);

System.out.println(s2);

 }

}

String Concatenation

In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings:

 

   String age = 10;

   String s = “He is “ + age + ” years old”; 

Java String class methods

The java.lang.String class provides many useful methods to perform operations on a sequence of char values.

 

Character Extraction

The String class provides several ways in which characters can be extracted from a String object. Some of the methods defined in the String class for this purpose are:

  • ·        charAt()
  • ·        getChars()
  • ·        getBytes()
  • ·        toCharArray()

 

charAt()

The charAt() method returns a char value at the given index number.

The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException if the given index number is greater than or equal to this string length or a negative number.

public class CharAtExample{  

public static void main(String args[]){  

String name="Strings in Java";  

char ch=name.charAt(4);   //returns the char value at the 4th index  

System.out.println(ch);  

}}  

 

getChars()

To extract more than one character at a time, use the getChars() method. It has this general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

 

Example

String s = "This is a demo of the getChars method.";

            int start = 10;

            int end = 14;

            char buf[] = new char[end - start];

 

            s.getChars(start, end, buf, 0);

            System.out.println(buf);  //will store demo in buf

 

getBytes()

There is an alternative to getChars( ) that stores the characters in an array of bytes. This method uses the default character-to-byte conversions provided by the platform. Here is its simplest form:

byte[ ] getBytes( )

 

toCharArray( )

To convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. It has this general form:

 

char[ ] toCharArray( )

 

Java String length()

The java string length() method length of the string. It returns the count of total number of characters. The length of the Java string is the same as the Unicode code units of the string.

public class LengthExample{  

public static void main(String args[]){  

String s1="java";  

String s2="python";  

System.out.println("string length is: "+s1.length());  //4 is the length of javatpoint string  

System.out.println("string length is: "+s2.length());  //6 is the length of python string  

}}  

Java String substring()

The java string substring() method returns a part of the string.

We pass the begin index and end index number position in the Java substring method where the start index is inclusive and the end index is exclusive. In other words, the start index starts from 0 whereas the end index starts from 1.

There are two types of substring methods in Java string.

1.    public String substring(int startIndex)  


2.    public String substring(int startIndex, int endIndex)  

 

Example

public class SubstringExample{  

public static void main(String args[]){  

String s1="java Program";  

System.out.println(s1.substring(2,4));//returns va  

System.out.println(s1.substring(2));//returns va Program  

}} 

Java String equals()

The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

The String equals() method overrides the equals() method of the Object class.

public class EqualsExample{  

public static void main(String args[]){  

String s1="hello";  

String s2="hello";  

String s3="HELLO";  

String s4="python";  

System.out.println(s1.equals(s2));//true because content and case is same  

System.out.println(s1.equals(s3));//false because case is not same  

System.out.println(s1.equals(s4));//false because content is not same  

System.out.println(s1.compareTo(s4));

}}  

 

Java String compareTo

   The String compareTo() method compares values lexicographically and returns an integer value that describes if the first string is less than, equal to, or greater than the second string.

Suppose s1 and s2 are two string variables. If:

s1 == s2 : 0

s1 > s2   : positive value (difference of character value)

s1 < s2   : negative value

 

Example

public static void main(String args[])

{  

String s1="hello";  

String s2="hello";  

String s3="meklo";  

String s4="hemlo";  

String s5="flag";  

System.out.println(s1.compareTo(s2));     //0 because both are equal  

System.out.println(s1.compareTo(s3));//because "h" is 5 times lower than "m"  

System.out.println(s1.compareTo(s4));//1 because "l" is 1 times lower than "m"  

System.out.println(s1.compareTo(s5)); //2 because "h" is 2 times greater than "f"  

}

Java String concat

The java string concat() method combines the specified string at the end of this string. It returns a combined string. It is like appending another string.

public class ConcatExample{  

public static void main(String args[]){  

String s1="java string";  

s1.concat("is immutable");  

System.out.println(s1);  

s1=s1.concat(" is immutable so assign it explicitly");  

System.out.println(s1);  

}}  

Java String isEmpty()

The java string isEmpty() method checks if this string is empty or not. It returns true if the length of the string is 0 otherwise false. In other words, true is returned if the string is empty otherwise it returns false.

The isEmpty() method of the String class has been included in the Java string since JDK 1.6.

public class IsEmptyExample{  

public static void main(String args[]){  

String s1="";  

String s2="java";  

  

System.out.println(s1.isEmpty());  

System.out.println(s2.isEmpty());  

}}  

 

Friday 18 August 2023

Daily Coding Problem (18-8-2023)

 Good morning! Here's your coding interview problem for today.

This problem was asked by Google.

You are given an array of nonnegative integers. Let's say you start at the beginning of the array and are trying to advance to the end. You can advance at most, the number of steps that you're currently on. Determine whether you can get to the end of the array.

For example, given the array [1, 3, 1, 2, 0, 1], we can go from indices 0 -> 1 -> 3 -> 5, so return true.

Given the array [1, 2, 1, 0, 0], we can't reach the end, so return false.

You can write the program in any programming language.

Monday 7 August 2023

Operation Research MCQ

 1. What type of approach does operation research have?

a) multi-disciplinary     b) scientific                 c) intuitive             d) all of the above

2. OR approach is typically based on the use of

a) Physical model b) Mathematical model c) Iconic model d) Descriptive model

3. Which of the following is not a characteristic of the LP model?

a) alternative courses of action

b) an objective function of maximization type

c) limited number of resources

d) non-negativity condition on the value of decision variables

4. What is the objective function in linear programming problems?

a) A constraint for available resource

b) An objective for research and development of a company

c) A linear function in an optimization problem

d) A set of non-negativity conditions

5. Which statement characterizes standard form of a linear programming problem?

a) Constraints are inequalities of any type b) Constraints are a set of linear equations

c) Constraints are inequalities of >= type d) Constraints are inequalities of <= type

6. In graphical representation, what is the name of the bounded region?

a) solution b) basic solution c) feasible solution d) optimal solution

7. If two constraints do not intersect in the positive quadrant of the graph, then ____________.

a) the problem is infeasible                             b) the solution is unbounded

c) one of the constraints is redundant             d) none of the above

8. What type of LPP can be solved using graphical method?

a) LPP with two decision variables b) LPP with three decision variables

c) LPP with one decision variable         d) LPP with any number of decision variables

9. How many columns will there be in the Simplex table, if there are ‘M’ original variables and ‘n’ introduced variables?

a) M + n b) M - n c) M + n + 1 d) M + n - 1

10. Name the variable that is added to the constraints of type ‘=’.

a) surplus variable b) dummy variable c) slack variable d) artificial variable

11. If all aij values in the entering variable column of the simplex table are negative, then ______________.

a) solution is unbounded                         b) solution is degenerate

c) there exists no solution                 d) there are multiple solutions

12. A BFS of an LPP is said to be ________, if at least one of the basic variables is zero.

a) Infeasible b) non-degenerate c) Feasible d) Degenerate

13. A minimization problem can be converted into a maximization problem by changing the sign of coefficients in the ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐

a) objective function only                             b) constraints only

c) both objective function and constraints     d) basis variables only

14. All the constraints are expressed as equations and the right-hand side of each constraint, and all variables are non-negative is called _______

a) Standard form of LPP                 b) Simplex form of LPP

c) Canonical form of LPP                 d) General form of LPP

15. If dual has an unbounded solution, primal has _________.

a) no feasible solution b) unbounded solution c) feasible solution d) an optimal solution

16. If a primal LP problem has a finite solution, then the dual LP problem should have __________.

a) finite solution     b) infeasible solution c) unbounded solution d) feasible solution

17. The dual of the dual is ______________.

a) dual-primal b) primal-dual c) primal d) dual

18. How are the dual constraints for the maximization LP problem written?

a) Σ aij yi ≥ cj             b) Σ aji yi ≥ cj         c) Σ aij yi ≤ cj                     d) Σ aji yi ≤ cj

19. The right-hand side constant of a constraint in a primal problem appears in the corresponding dual as __________.

a) a coefficient in the objective function b) a right-hand side constant of a constraint

c) an input-out coefficient                         d) none of the above

20. Variable in dual problem which can assume negative values, positive values or zero value is classified as _________________.

a) slack variable     b) restricted variable c) unrestricted variable d) decision variable

21. The dummy source or destination in a transportation problem is added to _____________ 

a) satisfy rim conditions                                             b) prevent solution from becoming degenerate

c) ensure that total cost does not exceed a limit     d) the solution not be degenerate

22. Which of the following methods is used to verify the optimality of the current solution of the transportation problem?

a) Least cost method                                         b) Vogel’s approximation method

c) North-west corner method                                 d) Modified Distribution Method

23. If demand is lesser than supply then dummy demand node is added to make it a __________

a) Simple problem                                                     b) Balanced problem

c) Transportation problem                                     d) Assignment problem

24. One disadvantage of using North-West Corner rule to find initial solution to the transportation  problem is that ___________.

a) It is complicated to use                                 b) It does not consider cost of transportation

c) It leads to a degenerate initial solution         d) It does not lead to optimal solution

25. In an assignment problem involving 5 workers and 5 jobs, total number of assignments possible are ______________

a) 10             b) 25                                 c) 5                                    d) 1

26. In assignment problem of maximization, the objective is to maximize the _______.

a) cost     b) time                         c) profit                           d) loss

27. Both transportation and assignment problems are members of a category of LP problems called ______

a) shipping problems                     b) network flow problem

c) logistic problems                     d) routing problems

28. In sensitivity analysis of the coefficient of the non-basic variable in a cost minimization LP problem, the upper sensitivity limit is ________________.

a) original value + Lowest positive value of improvement ratio

b) original value – Lowest absolute value of improvement ratio

c) positive infinity

d) negative infinity

29. The entering variable in the sensitivity analysis of objective function coefficients is always a ____.

a) decision variable         b) non-basic variable c) basic variable d) slack variable

30. A change in the objective function for a non-basic variable can affect _____________.

a) cj – zj values of all non-basic variables             b) cj – zj values of all basic variables

c)  Only the cj – zj value of that variable                     d) the initial basic feasible solution


ANSWER

1.a

2.  b

3.  b

4. c

5. a

6. c

7. a

8. a

9. a

10. d

11. a

12. d

13. a

14. c

15. a

16. a

17. c

18.  b

19.  a

20. c

21. a

22. d

23. b

24. b

25. c

26. c

27. b

28. c

29. d

30. c