Showing posts with label Core JAVA. Show all posts
Showing posts with label Core JAVA. Show all posts

Tuesday, December 27, 2016

Count no of String occurences in single pass

package com.prac;

import java.util.*;

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

String[] str = {"A","B","C","A","A","B","B","B","B","B","C","A","D","E","E","F","D","D"};

Map<String, Integer> hm = new HashMap<String, Integer>();

int cnt=1;

for(String ans : str)
{
if(hm.containsKey(ans))  //check if the key is already present
{
 cnt=hm.get(ans); // if present then fetch its count and increment it
 cnt++;
}
else
{
   cnt=1; //else set count to 1
}

     hm.put(ans, cnt);  // add the data in map
}


System.out.println("hm="+hm);
}
}


Output:
hm={D=3, E=2, F=1, A=4, B=6, C=2}

Thursday, December 15, 2016

Find first non-repeating character in String

Following code finds the first non-repeating character in just one pass :)


public class NonRepeating{

public static char firstNonRepeatingChar(String word)
{
Set<Character> repeating = new HashSet<Character>();
List<Character> nonRepeating = new ArrayList<Character>();

for (int i = 0; i < word.length(); i++)
{
char letter = word.charAt(i);
if (repeating.contains(letter))
{
continue;
}

if (nonRepeating.contains(letter))
{
nonRepeating.remove((Character) letter);
        repeating.add(letter);
}
else
{
nonRepeating.add(letter);
}
}

if(nonRepeating.size()!=0)
 return nonRepeating.get(0);
else
  return '\0';
}


public static void main(String[] args)
{
char ans = firstNonRepeatingChar("hrishikesh");

System.out.println("ans="+ans);
}
}

Wednesday, December 14, 2016

Fibonacci Series

Fibonacci Series = 0 1 1 2 3 5 8 13 21 34.

Basically we have to add the previous and current number to get the next number.


Java Code->
public class Fibonacci
{
    static int[] fibonacci(int n)
    {
     //Declare an array to store Fibonacci numbers
     int f[] = new int[n+1];
     int i;
   
     //0th and 1st number of the series are 0 and 1
     f[0] = 0;
     f[1] = 1;
   
     for (i = 2; i <= n; i++)
     {
    //Add the previous 2 numbers in the series and store it
        f[i] = f[i-1] + f[i-2];
     }
   
      return f; //Return the array back to main method.
    }

 
   public static void main(String[] args)
   {
     int n = 9;
     int[] ans = fibonacci(n);
 
     for (int i = 0; i <= n; i++)
     {
        System.out.print(ans[i]+" "); //Print the array.
     }
   }

}

Thursday, November 17, 2016

Volatile in JAVA

Volatile keyword can be applied only to variables. It cannot be applied to class or method.

Volatile is used to indicate that a variable's value will be modified by different threads.

The value of volatile variable never get cached thread-locally; all reads and writes go straight to main memory.

A volatile variable can be used as an alternative way of to achieve synchronization in Java in some cases, like visibility. 

With volatile variable, it's guaranteed that all reader threads will see updated value of the volatile variable once write operation is completed, without volatile keyword different reader threads may see different values.

Example:
Imagine a situation in which two or more threads have access to a shared object which contains a counter variable declared like this:

public class SharedVariable {
    public int counter = 0;
}

Imagine too, that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time.

If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable is written from the CPU cache back to main memory. This means, that the counter variable value in the CPU cache may not be the same as in main memory.

The problem with threads not seeing the latest value of a variable because it has not yet been written back to main memory by another thread, is called visibility problem (updates of one thread are not visible to other threads).

By declaring the counter variable volatile all writes to the counter variable will be written back to main memory immediately. Also, all reads of the counter variable will be read directly from main memory. Here is how the volatile declaration of the counter variable looks:

public class SharedVariable {
    public volatile int counter = 0;
}

Declaring a variable volatile thus guarantees the visibility for other threads of writes to that variable.

Tuesday, October 27, 2015

POI API for writing data from excel file to a text file.

Many times you will come across situations, wherein you will need to read data from excel files and do some processing.

POI API comes to the rescue here :)

Download the latest POI jar file and add it to your project library.

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ConvertFile 
{
   public static void main(String[] args) 
   {
      System.out.println("Start of Program");
      try
      {
FileInputStream file = new FileInputStream(new File("D:\\Test_Data_Automation.xls"));

//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file);

//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(2);

//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();

String fileName = "";
PrintWriter writer = null;

        while(rowIterator.hasNext())
         {
            Row row = rowIterator.next();
       
            //For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
             
            try{
                 writer = new PrintWriter("D:\\Output_Data.txt", "UTF-8");
            }catch(Exception ex){ex.printStackTrace();}
                          
            while(cellIterator.hasNext()) 
            {
               Cell cell = cellIterator.next();
                       
            if(cell.getRowIndex() > 3)      //Start reading from the 3rd row.
            {
               switch(cell.getCellType()) 
               {
                  case Cell.CELL_TYPE_BOOLEAN:
                  System.out.print(cell.getBooleanCellValue() + "\t\t");
                  writer.println(String.valueOf(cell.getBooleanCellValue()));
                  break;
                  
                   case Cell.CELL_TYPE_NUMERIC:
                  System.out.print(cell.getNumericCellValue() + "\t\t");
                  writer.println(String.valueOf(cell.getNumericCellValue()));
                  break;
                   
                   case Cell.CELL_TYPE_STRING:
                  System.out.print(cell.getStringCellValue() + "\t\t");
                  writer.println(String.valueOf(cell.getStringCellValue()));
                  break;
                   
                   case Cell.CELL_TYPE_FORMULA:
                  cellValue=String.valueOf(cell.getStringCellValue());
                  break;
                   
                   case Cell.CELL_TYPE_ERROR:
                  cellValue=String.valueOf(cell.getStringCellValue());
                  break;
                  }
            }
             }
             
             try{
             System.out.println("Close the file");
                 writer.close();
             }catch(Exception ex){ex.printStackTrace();}
         }

         System.out.println("End of Program");

     }
     catch(Exception ex) {ex.printStackTrace();}
   }
}   //End of Main


Some Important syntax->
1) To read any row apart from the current row, use the following.
     Row nextRow = sheet.getRow(row.getRowNum() + 1);
     Row prevRow = sheet.getRow(row.getRowNum() - 1);
     Row next2Row = sheet.getRow(row.getRowNum() + 2);
     Row prev2Row = sheet.getRow(row.getRowNum() - 2);
     etc.

2) To read any column in any particular row, use the following.
     row.getCell(1);
     row.getCell(7);
     row.getCell(11);
     etc.

Thursday, August 27, 2015

Garbage Collection in JAVA

1) When the garbage collector runs, its purpose is to find and delete objects that cannot be reached.
 
2) The garbage collector is under the control of the JVM. The JVM decides when to run the garbage 
     collector.
 
3) An object is eligible for garbage collection when no live thread can access it.
 
4) Garbage collection cannot ensure that there is enough memory, only that the memory that is
    available will be managed as efficiently as possible.
 
5) The simplest way to ask (request) for garbage collection in System.gc();
 
6) About the only thing you can guarantee is that if you are running very low on memory, the garbage
    collector will run before it throws an OutOfMemoryException.
 
7) JAVA provides you a mechanism to run some code just before your object is deleted by the
    garbage collector. This code is located in a method named finalize() that all classes inherit from
    class Object.
    - For any given object, finalize() will be called only once (at most) by the garbage collector.
    - Calling finalize() can actually result in saving an object from deletion.
 
    For example, in the finalize() method you could write code that passes a reference to the object in
    question back to another object, effectively uneligibilizing the object for garbage colleciton.
 

Monday, August 17, 2015

Memory management in JAVA

Sometimes when you run some java applications you may run out of memory and get exceptions related to memory.

Following code helps you to manage the memory better. Also you may trigger an email to the users or dvelopment team whenever you anticipate shortage of space, so that the development team can take necessary action.

public class MemoryUsage
{

  public static void main(final String[] args)
  {
   final int mb = 1024 * 1024;

   final Runtime runIns = Runtime.getRuntime();
   
   System.out.println("Total Memory = " + runIns.totalMemory() / mb + " mb");
  
   System.out.println("Free Memory = " + runIns.freeMemory() / mb + " mb");
   
   System.out.println("Used Memory = " + (runIns.totalMemory() - runIns.freeMemory()) / mb + " mb");
  
   System.out.println("Max Memory= " + runIns.maxMemory() / mb + " mb");
  }

}

Sunday, August 16, 2015

Move zeroes (0's) to the end of array list

In a arraylist if you have zeroes (0's) at any randon location and want to move all the zeroes to the end of the list keeping the sequence of the list as-is, here is the solution -

Input - 1 9 8 4 0 0 2 7 0 6 0 9

Output - 1 9 8 4 2 7 6 9 0 0 0 0

void puchEnd()
{
   int count = 0;

   //Traverse the list and if element is non-zero, write to the list.
   for(int i=0 ; i<arr.length; i++)
  {
      if(arr[i].equals("0"))
      {
          //do nothing
      }
      else
      {
          arr[count++] = arr[i]; 
      }
  }
  
   //After writing all non-zero elements, now copy zero till the end of list.
   while(count < n)
   {
      arr[count++] = arr[i];
   }
}

JDBC Steps

1) Load the driver class.
    Class.forName("oracle.jdbc.driver.OracleDriver");


2) Create the connection Object.
    Connection con = DriverManager.getConnection  
    ("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");


3) Create the statement Object.
     Statement stmt = con.createStatement();


4) Execute query.
     ResultSet rs = stmt.executeQuery("select * from emp");
     
     while (rs.next)
     {
        System.out.println(rs.getString());
     }


5) Close the conneciton Object.
     con.close();

Wednesday, August 5, 2015

Parse Nested JSON in JAVA

Sample JSON file ->

--------------------------------------------------------------------------------------------------------------------------
{

"products": [

{

"summary": "Flagship tripod with remote control and pan handle – designed for professionals!",

"averageRating": 4.555555555555555,

"stock": {

"stockLevelStatus": {

"code": "inStock",

"codeLowerCase": "instock"

}

},

"description": "Remote pan-handle with under-hand grip controls zoom in/out, record start/stop, photo mode on/off (camcorder only) Dimensions: maximum height approx. 1,505 mm Dimensions: minimum height approx. 735 mm Weight: approx. 3.2 kg Maximum Load: 5.0 kg Panning Angle: 360 degrees Tilting Angle: 90 degrees down / 70 degrees up Quick-release Mounting Shoe Ball level for quick and easy level adjustment Oil Friction Head ...",

"name": "Flagship tripod with remote control and pan handle",

"availableForPickup": true,

"code": "23355",

"url": "/Open-Catalogue/Cameras/Camera-Accessories-%26-Supplies/Tripods/Flagship-tripod-with-remote-control-and-pan-handle/p/23355",

"priceRange": {},

"price": {

"currencyIso": "USD",

"priceType": "BUY",

"value": 580.38,

"formattedValue": "$580.38"

},

"manufacturer": "Sony",

"volumePricesFlag": false,

"images": [

{

"imageType": "PRIMARY",

"format": "thumbnail",

"url": "/medias/?context=bWFzdGVyfGltYWdlc3wyNDA3fGltYWdlL2pwZWd8aW1hZ2VzL2hkYi9oNzIvODc5NjIzNzEzNTkwMi5qcGd8YTE0YmM0NzE4NzAyZjVlNDcwYWY5NzdjZTA1MzlmMWVkMzYwZWU1ZDA0OGY3MWY1MTdkYzNjMGJhMTk4NTBhMA"

},

{

"imageType": "PRIMARY",

"format": "product",

"url": "/medias/?context=bWFzdGVyfGltYWdlc3wxMTg0NnxpbWFnZS9qcGVnfGltYWdlcy9oNDMvaDY1Lzg3OTYyMTA3OTA0MzAuanBnfDhhNzM5YThjMTYzZmU0OWIyYWQ0Mjg0OWZhYWQ1MmMwM2U2N2RmYzE4NDFmN2RjOWE1YTYzNmQyNmQ3NzNhZDk"

}

]

}

]

}

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

JAVA Code->

Here JSON data can be fetched by storing it in a file or directly through the url (exposed via web-service).

--------------------------------------------------------------------------------------------------------------------------
package com.parseProduct;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Scanner;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class ParseFinal {

public static void main(String[] args) throws IOException {

JSONParser parser = new JSONParser();

String s = "
http://localhost:9001/rest/v1/electronics/products";

URL url = new URL(s);

Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();

try
{
Object obj = parser.parse(str);

JSONObject jsonObject = (JSONObject)(obj);
JSONArray slideContent = (JSONArray) jsonObject.get("products");

Iterator i = slideContent.iterator();

while (i.hasNext())
{
JSONObject slide = (JSONObject) i.next();
String summary = (String)slide.get("summary");
double averageRating = (double)slide.get("averageRating");

JSONObject stockObj1 = (JSONObject) slide.get("stock");
JSONObject stockoo = (JSONObject) stockObj1.get("stockLevelStatus");
String code = (String)stockoo.get("code");
String codeLowerCase = (String)stockoo.get("codeLowerCase");

String description = (String)slide.get("description");
String name = (String)slide.get("name");
boolean availableForPickup = (boolean)slide.get("availableForPickup");
String productCode = (String)slide.get("code");
String productUrl = (String)slide.get("url");


JSONObject stockObj = (JSONObject) slide.get("price");
String currencyIso = (String)stockObj.get("currencyIso");
String priceType = (String)stockObj.get("priceType");
double value = (double)stockObj.get("value");
String formattedValue = (String)stockObj.get("formattedValue");

String manufacturer = (String)slide.get("manufacturer");
boolean volumePricesFlag = (boolean)slide.get("volumePricesFlag");

JSONArray jsonImage = (JSONArray) slide.get("images");

System.out.println("\n"+"summary:"+summary);
System.out.println("\n"+"averageRating:"+averageRating);
System.out.println("\n"+"stock:"+"stocklevel status:");
System.out.println("\n"+"code:"+code);
System.out.println("\n"+"codeLowerCase: "+codeLowerCase );
System.out.println("\n"+"description:"+description);
System.out.println("\n"+"name:"+name);
System.out.println("\n"+"availableForPickup :"+availableForPickup );
System.out.println("\n"+"productCode :"+productCode);
System.out.println("\n"+"productUrl :"+productUrl);
System.out.println("\n"+"productUrl :"+productUrl);


System.out.println("\n"+"currencyIso:"+currencyIso);
System.out.println("\n"+"priceType:"+priceType);
System.out.println("\n"+"value:"+value);
System.out.println("\n"+"formattedValue:"+formattedValue);
System.out.println("\n"+"manufacturer:"+manufacturer);
System.out.println("\n"+"volumePricesFlag:"+volumePricesFlag);

System.out.println("*************************************");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

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

Thursday, July 23, 2015

Favour Composition over Inheritance

There are 2 ways in which a class can inherit properties from another class in JAVA.

Inheritance (is-a) and Composition (has-a).


1) is-a takes place when we use extends keyword in JAVA.

public class Dog extends Animal

Here Dog inherits the properties of Animal. This can only be done at comile time and once the assignment is done cannot be changed at runtime.



2) has-a takes place when we use reference of one class in another class.

public class Dog
{
   Animal animalObj;
  
   Dog (Animal animalObj)
   {
       this.animalObj = animalObj; 
   }
 }

Here Dog gets the properties of Animal and the assignment can be changed at runtime as well.

This feature is famously used as Dependency Injection in Springs framework.



Hence Composotion is a better option than Inheritance to inherit properties from another class.
 

JAVA does not support multiple Inheritance

Why JAVA does not support multiple Inheritance ?

JAVA removes rarely used and confusing features from C++.

Multiple Inheritance gives rise to the common diamond problem.

 
 
In the above figure we have two classes B and C inheriting from A.

Assume that B and C are overriding an inherited method and they provide their own implementation.

Now D inherits from both B and C through multiple inheritance and thus D should inherit that overridden method.

Which overridden method will be used? Will it be from B or C?

This gives rise to ambiguity.

Hence it was felt better to remove this feature from JAVA.

If required this feature can be substituted by alternative design by using interfaces in JAVA.
 

public static void main (String[] args)

public static void main (String[] args)

What does this syntax mean in your JAVA program ?

public - This is the access modifier. Being declared as public means it can be called from anywhere. This makes sense because the JVM is going to call this method.

static - If we don't declare it as static then JVM will have to make an instance (object) to call this method. Static makes it a class level method which does not require any object to be called.

void - We dont have to return anything to the JVM, hence void declaration makes sense.

main - Predefined method name which the JVM tries to call automatically. Java is case-sensitive, Main is different from main.

String[] args - Argument list that can be passed from the command prompt to the JAVA program.

Wednesday, July 22, 2015

ClassNotFoundException VS NoClassDefFoundError

ClassNotFoundException : This exception occurs when class loader is not able to find the required class in class path.

NoClassDefFoundError : This exception occurs when at compile time the required classes are present, but at runtime the classes are changed or removed.

ResultSet and ResultSetMetaData

When we dont know what type of value the query will return, we have to use ResultSetMetaData otherwise go for ResultSet.

ResultSetMetaData.getColumnType(int column) returns a int value specifying the column type found in java.sql.Types.

ResultSetMetaData rsmd = rs.getMetaData();

int type = rsmd.getColumnType(i);

if (type == Types.VARCHAR)
    rs.getString(i);
else
    rs.getLong(i);

Platform Independent JAVA

Java is compiled to a byte code by the java compiler, which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.

JVM is the interpretor that converts byte code to machine code.

Thus if we have JVM installed on any platform, java applications work perfectly fine.


Source Code (Program.java) -- Compiler --> Byte Code (Program.class)

Byte Code (Program.class) -- JVM --> Machine Code

JIT Compiler

JIT (Just-In-Time) compiler is used to improve performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.

JIT also known as second compiler is present in the JVM.

JIT is enabled by default and operates at runtime.

The JIT analyzes the behaviour of a program while it runs and looks for opportunities to optimize the bytecode.

To disable JIT, Djava.compiler = NONE parameter can be used.

Association, Aggregation and Composition

Association - Indicates the relationship between objects.
                       Example : Computer uses keyboard as input device.
                       An association is used when one object wants another object to perform a service for it.


Aggregation - Is a special case of association, a directional association between objects. When an
                        object "has-a" another object, then you have got an aggregation between them.
                        Example : Room has a table, but the table can exist without the room.


                        public class Room
                        {
                           private Table table;
  
                           void setTable(Table table)
                           {
                              this.table=table;
                            }
                        }


Composition - Is a special case of aggregation. Composition is more restrictive. When there is a
                         composition between two objects, the composed object cannot exist without the outer 
                         object.This restriction is not there in aggregation.
                         Example : Rooms in a house, which cannot exist after the lifetime of the house.


                         public class House
                         {
                           private Room room;
 
                           House(Room roomSpecks)
                          {
                               room = new Room (roomSpecks);
                           }
                         }

How to create an Immutable class in JAVA

1) Make class as Final.
2) Private and Final variables.
3) No setter methods.
4) Values should be set only via public constructor.


public final class Contacts
{
   private final String name;
   private final String mobile;

   public Contacts (String name , String mobile)
   {
      this.name=name;
      this.mobile=mobile;
    } 

    public String getName()
    {
       return name;
    }

    public String getMobile()
    {
        return mobile;
     }
  }


Benefits of immutable classes in JAVA.

1) Immutable classes are by default thread-safe.

2) Immutable objects boost performance of Java application by reducing synchronization in code.

3) Reusability - You can cache immutable objects and reuse them much like string literals and 
    integers.
                You can use static factory methods to provide methods like valueOf(), which can return an existing immutable object from cache, instead of creating a new one.

 

Why wait(), notify() and notifyAll() are defined in Object rather than Thread

Locks are acquired on the object (monitor). One thread does not know which other thread has acquired the lock. it only knows that the monitor has been acquired and thus it has to wait.


In the above banking example, there are many ways (channels) to access any bank account.

If in a joint-account one person tries debit and other online, the person who comes first gets the money while the other has to wait.

In this example, the lock is acquired on the account and not on the channel.

Hence, wait(), notify() and notifyAll() are defined in Object rather than Thread.
Home