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. )] 





Saturday 15 September 2018

Getting Input From User




In this post, we are going to learn how to get input from the User. Then will do some programming exercises to enhance our programming knowledge.

There are Different - Different ways to get an input from the console -- Go HERE.
 but right now will stick to Scanner Class, because it is the most common and easiest way.

using Scanner Class will get the input from the user,

   
- The Scanner is a  class in java.
- present in java.util package
- which allows the user to read values of various types.
- There are far more methods in class Scanner than you will need in this course.

Syntax:- 


Scanner - is a class in java.

sc - is an object of Scanner class (you can give any name).

new - is an operator which is used to make an object of a class.

Scanner() - is a constructor in Scanner Class(Don't Worry will talk it later).

System - is a class in java, represents your computer system (helps to provide us system-level methods)

in - stands for input (s).

System.in - getting input from the system and it passes as an argument to Scanner Constructor.(Don't Worry, if you are unable to get it). 



# Scanner Class has Somes Methods to get Different kinds of values from the console.

- For different types of values different, types of methods are available.
- For int type nextInt() method is used,
- For double type nextDouble() method used,
- All the methods called by using Scanner Object (sc.method name).
- for example (String value) -- we have to use next() or nextLine().


String s; // variable -- where data store
Scanner sc = new Scanner(System,in); // creating Scanner class object 
s = sc.next(); // getting input from user and assgin it to "s" variable  
sc.close(); // good practic to close resourses.







Question -- WAP to Take two number from the user and return its sum.
Answer -- 



# Code 

package scannerClass;

import java.util.Scanner;

public class Sum {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter 1st number : ");
int num1 =sc.nextInt();
System.out.println("Enter 2nd number : ");
int num2 = sc.nextInt();
int add=num1+num2;
System.out.println("Sum = "+add);
}
}








Friday 14 September 2018

Control Statements (Part 3)




In this post will strictly discuss break and continue statement and then will see some of the programs that will help you to understand the concepts.


Break - 
+ Break statement (Keyword) in java. 
+ When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
+* It can be used to terminate a case in the switch statement.


Continue - 
+ The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
+ In a for loop, the continue keyword causes control to immediately jump to the update statement(Step).
In a while loop or do/while loop, control immediately jumps to the Boolean expression.




Let's See Some Programs based on this...



Ques 1: WAP (Write a program) to get a number user (1-7) and print its equivalent day.
(without break)



Explanation -  

User enter 5 in the console,
week = 5;
case 5 matches, after execution of case 5
all the rest case will execute because execution of program follows top to down approach.
that why you are getting
Thursday
Friday
Saturday
Invalid day  as an output



Ques 2: WAP (Write a program) to get a number user (1-7) and print its equivalent day.
(with break)




Explanation -  

User enter 5 in the console,
week = 5;
case 5 matches, after execution of case 5 (output is Thursday)
JVM encounter break statement,
all the rest case will not execute because execution of program follows top to down approach.
so after execution of case 5, break statement execute and break statements immediately terminated switch.



Ques 3: WAP (Write a program) to print number from 1 to 10. (Using for loop)

Will see three (3) cases --
 flow of execution of for loop Initialisation -> Condition check -> Loop body -> Iteration/Increment




Case 1: using for loop, printing 1 to 10.


Explanation -  
- for loop is used for counting.
- i =1 (counting start from 1)
- i<=10 (condition - till contidion setisfied, it will counting) 
- i++ increment (every time i=current value of i +1)
- output is 1 to 10.


Case 2:  using for loop, printing 1 to 10 ( with continue).


Explanation -  
- for loop is used for counting.
- i =1 (counting start from 1)
- i<=10 (condition - till condition satisfied, it will counting) 
- i++ increment (every time i=current value of i +1)
- there is an if condition,
  • if condition true - control goes inside if block and continues execute, so when i=5  condition became true and continue statement executed then control goes for next iteration.
  • if condition false - control never goes inside if block so the program will work as above case.




Case 3: using for loop, printing 1 to 10 ( with break).


Explanation -  
- for loop is used for counting.
- i =1 (counting start from 1)
- i<=10 (condition - till condition satisfied, it will counting) 
- i++ increment (every time i=current value of i +1)
- there is an if condition,



  • if condition true - control goes inside if block and continues execute, so when i=5  condition became true and continue statement executed then control goes out of the loop.
  • if condition false - control never goes inside if block so the program will work as above case.



Link to download these two programs... Click Here.



Now, In next post, I will tell you how to get INPUT From USER.
Using Scanner Class.




Control Statements (Part 2)




In this post, will talk about all Control Statements in details and Will see the syntax of it.
In next couple of part will see some of the examples that will definitely help you to understand better,
as well as I will going to give you some basics programming question to solve it.



Syntax - Syntax is the set of rules that defines the combinations of symbols that are considered to be a correctly structured document. (or in short, it is a grammar of programming)


Expression  - Expression is a valid and logical combination of the operator ( athematic and relational ) and number.


Boolean Expression - Boolean Expression is an expression which always gives its result either "true" or "false".




# if Statement


+ If the Boolean Expression / Condition gives true, then whatever written inside if block will execute.
+ If the Boolean Expression / Condition gives false, then whatever written inside if block will never execute.
+ Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# if else Statement 

+ If the Boolean Expression / Condition gives true, then whatever written in the place of "do this work 1" will execute.
+ If the Boolean Expression / Condition gives false, then whatever written in the place of "do this work 2" will never execute.
Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# switch Statement


+ The switch statement is also called Integer Based Decision Maker ( till Java 1.4).
+  X can be constant (final) and in the range.
+ in the place of X you can use Number (byte, short, integer), character, wrapper classes (will See later) and string (Sequence of characters).  
+ default is also a case if no case matches then default case will be executed. 
+*  in switch "break" and "continue", these two keywords will be used frequently. (will discuss in next post).



# while loop
+ it is also called Entry Controlled loop because it will check the condition before execution.
+ If the Boolean Expression / Condition gives true, then whatever written inside the block will execute repeatedly.
+ If the Boolean Expression / Condition return false, then whatever written inside the block will never execute and control goes out of the loop.
Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# do while loop
+ it is also called Exit Controlled loop because condition checks at the time of exit.
+ it will definitely going to be executed at once then checks for the condition.
+ If the Boolean Expression / Condition gives true, then whatever written inside the block will execute again.
+ If the Boolean Expression / Condition return false, then control goes out of the loop.
Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# for loop


+ it is used for counting purpose
+  it has three steps

  • initialization - counting start from
  • condition - do it, till the condition satisfied
  • step - ascending to descending or descending to ascending
+ above steps are optional 
+ ; (semi-colon) is mandatory.







Control Statements (Part 1)




Control Statements are the statements which are used to make a group of statements and those groups of statements execute on some certain conditions. These are very useful while taking a decision on the basis of some boolean conditions.



In Java, control statements can be divided into the following three categories:

♣  Sequential Statement (Liner Statement)
♣  Selection Statements (Branching)
♣  Iteration Statements (Loop)


# Sequential Statement (Liner Statement) 

In a program, all statements execute one by one.
Staring from 1st statement to till the last statement.
This is called Sequential Statements.

For Example:-

  


# Selection Statements (Branching)

In Selection/Branching, you just make a group of some similar kinds of statement that together performs some specific kind of job.
We use if, if else to make the group of statements.
It is very useful for decision making on the basis of right or wrong  / true false.

For Example:- if, if else, switch



# Iteration Statements (Loop)

these are some group of statements that executed rapidly till a certain condition is not satisfied.
There are only three kinds of looping/iterative statements till now.
1-for loop
2-while loop (Entry Control loop)
3-do while loop (Exit Control loop)









Wednesday 12 September 2018

Operators In JAVA ( Part 2 )




In this post, we discuss some programs and try to understand some core concepts(Remarkable points). One more thing I would like to share with you...

I am not able to write all the programs using all operators .. I can write some important one (That follows some different rules).

But please you guys, practice as much as you can, this is the only way to learn to programming.


 Assignment Operator 

-- Assignment has LOWEST Priority.
-- it is denoted by " = " (equal to sign)
-- always value assign from RIGHT to LEFT


Now, There are three cases may arise.


case 1 - Destination and Source will be EQUAL.

If this is the scenario, then there is no problem.

Let's Take an EXAMPLE -

suppose you have a glass of water ... and you want to transfer it in the different glass with the same type, then you can easily do it without any problem.

case 2 - Destination is GREATER THAN Source.

If this is the scenario, then there is no problem.
It is also called Widening Conversion. 


Let's Take an EXAMPLE -

suppose you have a small glass of water ... and you want to transfer it in a large glass, then you can easily do it without any problem.




case 3 - Destination is SMALLER THAN Source.

If this is the scenario, then you are in big problem.
It is also called Narrow Conversion.
The main problem is that when you are doing this your data may be loose.
And Compiler will not allow Narrow Conversion Directly.

Let's Take an EXAMPLE -

suppose you have a large glass of water ... and you want to transfer it in a small glass, then if water is full in the large glass then some water will be lost during transfer, so you can't do it easily. It is a problem.


To Solve this problem we use TYPE CASTING.

Definition -  Forcing Compiler to allow Narrow Conversion.




Modulus Operator


-- This operator helps to give us the reminder.
-- % (per cent sign) is used for modulus operator. 

System.out.println( 5 % 2 );       // output = 1
System.out.println( -5 % 2 );      // output = 1
System.out.println( 5 % -2 );      // output = -1
System.out.println(-5 % -2);      // output = -1 

Note - In Modulus Operator, Reminder Sign is depends on DENOMINATOR. 



Shift Operator

  1. a>>>n
    • Shift bits of  "a" n times right filling with 0 from left.
  2. a>>n
    • Shift bits of "a" n times right filling with sign bit from left
  3. a<<n
    • Shift bits of "a" n times left filling with 0 from the right.




Now There are some points that you must know -


  1. When every you try to store negative number in your program, then those negative numbers store in 2's compliment.
  2. By default all the numerical value are of type int (means to say that all the calculation internally done in 32 bit memory)
  3. By default all the floating point are of type double (means to say that all the calculation internally done in 64 bit memory) 
  4. if both the operand are either int type or smaller then int (calculation done in 32 bit)
  5. if one or both operand bigger then int type then smaller type promoted to bigger type.
  6. any Integer arithmetic (except /0 or %0 ) always gives result within the range.
  7. Any Integer value  divided by zero gives -- ArithmeticException
  8. Floating point Numbers goes INFINITY.
    • System.out.println(5.0/0); // INFINITY
    • System.out.println(5/0.0); // INFINITY
    • System.out.println(5.0/0.0); // INFINITY
  9. Any Operation which is not possible -- for that java gives NaN (Not a Number) 
  10. we can not use/assign ++ or --  to any constant, it can be only for variable.




Question - Why float f = 10.5; gives error?
Answer - 
//float f = 10.5;  //ERROR
 // error because all the operation done in double (64 bit).So we have to typecast it.
// These are the 3 ways to do it.
float fl = 55.5f;
float f2 = 55.55F;
float  f3 = (float) 555.55;

Question - Full Form & Example of NaN?

Answer - NaN ==> Not a Number 
It comes when you are trying to do the operation at are not possible mathematically.
like finding the square root of a negative number.


        System.out.println(2.0 % 0);
        System.out.println(0.0 / 0);
        System.out.println(Math.sqrt(-1));


*Question - When we use "=" or "= ="?

Answer - " = " used for assignment, from right to left.
" ==  " used for comparison. [will descuss it later]

*Question - How can you say Compound Operators are implicit typecasting?



short s=5;
//short result =s+s;// ERROR Bcoz all the calculation done in 32 bit (int);
short result = (short)(s+s); // type casting required
System.out.println(result);

Or

instead off writing short result = (short)(s+s);
we can also write -- short result +=(s+s); // Called Short Hand Operator.