Please open the menu to show more

Sunday, August 27, 2017

Very important concept "The Binary Search" by Keshav

This code is implemented and provided by Keshav from Cetpa Infotech.

Binary Search : search an element [ stbs==>String to be search ] over
sorted array of n-elements by repeatedly dividing the search interval in half.
If 'stbs' is found in the array, return the position of element in the array
else return -1.
step 1: initially compare the 'stbs' begin with an interval covering 
the whole array.
if there is only one element in the array, then compare 'stbs' with
element. if it matches, then return 0 as index value. else return -1.
step 2: find the mid element. and compare it with 'stbs'. if matches, return 
mid position 
step 3: else if compareTo() method return -ve value then 'stbs' 
can be match in left half subarray before the mid element.
step 4: else 'stbs' can be match in right half subarray after the mid element.
  
NOTE: 1.Please create a Java project in Eclipse and save this class as 
BinarySearchForString.java
   2.Binary search only works on sorted array.
       Click here to know more about binary search


import java.util.*;
class BinarySearchForString
{
/* lets define a method search() which will be call recursively, this method will
take four arguments, 1st is an array of String, 2nd and 3rd argument will define
an interval and 4th argument will be 'String to be search' [stbs].
*/
static int search(String data[],int i,int j,String stbs)
{
// if (i==j) that means there is only one element in array.
if(i==j){
// lets compare the stbs with array element by calling compareTo()
// method, if match then return the position of element.
if(stbs.compareTo(data[i])==0){
return i;
}
// else return -1. ==> it means element is not present in array.
else{
return -1;
}
}
// if there is more then one element then find the mid position and then
// compare the stbs with mid position element.
else{
// so lets get the mid position.
int mid=(i+j)/2;
/* lets compare the stbs with mid position element.
if matches [means, if compareTo() method return 0 then ]
return mid position.*/
if(stbs.compareTo(data[mid])==0){
return mid;
}
/* if compareTo() method return negative (-ve) value, then 'stbs'
can be match in left half subarray before the mid element i.e.
[ from i to mid-1 ] */
else if(stbs.compareTo(data[mid])<0){
return search(data,i,mid-1,stbs);
}
// else 'stbs' can be match in right half subarray
// after the mid element i.e. [ from mid+1 to j ]
else{
return search(data,mid+1,j,stbs);
}
}
}


public static void main(String[] args)
{
// lets define an array of String
String str[]={"calcutta","delhi","hyderaba","jaipur","mumbai","pune"};
// lets get the number of element in the array.
int n=str.length;

Scanner sc=new Scanner(System.in);
System.out.println();
// now here i am going to show the element present in the array.
for(String s:str)
{
System.out.print(s+"  ");
}

System.out.println("\n");
System.out.print("enter String that to be search:");
String stbs=sc.next();
/* lets call the search() method to find the position of 'stbs'.
this method will return the postion of 'stbs' available inside
the array. else return -1. */
int index=search(str,0,n-1,stbs);
if(index!=-1){
System.out.println("the String is at index: "+index);
}
else{
System.out.println("the String is not availble: "+index);
}
}
}


now lets calculate the Time Complexity.
assume, there is n element in the array. and T(n) be the amount of time required to
find the element [stbs] using above algorithm.

but before this, let analysis the code.
1. if(i==j){
2. if(stbs.compareTo(data[i])==0){
3. return i;
4. }
5. else{
6. return -1;
7. }

from line number 1 to 7, there is one comparison which is done in O(1) time.

8. else{
9. int mid=(i+j)/2; ==> here is 0 comparison ==>mid position can
find in constant time that is O(1) time.

10. if(stbs.compareTo(data[mid])==0){
11.  return mid; ==> here is only one comparision ==>O(1) time.
12. }
13. else if(stbs.compareTo(data[mid])<0)
                        { ==> here is also one comparison
==> that can be done in O(1) time.
14. return search(data,i,mid-1,stbs);==> it takes T(n/2) time.
15. }
16. else{
17. return search(data,mid+1,j,stbs);==> it takes T(n/2) time.
18. }
19. }

overall time is 

T(n) = O(1) ==> if n=1 <== this is best case
(or)
O(1)+O(1)+O(1)+T(n/2) <== this is worst case

so in the worst case, time complexity is  
T(n) = T(n/2)+c, here c means constant time which is used to represent
         [O(1)+O(1)+O(1)]
         after solving this by using substitution approach , 
         we get Time Complexity as O(log n).

Friday, August 25, 2017

Frequently asked interview question on java programming language part Eight (8)

Question: Can you tell me the output of this code. Also justify your answer.

Note: Before using this code please create a Java project inside Eclipse and save this class inside TestOfArray.java file

class TestOfArray {

public static void main(String[] args) {

int[] array1 = {1,2}; // lets assume it is line 1
String[] array2 = {"1","2"}; // lets assume it is line 2
char[] array3 = {'1','2'}; // lets assume it is line 3

System.out.println(array1); // lets assume it is line 4
System.out.println(array2); // lets assume it is line 5
System.out.println(array3); // lets assume it is line 6
System.out.println(array3.toString()); // lets assume it is line 7

}
}

The output of this code will be something like ->

array of int: [I@15db9742
array of string: [Ljava.lang.String;@6d06d69c
array of char: 12


Explanation of this code ->

In Java the arrays are represented as an object, and every object has an address.
The name of array is treated like a reference-variable/object-name.

At line number 1 we are creating an array of int
At line number 2 we are creating an array of string
At line number 3 we are creating an array of string

Now,
Actually println is an overloaded methods of PrintStream class (means, many methods in a class with same name but with different parameters).

list of println() method inside PrintStream class is given below ->

1. public void println();
2. public void println(boolean);
3. public void println(char);
4. public void println(int);
5. public void println(long);
6. public void println(float);
6. public void println(double);
7. public void println(char[]);
8. public void println(java.lang.String);
9. public void println(java.lang.Object);

So, at line number 4 and 5 when we pass array name inside println() method the compiler will convert the address of array into string by using toString() method and then this method "public void println(java.lang.String)" will be called, and it will print the address of array in string format

But, when we pass array of char inside println method at line number 6, the method " public void println(char[])" will be called and it will print the content of array rather than address.

Now, at line number 7 we are explicitly calling toString() method on array of char in order to convert it into string, then in this case the method "public void println(java.lang.String)" will be called and address of array will be printed


Thursday, August 24, 2017

Beautifull Java code for "Tower of Hanoi" problem by Keshav

A code by Keshav, from Cetpa Infotech.


The Tower of Hanoi 

Tower of Hanoi is a mathematical game.
 it consist of 3 rods and different size of disks
and they will in ascending order from top to bottom
which can slide onto any rod.
There is some rules: 
==>only one disk can slide at a time from one rod to another.
==>disks should be in ascending order from top to bottom
==>only top of the disk can slide.

To know more about "Tower of Hanoi" please click on this link want to know more about tower of hanoi

Note: Please create a Java project in Eclipse and save this class as TowerOfHanoi.java file


import java.util.Scanner;
import java.util.InputMismatchException;
public class TowerOfHanoi {

/* 
 lets define a method toh() which will be call recursively. 
 this method will take three arguments. 1st argument will be
 number of disk (nod), 2nd argument will be source rod or 
 can say starting rod, 3rd argument will be middle rod and
 4th argument will be last rod or destination rod.
  
 so it will be like
 toh(number_of_disk,starting_rod,middle_rod,last_rod)
  
 number_of_disk==> nod
  
 note: slide of a disk will be source to destination.
  
 At the end of the program we will see how to calculate 
 time complexity of this program.
 */
static int moves = 0;
static int toh(int nod,String st,String mi,String la)
{
// if ther is only one disk
if(nod==1)
{
System.out.println("Step "+(moves+1)+"==> Move "+st+" to "+la);
moves++;
}
// otherwise
else
{
/* here st means A
    la means C
    mi means B 
*/
 
toh(nod-1,st,la,mi);
/* here st means A
     mi means B
     la means C 
*/
toh(1,st,mi,la);
/* here mi means B
     st means A
     la means C 
*/
toh(nod-1,mi,st,la);
}
return moves;
}
public static void main(String[] args) {
// nod means number_of_disks
int nod;
// lets get the number of disk
Scanner sc=new Scanner(System.in);
System.out.print("enter number of disk to be moved :");
try
{
nod=sc.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("you have given wrong input");
System.out.println("try again");
// lets initialize the nod with 0 and terminate the jvm
nod=0;
System.exit(0);
}
// it indicates starting rod
// let give a name to it as "A"
String start="A";
// it indicates middle rod
// let give a name to it as "B"
String middle="B";
// it indicates last rod
// let give a name to it as "C"
String last="C";
int moves = toh(nod,start,middle,last);
System.out.println("No of moves are "+moves);
}
}
// end of the programe

lets calculate time complexity of this code =>
as we have call 3 methods as follows 
toh(nod-1,st,la,mi);==>it will execute T(n-1) time
toh(1,st,mi,la); ==>it will execute only 1 time
toh(nod-1,mi,st,la);==>it will execute T(n-1) time
where n indicates number_of_disk
so overall time will be
T(n)=T(n-1)+1+T(n-1)=2T(n-1)+1
so the time complexity we will get as O(2^n).


Tuesday, August 22, 2017

One of the most important and frequently asked interview question on pointers

Question: Hey, can you explain the "pointer to a constant" and a "constant pointer".
               Also explain the combo of these two.

Note: Please copy and paste this code in any IDE related to C or C++.
(I have used Dev C++)

Detailed Explanation: 

----------------------------------------------------------------------------  

#include<stdio.h>
int main()
{
int a = 1;
int b = 1;
int c = 1;

// 'p' is a pointer to constant
// means the value which is pointed by pointer 'p' can't be modified
// but address stored inside pointer 'p' can be modified
// so, lets create a pointer to constant 'p' and store address of 'a' inside it
int const *p = &a;

// lets store the address of variable 'b' inside pointer 'p'
p = &b;

// lets modify the value pointed by pointer 'p'
// as we know we can't change the value pointed by pointer 'p'
// this statement will raise a compilation error
*p = 100;  // <= THIS IS A COMPILATION ERROR, so please comment this
         // line before use

// 'q' is a constant pointer 
// means the address which is stored inside pointer 'q' can't be modified
// so, lets create a constant pointer 'q' and store address of 'a' inside it
int *const q = &a;

// lets change the address stored inside pointer 'q'
// as we know we can't change the address which is stored inside pointer 'q'
// this statemnt will raise a compilation error
q = &b;  // <= THIS IS A COMPILATION ERROR, so please comment this
         // line before use

// this statement works fine since value pointed by pointer 'q' can be changed
*q = 100;

// 'r' is a constant pointer as well as pointer to constant 
// means the address which is stored inside pointer 'r' can't be changed
// also the value pointed by pointer 'r' can't be changed
// so, lets create a constant pointer to constant 'r' and store address of 'a'
        // inside it
const int *const r = &a;

// lets change the address stored inside pointer 'q'
// as we know we can't change the address which is stored inside pointer 'r'
// this statemnt will raise a compilation error
r = &a;   // <= THIS IS A COMPILATION ERROR, so please comment this
        // line before use

// lets modify the value pointed by pointer 'r'
// as we know we can't change the value pointed by pointer 'r'
// this statemnt will raise a compilation error
*r = 100;  // <= THIS IS A COMPILATION ERROR, so please comment this
        // line before use

      return 0;
}

----------------------------------------------------------------------------    

Monday, August 21, 2017

Awesome code by MAYANK to convert Number to Word, Non Recursive approach

This code is implemented and provided by Mayank Banga (WW), 
from GBU, Greater Noida.

About this code : By using this code we can translate a number into a word without using recursion

For example 1 will become one
and 120 will become  1 hundred twenty 

Note : Before using this code please create a java project in eclipse and save the 
code inside NumberToString .java file inside src folder  


import java.util.Scanner;

public class NumberToString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

/*
                 Three arrays for corresponding String to the number
 one to print values of ones place 
 second to print values of tens place
 third is due to different naming of eleven series 
*/
                String[] ones = { "zero", "one", "two", "three", "four", "five", "six", 
                                         "seven", "eight", "nine" };
String[] tens = { "zero", "ten", "twenty", "thirty", "fourty", "fifety",
                                       "sixty", "seventy", "eighty","ninety" };
String[] teens = { "ten", "eleven", "twelve", "thirteen", "fourteen", 
                                         "fifteen", "sixteen", "seventeen","eighteen", "nineteen" };
                System.out.println("please enter any number below 1,00,00,000");
String num = sc.next();
                int a = num.length();
             
                // applying validation such that number above range will show error
if (a > 9) {
System.err.println("OOPS ! Out of range");
System.err.println("Try again by restarting program");
} else {
//converting String into array of bytes 
byte[] b = num.getBytes();
byte[] d = new byte[a];
/*
since in array b we get corresponding ascii value of String 
like for 0 it is 48 and for 1 it is 49
so to get integer back from ascii value array d is used and 
in below for loop we retrieve back the int value from ascii codes
and here array is reversed as we will be decreasing size of array
from end point we will read one value and print corresponding
                        string for it as we do in normal life we read a number from left 
                        to right
*/
for (int i = 0; i < a; i++) {
d[a - i - 1] = (byte) (b[i] - 48);
}
//performing operations regarding to size
while (a != 0) {
if (a == 1) {
System.out.print(ones[d[a - 1]] + " ");
a = a - 1;
} else if (a == 2) {
if (d[a - 1] == 1) {
System.out.print(teens[d[a - 2]] + " ");
a = a - 2;
//here size was decreased by 2 because in 
//case of teens two digit are read as single
} else if (d[a - 1] == 0) {
a = a - 1;
if (d[a - 1] == 0) {
a = a - 1;
}
} else {
System.out.print(tens[d[a - 1]] + " ");
if (d[a - 2] == 0) {
a = a - 2;
} else {
a = a - 1;
}
}
} else if (a == 3) {
if (d[a - 1] == 0) {
a = a - 1;
} else {
System.out.print(ones[d[a - 1]] 
 + " hundred ");
a = a - 1;
}
} else {
if (d[a - 1] == 0) {
a = a - 1;
// to discard 0 that comes on first place 
//as their is no significance of 0 at starting
} else if (a % 2 == 0) {
System.out.print(ones[d[a - 1]]);
if (a == 4) {
System.out.print(" thousand ");
} else if (a == 6) {
System.out.print(" lakh ");
} else if (a == 8) {
System.out.print(" crore ");
}
a = a - 1;
} else if (a % 2 == 1) {
if (d[a - 1] == 1) {
System.out.print(teens[d[a - 2]]);
} else {
System.out.print(tens[d[a - 1]] 
  + " " + ones[d[a - 2]]);
}
if (a == 5) {
System.out.print(" thousand ");
} else if (a == 7) {
System.out.print(" lakh ");
} else if (a == 9) {
System.out.print(" crore ");
}
a = a - 2;
}
}
}
}
}
}

Sunday, August 20, 2017

Awesome code by VASU to convert Number into Words

This code is implemented and provided by Vasu, from MAIT, Delhi.

About this code : By using this code we can translate a number into a word.

For example 1 will become one
and 120 will become  1 hundred twenty 

Note : This code is based on recursion. 
I will post a non recursive approach to do the same thing very soon.
Till then enjoy this code.

Note : Before using this code please create a java project in eclipse and save the 
code inside Conversion.java file inside src folder  

import java.util.Scanner;

// Create a class consisting of main method and a calculate function
public class Conversion {
// Array of numbers for units place
static String[] unit = {"" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , 
                                       "eight" , "nine" , "ten" , "eleven" , "twelve" , "thirteen" , 
                                       "fourteen" , "fifteen" , "sixteen" , "seventeen" ,
                                       "eighteen","nineteen"} ;
// Array of numbers for tens place
static String[] tens = {"" , "ten" , "twenty" , "thirty" , "forty" , "fifty", "sixty" , 
                                        "seventy" ,"eighty" , "ninety" } ;

public static void main(String[] args) {
// Create object of Scanner Class
Scanner sc = new Scanner(System.in) ;
// Get Input From User
System.out.print("Enter the number : ");
int number = sc.nextInt() ;
// Show the Output to the user
System.out.println("Number in words : " + calculate(number)); 
}
public static String calculate(int n) {
// Create some cases to define range of the input number
if(n < 20) {
// Directly return the string corresponding to the number
return unit[n];  
}

else if(n < 100) {
return tens[n/10] + " " + unit[n%10];
}
                else if(n < 1000) {
// Apply recursion by converting the sub integer to actual integer
return unit[n/100] + " hundred " + calculate(n%100);  
}
                else if(n < 100000) {
// For numbers in thousands
return calculate(n/1000) + " thousand " + calculate(n%1000) ;  
}
                else if(n < 10000000) {
// For number in lakhs 
return calculate(n/100000) + " lakhs " + calculate(n%100000) ; 
}
                 else if(n < 1000000000) {
// For number in crore 
return calculate(n/10000000) + " crore " + calculate(n%10000000) ; 
}
               else {
return "Number Not In The Range ! Please Try Again" ;
}
}
}

Tuesday, August 15, 2017

Frequently asked interview question on java programming language part seven (7)

Question: What will be the output of this code, also explain your answer.

class Test
{
public static void main(String[] args)
{
for(byte b=1;b<=127;b++)
{
System.out.println(b);
}
}
}

Output of code =>
 This loop will print numbers from 1 to 127 then -128 to 0, then it will do it
                  the same for infinite times, so it is an infinite loop

Explanation of code =>
                       ## The range of byte datatype is -128 to 127
      ## So any value greater than 127 will round off to -128 and
                       any value less than -128 will round off to 127 due to
                       most significant bit (MSB)
      ## The MSB is zero for positive value and 1 for negative values
   

Sunday, August 13, 2017

very very simple but tricky question asked during Java interviews

Tell me the output of this code and explain

class Test 
{
public static void main(String[] args)
{
boolean b = false; // lets assume it is line number 1

if(b = true) // lets assume it is line number 2
{
System.out.println("if block executes");
}
else
{
System.out.println("else block executes");
}

}


output of code is =>
                    if block executes


explanation of code:
  ## at line number 1 we are assignning false in a boolean variable b
  ## at line number 2 we are again assigning true inside variable b using 
        assignment operator (that is =)
   ## so new value of variable b is true, so result inside if statement 
         becomes true
  ## and we know in case of true condition the block of if will be 
         executed 


              
     

Saturday, August 12, 2017

Who says Java does not supports pointers part-seven, lets implement a "Binary Search Tree" in Java, a code by Pankaj

This awesome code of "Binary Search Tree"
(BST) is implemented and provided by Pankaj
,from Nit-Arunachal Pradesh

Note: A Binary Search Tree is a non linear data
structure. It provides a very fast store and
retrieve operation for further information on
BST please click on given link

Note: Please create a "Java Project" inside
Eclipse before using this code

## save this class inside BSTNode.java file ## import java.util.Scanner; // Class BSTNode class BSTNode { BSTNode left, right; String data; // Constructor to create node public BSTNode() { left = null; right = null; data = null; } // Constructor to provide data to node public BSTNode(String n) { left = null; right = null; data = n; } // Method to set left node public void setLeft(BSTNode n) { left = n; } // Method to set right node public void setRight(BSTNode n) { right = n; } // Method to get left node public BSTNode getLeft() { return left; } // Method to get right node public BSTNode getRight() { return right; } // Method to provide data to node public void setData(String d) { data = d; } // Method to get data to node public String getData() { return data; } }

## save this class inside BST.java file ## // Class BST class BST { private BSTNode root; public BST() { root = null; } // empty check public boolean isEmpty() { return root == null; } // insert data public void insert(String data) { root = insert(root, data); } private BSTNode insert(BSTNode node, String data) { if (node == null) node = new BSTNode(data); else { int temp=data.compareTo(node.getData()); if (temp<0) node.left = insert(node.left, data); else node.right = insert(node.right, data); } return node; } //delete data public void delete(String k) { if (isEmpty()) System.out.println("Tree Empty"); else if (search(k) == false) System.out.println("Sorry "+ k +" is not present"); else { root = delete(root, k); System.out.println(k+ " deleted from the tree"); } } private BSTNode delete(BSTNode root, String k) { BSTNode p, p2, n; if ((root.getData()).equalsIgnoreCase(k)) { BSTNode lt, rt; lt = root.getLeft(); rt = root.getRight(); if (lt == null && rt == null) return null; else if (lt == null) { p = rt; return p; } else if (rt == null) { p = lt; return p; } else { p2 = rt; p = rt; while (p.getLeft() != null) p = p.getLeft(); p.setLeft(lt); return p2; } } //Edit here if (k.compareTo(root.getData())<0) { n = delete(root.getLeft(), k); root.setLeft(n); } else { n = delete(root.getRight(), k); root.setRight(n); } return root; } // number of nodes public int countNodes() { return countNodes(root); } private int countNodes(BSTNode r) { if (r == null) return 0; else { int l = 1; l += countNodes(r.getLeft()); l += countNodes(r.getRight()); return l; } } // search an element public boolean search(String val) { return search(root, val); } private boolean search(BSTNode r, String val) { boolean found = false; while ((r != null) && !found) { String rval = r.getData(); //edit here if (val.compareTo(rval)<0) r = r.getLeft(); else if (val.compareTo(rval)>0) r = r.getRight(); else { found = true; break; } found = search(r, val); } return found; } //inorder traversal public void inorder() { inorder(root); } private void inorder(BSTNode r) { if (r != null) { inorder(r.getLeft()); System.out.print(r.getData() +" "); inorder(r.getRight()); } } // preorder traversal public void preorder() { preorder(root); } private void preorder(BSTNode r) { if (r != null) { System.out.print(r.getData() +" "); preorder(r.getLeft()); preorder(r.getRight()); } } // postorder traversal public void postorder() { postorder(root); } private void postorder(BSTNode r) { if (r != null) { postorder(r.getLeft()); postorder(r.getRight()); System.out.print(r.getData() +" "); } } }
## save this class inside BinarySearchTree.java
file ## // main Class BinarySearchTree public class BinarySearchTree { public static void main(String[] args) { Scanner scan = new Scanner(System.in); BST bst = new BST(); System.out.println("Binary Search Tree Test\n"); char ch; do { System.out.println("\nBinary Search Tree Operations\n"); System.out.println("1. insert "); System.out.println("2. delete"); System.out.println("3. search"); System.out.println("4. count nodes"); System.out.println("5. check empty"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter String to insert"); bst.insert( scan.next() ); break; case 2 : System.out.println("Enter String element to delete"); bst.delete( scan.next() ); break; case 3 : System.out.println("Enter String element to search"); System.out.println("Search result : "+ bst.search( scan.next() )); break; case 4 : System.out.println("Nodes = "+ bst.countNodes()); break; case 5 : System.out.println("Empty status = "+ bst.isEmpty()); break; default : System.out.println("Wrong Entry \n "); break; } System.out.print("\nPost order : "); bst.postorder(); System.out.print("\nPre order : "); bst.preorder(); System.out.print("\nIn order : "); bst.inorder(); System.out.println("\nDo you want to continue (Type y or n) \n"); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } }



Friday, August 11, 2017

Simple but very important code asked in Java based companies

How to get Current Working Directory (CWD) in Java. 

In Java Current Working Directory can be retrieved using the following code

Note: Please save this class inside GetCurrentDirectory.java file inside Java Project of Eclipse

public class GetCurrentDirectory {
public static void main(String[] args) {

String dir = System.getProperty("user.dir");
System.out.println("Current directory is "+dir);

}

}

Explanation of code :
note-1: getProperty() is a static method of System class
note-2: user.dir is a pre defined property (kind of a key)
note-3: on the basis of user.dir key, the getProperty() method retuns the complete
            path of current Working directory  

Frequently asked interview question on java programming language part 6

---------------------------------------------------------------------------------------------------
Question: Why final modifier cant be applied on constructor in Java?

Answer: If we apply final modifier on a method of superclass the subclass cant override that method.
As we know the constructors never inherits, so they cant be overriden by the subclass.
So in this scenario the explicit use of final modifier becomes unnecessary on constructor.
---------------------------------------------------------------------------------------------------
Question: Can we apply native modifer on constructors in Java? Justify your answer.

Answer: We cant apply native modifer on constructors.
native modifer is applicable for the methods only. native methods are declared in Java and defined in C/C++ generally.
The native methods are evaluated by JVM using JNI (Java Native Interface), the JNI does not understands the OOPS concepts, and we already know the constructors are associated with objects only.
---------------------------------------------------------------------------------------------------

Solution for the assignment "find occurrence of a word in string"

This code is implemented and provided by "ITI" From "Banasthali University"

import java.util.*;
public class StringIndex
{
public static void main(String[] args)
{
System.out.println("PLEASE ENTER A PARAGRAPGH : ");
Scanner sc=new Scanner(System.in);
System.out.println("PLEASE ENTER A WORD : ");
String p=sc.nextLine(); String w=sc.nextLine();
System.out.println("FIRST INDEX OF "+w+" = "+fi);
//finding first index of w in p int fi=p.indexOf(w);
System.out.println("LAST INDEX OF "+w+" = "+li);
//finding last index of w in p int li=p.lastIndexOf(w); int c=0;
//loop for upgrading the index in order to check
System.out.print("ALL THE INDEXES OF "+w+" = ");
//finding all the indexes of w in p
//it's further occurrence
while(fi>=0) {
//finding index of next occurrence until it returns -1
fi=p.indexOf(w,fi+1); System.out.print(fi+","); //calculating frequency
}
c++; } System.out.println("\n"+w+" OCCURRED "+c+" TIMES ");
}

Who says java does not supports pointers part-six, lets implement a Tree in Java, a code by Pankaj

This extraordinary code of Binary Tree is implemented and provided by Pankaj, from Nit-Arunachal Pradesh
Note: Binary tree is a non linear data structure. It is very important and useful in computer science. In a binary tree huge amount of data can be stored and retrieved in a very less period of time. So, its time complexity is very good. For further information on binary tree please click on given link more about binary tree
note : before using this code please create a "java project" in "eclipse" and store all the classes in separate program files inside "src" folder of "java project".
## save this class inside BTNode.java file ## import java.util.Scanner; public class BTNode {
BTNode left, right; int data; // Constructor to craete a node public BTNode() { left = null; right = null; data = 0; } // Constructor to put value of data public BTNode(int n) { left = null; right = null; data = n; } // method to join left node public void setLeft(BTNode n) { left = n; } // method to join right node public void setRight(BTNode n) { right = n; } // method to get left node public BTNode getLeft() { return left; } // method to get right node public BTNode getRight() { return right; } // method for set data to node public void setData(int d) { data = d; } // method to get data from node public int getData() { return data; } }
## save this class inside BT.java file ## // Class BT public class BT { private BTNode root; public BT() { root = null; } // empty check public boolean isEmpty() { return root == null; } public void insert(int data) { root = insert(root, data); } private BTNode insert(BTNode node, int data) { if (node == null) node = new BTNode(data); else { if (node.getRight() == null) node.right = insert(node.right, data); else node.left = insert(node.left, data); } return node; } // count number of nodes public int countNodes() { return countNodes(root); } // count nodes implementation private int countNodes(BTNode r) { if (r == null) return 0; else { int l = 1; l += countNodes(r.getLeft()); l += countNodes(r.getRight()); return l; } } // search for an element public boolean search(int val) { return search(root, val); } // search implementation private boolean search(BTNode r, int val) { if (r.getData() == val) return true; if (r.getLeft() != null) if (search(r.getLeft(), val)) return true; if (r.getRight() != null) if (search(r.getRight(), val)) return true; return false; } // inorder traversal public void inorder() { inorder(root); } private void inorder(BTNode r) { if (r != null) { inorder(r.getLeft()); System.out.print(r.getData() + " "); inorder(r.getRight()); } } // preorder traversal public void preorder() { preorder(root); } private void preorder(BTNode r) { if (r != null) { System.out.print(r.getData() + " "); preorder(r.getLeft()); preorder(r.getRight()); } } // postorder traversal public void postorder() { postorder(root); } private void postorder(BTNode r) { if (r != null) { postorder(r.getLeft()); postorder(r.getRight()); System.out.print(r.getData() + " "); } } } ## save this class inside BinaryTree.java file ## public class BinaryTree { public static void main(String[] args) { Scanner scan = new Scanner(System.in); BT bt = new BT(); System.out.println("Binary Tree Test\n"); char ch; do { System.out.println("\nBinary Tree Operations\n"); System.out.println("press 1 to insert "); System.out.println("press 2 to search"); System.out.println("press 3 to count nodes"); System.out.println("press 4 to check empty"); int choice = scan.nextInt(); switch (choice) { case 1: System.out.println("Enter integer element to insert"); bt.insert(scan.nextInt()); break; case 2: System.out.println("Enter integer element to search"); int element = scan.nextInt(); System.out.println("Search result : " + bt.search(element)); break; case 3: System.out.println("Nodes = " + bt.countNodes()); break; case 4: System.out.println("Empty status = " + bt.isEmpty()); break; default: System.out.println("Wrong Entry \n "); break; } // display the tree System.out.print("\nPost order : "); bt.postorder(); System.out.print("\nPre order : "); bt.preorder(); System.out.print("\nIn order : "); bt.inorder(); System.out.println("\n\nDo you want to continue (Type y or n) \n"); ch = scan.next().charAt(0); } while (ch == 'Y' || ch == 'y'); } }

Wednesday, August 9, 2017

Feel the power of Unicode in Java Programming language

This awesome code is implemented and provided by Mayank Banga (WW), from GBU, Greater Noida


Some facts: 

1. A Java program can be implemented in Unicode notation. The compiler of Java can read the Java code even if it is written in Unicode notation.
2. Unicode is a unique numeric representation of natural languages (like English, Hindi, Urdu) characters. So by using Unicode we can denote the characters in programming languages. Unicode can supports many natural languages. Up to 65536 characters can be supported.
In Java programming language a Unicode can be specified using \u0000 to \uffff representation.

For example =>

System.out.println("\u0041"); will display A, since Unicode value of A is 65
System.out.println("\u0061"); will display a, since Unicode value of A is 97
System.out.println("\u0040"); will display @, since Unicode value of A is 64


NOTE: Create a Java project in Eclipse IDE, then create a class inside this Java project. The class name must be Unicode.java

\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0063\u006C\u0061\u0073\u0073\u0020\u0055\u006E\u0069\u0063\u006F\u0064\u0065\u0020\u007B

\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0020\u0061\u0072\u0067\u0073\u0029\u0020\u007B

\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u0068\u0065\u006C\u006C\u006F\u002C\u0020\u0074\u0068\u0069\u0073\u0020\u0069\u0073\u0020\u0063\u0068\u0061\u0072\u0061\u0063\u0074\u0065\u0072\u0020\u0072\u0065\u0070\u0072\u0065\u0073\u0065\u006E\u0074\u0061\u0074\u0069\u006F\u006E\u0020\u0069\u006E\u0020U\u006E\u0069\u0063\u006F\u0064\u0065\u0022\u0029;

\u007D

\u007D


output of this code is  => hello, this is character representation in Unicode



Really guys, the "pointers are awesome "

This code will show us how pointer are so much useful for us.
We can do anything using pointer.

Note: Just copy and paste this code in either Turbo C++, or Dev C, environment, then compile and execute the code.

This code will show us how pointer are so much useful for us.
We can do anything using pointer.

Note: Just copy and paste this code in either Turbo C++, or Dev C, environment, then compile and execute the code.

#include<stdio.h>
#include<string.h>
int main()
{
        // create a string
char str[] = "C for Computer";
     
        // get length of string using strlen() function
        int length = strlen(str);
int i = 0;
int j = 0;

    for(i=0;i<length;i++)
{
    // here "str" means the base address of string
   //  so value of 'i' will move the pointer of string to next index
    printf("%s",str+i);
printf("\n");
}
for(j=i;j>=0;j--)
{
    // here "str" means the base address of string
   //  so value of 'j' will move the pointer of string to previous index
printf("%s",str+j);
printf("\n");
}
return 0;
}

Monday, August 7, 2017

Frequently asked question asked by good companies on java programming language part-5

Question: How can we access the variables of super-classes without using "super" keyword.

Answer: We can access the variables of super-classes using "this" keyword instead of "super" keyword.

Lets understand how following code words =>

As we know the "this" keyword denotes current object in java programming language. And the type of any object can be type caste to any of its super-classes using the following syntax 

==> ((name-of-superclass)this)

after this syntax we can access the variable of super-classess like given syntax

==> ((name-of-superclass)this).variable-name


note: before using this code please create a "Java Project" in "Eclipse"


# save this class inside GreatGrandFather .java file #
public class GreatGrandFather {
String name = "Prithvi Raj Kapoor";
}

# save this class inside GrandFather .java file #
public class GrandFather extends GreatGrandFather {
String name = "Raj Kapoor";
}



# save this class inside Father .java file #
public class Father extends GrandFather {
String name = "Rishi Kapoor";
}

# save this class inside Son.java file #
public class Son extends Father {
String name = "Ranbeer Kapoor";
void showNames() {
System.out.print("The name of GreatGrandFather is ");
// access the variable of GreatGrandFather
// here i am converting the type of Son's object to the GreatGrandFather
System.out.println(((GreatGrandFather)this).name);
System.out.print("The name of GrandFather is ");
// access the variable of GrandFather
// here i am converting the type of Son's object to the GrandFather
System.out.println(((GrandFather)this).name);
System.out.print("The name of Father is ");
// access the variable of Father
// here i am converting the type of Son's object to the Father
System.out.println(((Father)this).name);
// note: we can also access the variable of class Father using "super"
       //  keyword, example "super.name"
System.out.print("The name of Son is ");
// access the variable of Son
// note: we can also access the variable of class Son using "this" keyword,
        // example "this.name"
System.out.println(((Son)this).name);
}
}

# save this class inside UseOfThisKeyword .java file #
public class UseOfThisKeyword {

public static void main(String[] args) {
// create object of class Son
        Son son = new Son();
// call the method using object-name "son" of class Son
        son.showNames();
}
}