Friday, 19 October 2018

String, String Buffer & String Builder (Part 3)




Hey Guyz,

There are some difference between String, String Buffer and String Builder. We discuss String and its methods. We have some more methods in String buffer and Builder to modify strings. 


String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.








String, String Buffer and String Builder



String and String Buffer



String Buffer and String builder is almost the same (excepts 2-3 differences).

You can refer this site -- gives the proper difference between these terms. 
String vs StringBuffer vs StringBuilder  ---  www.journaldev.com 




Strings In Java (Part 1)




Hey guys,

Today we are going to start a new topic and this topic is very important for interview purpose as well as for job/doing coding.


" String is a CLASS in Java.."  String is a sequence of characters.

There are two ways to get string object in java

  1. using new keyword
  2. using literal constant


1 ) Using a new keyword. 

whenever we want to create an object, we must know about the constructor of it.
String class has 2 Constructors.
  1. no argument constructor [ String() ]
  2. one argument constructor [ String(String s) ]
Note - Both are same no difference, just a way of writing (Syntax) is different because of the constructor. 




2) literal Way



Question  -- what is the diffrence between String s = new String("Hello"); and String s = "Hello";  ?

Answer -

String s1="hello";

The string literal "hello" will be created and this would be placed in the String constant pool. (constant pool is a special memory for String literal. )

Hence one object is created with s1 as a reference variable to it.

Also, when any other reference variable is created in future with the same value as "hello", it would refer to the already created String literal present in the constant pool rather than creating a new one.


String s1=new String("hello");

In this case, two objects would be created.One would be the same string literal as above and would be placed in String constant pool. The second object would be created and placed in the normal(non pool) memory and s1 would refer to it. The second object would act as a normal object in a heap.



In short,

String S1 = new String("Hello");
This statement creates a String object in the Heap Memory.

String S1 = "Hello";
This statement creates a String literal with value "Hello" in the String Pool.

For more understanding, let's take 3 cases.

Case 1. String Object and Literal

String s1 = "Hello";
String s2 = new String("Hello");

Since s1 and s2 are reference variables, they'd be pointing at their respective memory locations right ?

s1 points to String Pool's location
and
s2 points to Heap Memory location.

Now testing if they're equal:
if(s1 == s2) 
would return false, as the reference variables are checked.

Whereas
s2.equals(s1) 
will return true as equals function checks the individual characters in both the reference variables.


An Interesting Fact:
"String Literal Pool" is a memory area that contains all the string literals used in the program.
Whenever a new literal is encountered, the JRE checks if it exists in the String pool or not. It does not contain duplicate literals.

If you create two reference variables with the same value "Hello", they'd both point to the same location.

Case 2: Two String Literals:

Eg:
String s1 = "Hello";
String s2 ="Hello";

if(s1==s2) 
will be true.

Case 3: One string object and anonymous literal

String s1 = new String("Hello");

if(s1 == "Hello")
will be false.

In this case, "Hello" creates a literal in the pool which has a different memory location than S1's heap memory.


Source  -- quora 






Strings in Java (Part 2)




Hey Friendz.

In this post, we are going to discuss string-specific methods. these methods are very useful, at the time of programming.

There are more than 40 methods in Java 1.7. Here, we are going to discuss the most common methods.



char charAt(int index)

Returns the character at the specified index.

String concat(String str)

Concatenates the specified string to the end of this string.

boolean endsWith(String suffix)

Tests if this string ends with the specified suffix.

int length()

Returns the length of this string.

boolean matches(String regex)

Tells whether or not this string matches the given regular expression.

String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

String[] split(String regex)

Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)

Tests if this string starts with the specified prefix.

char[] toCharArray()

Converts this string to a new character array.

String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

String substring(int beginIndex)

Returns a new string that is a substring of this string.

String toLowerCase()

Converts all of the characters in this String to lower case using the rules of the default locale

String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the default locale.

String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.


♣♣  Compaire two Strings

  1. Based On Memory Location [ == ]
  2. Based On String sequence [ .equals() ]
  3. Based On Lexicographical order [ compaireTo ]

refer this website  -- www.baeldung.com






Here are the links and videos... You can find good programs here and please understand all logical concept from here and practice all logical programs...to become a good java developer.

beginnersbook -- Go Here

Java CodeExample -- Go Here (one more good site) 




# Videos 




String Part 1




String Part 2





Practice Programming Question In JAVA (Part 2)




Hey,

Here are some logical programming question that may ask in viva or an interview. Don't by heart (mug up) these programs to try to do it by your self.
If you find any difficulty to solve these programs please comment on this post I will mail you the solutions.


# Some Logical Programs


Ques 1 - WAP of Fibonacci sequence, ask a number from user and print n terms of that Fibonacci Series.


Ques 2 - WAP to generate TABLE in proper formate

  • if the number is negative --- o/p will be a negative number
  • if the number is positive --- o/p will be table generate 
  • if the number is string --- o/p will be enter number only.


Ques 3 - WAP to generate Factorial 
  1. With recursion 
  2. Without recursion


Ques 4 - WAP to print your name 100 times without using a loop. [Hint - using recusion]


Ques 5 - WAP to find the factorial of a given number n.
  1. With recursion 
  2. Without recursion


Ques 6 - WAP to find the prime number from 2 to n (n is input from the user).



# Some Array Question


Ques 7 -  arr[25] = { 1,5,8,7,19,14,5,7,2,12,31,78,3,2,4,19,17,8,5,77,9,19.45,54,20 }
  1. Find the duplicates in given array?
  2. Sort the array 
    1. Ascending order
    2. Descending order
  3. Sort the array and display only alternate elements in the array.
  4. Find the second largest and second smallest element in the array.
  5. Find the sum of elements in the array
    1. Including Duplicate elements 
    2. Excluding Duplicate elements(add once)




Array ( Part 2 )




Hey, guys


# There are two types of array.

  1.  Single Dimensional Array 
  2.  Multidimensional Array


# Single Dimensional Array


whatever we learn in the previous post is all about basics of an array and all pics are belongs to "Single Dimensional Array".

Now, We are going to discuss on syntax and program on it.



It is a two-step Process...

Step 1 )
These are three (3) ways to Declare An Array...




Step 2 )
Way to instantiation/initialization of an array....





This step is a combination of Step 1 and Step 2




This is a basic program to declare, initialize and display character array.






# Multi-Dimensional Array


Multi-Dimensional Array is a " MATRIX ". It has a ROW and  COLUMN .
But  In java , we have somthing called "JAGGED ARRAY".



A jagged array in Java is a multi-dimensional array comprising arrays of varying sizes as its elements. It’s also referred to as “an array of arrays” or “jagged array”.



But you don't need to bother about terms because it works same as 2D Array (Multi-Dimensional Array) but internally it different with 2D Array.








If you want to understand it in more deep and better ways --- go to this site -- "  www.baeldung.com " Detailed Description.






Array ( Part 1 )




Today, we are going to learn ARRAY in java. An array is the most common and useful data structure in most of the programming language like C, C++, Java, python etc.



Ques - What is Array?

Answer - Array is a collection of homogeneous elements referred under a common name.




- Array is a group of the same kind of element. ( blue colour numbers )

- Array is homogeneous means all kind of elements of the same type. (all are int, double etc).

- Array referred under a common name (there is the only name for accessing it). 

- Array is an indexed based collection means it a group of element with some index number. ( red colour numbers )

- Array index always starts from 0 (zero) and end with size -1.

- Array is a fixed size data structure.

- Array is stored in a linearly (it is also called linear list).

- Hence, we can also difine Array As -  



Array is a data Structure that defines an index collection of a fixed number of homogeneous data elements and referred under a common name. 



For Example :




 Here,

"a" is the array name.

0 1 2 3 4  are the index number. [index always start from 0 and end with size-1 i.e., 4]

1 2 4 8 16 are the group of integer elements.

"a[0]" "a[1]" "a[2]" "a[3]" are index numbers to access each element separatly 

"a[0]" it is pronounced as " a " of  0. [ Array_Name  of  Index_Number ]




# Types Of Array


1) Single Dimension Array
2 ) Multi-dimensional Array



Will talk about these in our next post.....






Variables




Today, we are going to discuss Variables and its type.

It is a very important question in an examination/interviews and these concepts are very useful when it comes to writing code.



Variables - " A variable is a container that holds values that are used in a program ".


In Java, three types of variable...
  1. Local Variable 
  2. Instance Variable 
  3. Static Variable 




# Local Variable 



- A variable which declares inside a block.

Ques - What is block?
Ans - Except class, anything has " { } " open and close curly braces are called block.

For Example - methods, loops etc.

- Local Variable is not accessible outside the block, where it is declared.

- Life of the local variable is the life of the block.

- No default value for Local Variables.

- Local Variable value must be explicitly initialized before its use.






Now, There are two types of the variable which can be initialized inside the class.
  1. Instance Variable 
  2. Static Variable 







# Instance Variable 



- A variable which is directly declared inside the class is called instance variable.

- Instance variable is used to store object specific properties/values.

- Each object may have its own value for that property ---- for this kind of property we should use instance variable to store values.







# Static Variable 




- A variable which is directly declared inside the class with the static keyword is called static variable.

- only one copy of in memory for static variables and all objects share its value.

- Life of a static variable is the life of a class.

- memory is assigned to static variables when the class is loaded in JVM.

- defaults values are assigned to static variables.


  


# Example:-




   


Suppose there is 1000 employ in a company (let's say Atom+ Company ), now all employs has its own employ ID and name but all employ has the same company name.


For object specific properties/values --- we can use Instance variables. -- like name & employID.


For Common object properties --- we can use static variables. -- like Company Name.






Practice Programming Questions in Java (Part 1)




Hey,

As I promised, I am going to give you some simple question based on

  • Simple Input/Output
  • Based on some Condition
  • Based on loops


And in case if you want answers to these question...then you have to comment your email id at the end of this post and I will mail you.


# Program...


1 - Write a program to get two numbers from the user and print its sum on the console.

2 - Write a program to get three numbers from the user and print the Largest of Three Numbers.

3 - Write a program to get 1 number from the user and print all the even number from 2 to userNumber.
[Using all loops]

4 - Write a program to get 1 number from the user and print all the odd number from 2 to userNumber.
[Using all loops]

5 - Write a program to print your name 100 times without using loop.
[Hint - You can do that using recursion. ( it is not the only way to do that. )]