Working with blob data in Java

In this post let’s take a requirement that we read a pdf file from java code and store it into database and then from another java class we read that blob data from database and store it as a pdf file.

A little introduction about how java handles io streams: In Java it has two variety of streams to handle io, one for binary data(image, pdf, video, audio) and another for text data.  When we are handling with binary data then we should use binary stream classes to handle them (the class names which ends with Stream are used to handle binary data).

Classes to use when working with binary data: InputStream, OutputStream, BufferedInputStream, BufferedOutputStream, FileInputStream, FileOutputStream.

Classes to use when working with text data & inputs from keyboard: InputStreamReader, OutputStreamWriter, BufferedReader, BufferedWriter, FileReader, FileWriter.

1. Create table with blob column:

create table emps(empId int primary key,empFile blob);

2. Insert data into table (blob column) [Here inserting is done using java code by reading data from a file]

package upload;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Pdf_insert{
static String url = "jdbc:oracle:thin:@localhost:1521:XE";
static String username = "HR";
static String password = "hr";
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "insert into emps (empid,empfile) values (?,?)";
//String sql = "update emps set empfile = ? where empid = 100";
File blob = new File("D:\\small.pdf");
FileInputStream in = new FileInputStream(blob);
//InputStream in  = new ByteArrayInputStream(blob.getBytes()); // if blob is a string not a file (eg: blob = "hexdata");
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, 100);
stmt.setBinaryStream(2, in, (int)blob.length());
stmt.executeUpdate();
in.close();
conn.close();
}}

3. Read data from table (blob column) and generate pdf file from that data.

package upload;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Pdf_read
{
 static String url = "jdbc:oracle:thin:@punitp406381d:1521:XE";
 static String username = "HR";
 static String password = "hr";
 static int BUFFER_SIZE = 4096;

 public static void main(String[] args) throws Exception
 {
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection conn = DriverManager.getConnection(url, username, password);
 String sql = "SELECT empfile FROM emps where empId = '100'";
 PreparedStatement stmt = conn.prepareStatement(sql);
 ResultSet resultSet = stmt.executeQuery();

 if (resultSet.next()) {
 System.out.println("if");
 Blob blob = resultSet.getBlob("empfile");
 InputStream inputStream = blob.getBinaryStream();
 OutputStream outputStream = new FileOutputStream("D:\\ourFile.pdf");

 int bytesRead = -1;
 byte[] buffer = new byte[BUFFER_SIZE];
 while ((bytesRead = inputStream.read(buffer)) != -1) {
 outputStream.write(buffer, 0, bytesRead);
 }
 inputStream.close();
 outputStream.close();
 System.out.println("File is saved");
 }
 conn.close();
 }
}

 

Let’s have a look at few more examples.

Below code used when you have a hex string and you need to generate a file from it.


package upload;

import java.io.FileOutputStream;

public class pdf_insert
{
static String hex = "255044462D312E32200D0A25E2E3CFD30D0A200D0A392030206F626A0D0A3C3C0D0A2F4C656E677468203130203020520D0A2F46696C746572202F466C6174654465636F6465200D0A3E3E0D0A73747265616D0D0A4889CD90D14AC33014869F20EFF07BA7B266E7244D93ED6ED216062D148D82901B115B266A658AE2DBDBA40CF17E822417C9C9FF7DC9C98517AC496A05ABACCC73C0978210C77E8058D6042D5D2CF78224591B97F7D329FC274EAB7508AD31219C84C05619D93F9FC13F0A9E62315262629CD289C948B25BB99954443A239E26D8ADD9CC58AEA6F80F69E7BB24716E66AC83BF1B8605B65DBBC0F5CBEEE361FFB67BFFC2D8A3899BD7717C4AAA4C73115D9951D21449B8AC196AEE8425AF8C39D8E960DFE0A6BABCC555BB691A74658D7ADB249B92DA16BF1A4F6542C6C492D2AFE1B852E5FE407ADC97FAF3FF67AABCF8063CF5A1AA0D0A656E6473747265616D0D0A656E646F626A0D0A31302030206F626A0D0A3234360D0A656E646F626A0D0A342030206F626A0D0A3C3C0D0A2F54797065202F506167650D0A2F506172656E742035203020520D0A2F5265736F7572636573203C3C0D0A2F466F6E74203C3C0D0A2F4630203620302052200D0A2F4631203720302052200D0A3E3E0D0A2F50726F635365742032203020520D0A3E3E0D0A2F436F6E74656E74732039203020520D0A3E3E0D0A656E646F626A0D0A362030206F626A0D0A3C3C0D0A2F54797065202F466F6E740D0A2F53756274797065202F54727565547970650D0A2F4E616D65202F46300D0A2F42617365466F6E74202F417269616C0D0A2F456E636F64696E67202F57696E416E7369456E636F64696E670D0A3E3E0D0A656E646F626A0D0A372030206F626A0D0A3C3C0D0A2F54797065202F466F6E740D0A2F53756274797065202F54727565547970650D0A2F4E616D65202F46310D0A2F42617365466F6E74202F426F6F6B416E74697175612C426F6C640D0A2F4669727374436861722033310D0A2F4C61737443686172203235350D0A2F576964746873205B20373530203235302032373820343032203630362035303020383839203833332032323720333333203333332034343420363036203235302033333320323530200D0A323936203530302035303020353030203530302035303020353030203530302035303020353030203530302032353020323530203630362036303620363036200D0A34343420373437203737382036363720373232203833332036313120353536203833332038333320333839203338392037373820363131203130303020383333200D0A38333320363131203833332037323220363131203636372037373820373738203130303020363637203636372036363720333333203630362033333320363036200D0A353030203333332035303020363131203434342036313120353030203338392035353620363131203333332033333320363131203333332038383920363131200D0A353536203631312036313120333839203434342033333320363131203535362038333320353030203535362035303020333130203630362033313020363036200D0A373530203530302037353020333333203530302035303020313030302035303020353030203333332031303030203631312033383920313030302037353020373530200D0A37353020373530203237382032373820353030203530302036303620353030203130303020333333203939382034343420333839203833332037353020373530200D0A363637203235302032373820353030203530302036303620353030203630362035303020333333203734372034333820353030203630362033333320373437200D0A353030203430302035343920333631203336312033333320353736203634312032353020333333203336312034383820353030203838392038393020383839200D0A34343420373738203737382037373820373738203737382037373820313030302037323220363131203631312036313120363131203338392033383920333839200D0A333839203833332038333320383333203833332038333320383333203833332036303620383333203737382037373820373738203737382036363720363131200D0A363131203530302035303020353030203530302035303020353030203737382034343420353030203530302035303020353030203333332033333320333333200D0A333333203535362036313120353536203535362035353620353536203535362035343920353536203631312036313120363131203631312035353620363131200D0A353536205D0D0A2F456E636F64696E67202F57696E416E7369456E636F64696E670D0A2F466F6E7444657363726970746F722038203020520D0A3E3E0D0A656E646F626A0D0A382030206F626A0D0A3C3C0D0A2F54797065202F466F6E7444657363726970746F720D0A2F466F6E744E616D65202F426F6F6B416E74697175612C426F6C640D0A2F466C6167732031363431380D0A2F466F6E7442426F78205B202D323530202D323630203132333620393330205D0D0A2F4D697373696E675769647468203735300D0A2F5374656D56203134360D0A2F5374656D48203134360D0A2F4974616C6963416E676C6520300D0A2F436170486569676874203933300D0A2F58486569676874203635310D0A2F417363656E74203933300D0A2F44657363656E74203236300D0A2F4C656164696E67203231300D0A2F4D6178576964746820313033300D0A2F4176675769647468203436300D0A3E3E0D0A656E646F626A0D0A322030206F626A0D0A5B202F504446202F5465787420205D0D0A656E646F626A0D0A352030206F626A0D0A3C3C0D0A2F4B696473205B3420302052205D0D0A2F436F756E7420310D0A2F54797065202F50616765730D0A2F4D65646961426F78205B203020302036313220373932205D0D0A3E3E0D0A656E646F626A0D0A312030206F626A0D0A3C3C0D0A2F43726561746F722028313732352E666D290D0A2F4372656174696F6E446174652028312D4A616E2D332031383A3135504D290D0A2F5469746C652028313732352E504446290D0A2F417574686F722028556E6B6E6F776E290D0A2F50726F647563657220284163726F6261742050444657726974657220332E303220666F722057696E646F7773290D0A2F4B6579776F7264732028290D0A2F5375626A6563742028290D0A3E3E0D0A656E646F626A0D0A332030206F626A0D0A3C3C0D0A2F50616765732035203020520D0A2F54797065202F436174616C6F670D0A2F44656661756C7447726179203131203020520D0A2F44656661756C7452474220203132203020520D0A3E3E0D0A656E646F626A0D0A31312030206F626A0D0A5B2F43616C477261790D0A3C3C0D0A2F5768697465506F696E74205B302E39353035203120312E30383931205D0D0A2F47616D6D6120302E32343638200D0A3E3E0D0A5D0D0A656E646F626A0D0A31322030206F626A0D0A5B2F43616C5247420D0A3C3C0D0A2F5768697465506F696E74205B302E39353035203120312E30383931205D0D0A2F47616D6D61205B302E3234363820302E3234363820302E32343638205D0D0A2F4D6174726978205B302E3433363120302E3232323520302E3031333920302E3338353120302E3731363920302E3039373120302E3134333120302E3036303620302E37313431205D0D0A3E3E0D0A5D0D0A656E646F626A0D0A787265660D0A302031330D0A3030303030303030303020363535333520660D0A30303030303032313732203030303030206E0D0A30303030303032303436203030303030206E0D0A30303030303032333633203030303030206E0D0A30303030303030333735203030303030206E0D0A30303030303032303830203030303030206E0D0A30303030303030353138203030303030206E0D0A30303030303030363333203030303030206E0D0A30303030303031373630203030303030206E0D0A30303030303030303231203030303030206E0D0A30303030303030333532203030303030206E0D0A30303030303032343630203030303030206E0D0A30303030303032353438203030303030206E0D0A747261696C65720D0A3C3C0D0A2F53697A652031330D0A2F526F6F742033203020520D0A2F496E666F2031203020520D0A2F4944205B3C34373134393531303433336464343838326630356638633132343232333733343E3C34373134393531303433336464343838326630356638633132343232333733343E5D0D0A3E3E0D0A7374617274787265660D0A323732360D0A2525454F460D0A";
public static void main(String[] args) throws Exception
{
String str = "";
for(int i=0;i<hex.length();i+=2)
{
String s = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(s, 16);
str = str + (char) decimal;
}
System.out.println("str:"+str);
FileOutputStream fos = new FileOutputStream("D:\\sampleFile.pdf");
int i = 0;
while (i < str.length()) {
fos.write(str.charAt(i));
i++;
}
fos.close();
}
}

For this example reference:

https://stackoverflow.com/questions/13990941/how-to-convert-hex-string-to-java-string

Other References:

http://www.codejava.net/java-se/file-io/how-to-read-and-write-binary-files-in-java

 

Note: For online conversion of hex to binary, vice versa you can check below site

http://tomeko.net/online_tools/hex_to_file.php?lang=en

Hope you enjoyed the post!

Advertisements

String & Math functions in Java

Math functions:

java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

Math.min(num1, num2):

float minVal = Math.min(float a, float b);   
// data types allowed: int, long, float, double.

Math.max(num1, num2):

float maxVal = Math.max(float a, float b);  
// data types allowed: int, long, float, double.

Math.random(): This method returns a pseudo-random number of double data type greater than or equal to 0.0 and less than 1.0.

double randomVal = Math.random();  
// data type returns is double (o/p: 0.15726642068533314)

Math.sqrt(num1): This method returns the square root of a number.

double sqrtVal1 = Math.sqrt(25); // data type returns is double.
double sqrtVal2 = Math.sqrt(10); 
(o/p: 5.0)
(o/p: 3.1622776601683795)

Math.cbrt(num1): This method returns the square root of a number.

double sqrtVal1 = Math.cbrt(27); // data type returns is double.
double sqrtVal2 = Math.cbrt(125); 
(o/p: 3.0)
(o/p: 5.0)

Math.round(num1):

float roundVal = Math.round(float a); 
// data types allowed: float, double

Math.floor(num1): This method returns the floor value of given number.

double sqrtVal1 = Math.floor(27.89034); // data type returns is double.
(o/p: 27.0)

Math.ceil(num1): This method returns the ceiling value of given number.

double sqrtVal1 = Math.ceil(27.89034); // data type returns is double.
(o/p: 28.0)

String functions/Methods:

java.lang.String class provides 40+ methods to work with the strings.

A sample java class is also given at the bottom, for a better understanding of string functions.

equals(Str), equalsIgnoreCase(): To compare two strings. Returns true/false.

System.out.println("ravi".equals("ravi"));   // true 
System.out.println("ravi".equals("raviteja")); // false

compareTo(), compareToIgnoreCase(): To compare two strings. Returns true/false.

System.out.println("ravi".compareTo("ravi")); // 0
System.out.println("ravi".compareTo(null)); // NullPointerException

Note: For comparing two strings use the equals() method. comapreTo() method can also be used, but prefer to use equals() method as compareTo() method throws NullPointerException when comparing string with another string with null value.

contentEquals(Str): To compare a string with String Buffer.

String str1 = "StringValue";
StringBuffer str2 = new StringBuffer( "StringBuffer");
System.out.println(str1.contentEquals(str2 ));   // false

contains(Str): To check if the string contains the given string value.

String str1 = "StringValue";
String str2 = "Val";
System.out.println(str1.contains(str2));   // true

length(): To find the length of a given string.

String str1 = "StringValue"; 
str1.length(); // o/p: 11  
[Note that an array length can be found using 'arr.length;']

trim(): It’ll trim the white spaces at leading and trailing of given string.

String str1 = "     StringValue  ";  
str1.trim();  // o/p: StringValue

valueOf():  Irrespective of the data type by using this method you can convert any data type variable to string variable.

String str1 = String.valueOf(anyDataType_value);  // o/p: string format

substring(int beginIndex), substring(int beginIndex, int endIndex):  Used to get the required substring from the given string using given beginIndex, endIndex values.  Here you have to notice one thing that when beginIndex and endIndex are given, the result will include the char at start Index value and excludes (won’t include) the char endIndex value of string.

String str1 = "StringValue"
str1.substring(3);  // o/p: ingValue
str1.substring(3,8); // o/p: ingVa

split(String regex), split(String regex, int limit):  Splits the string as per given regular expression. The result will be stored as an array. You can pass the limit value also, which will splits the given string into given limit values.

 String Str = new String("Welcome-to-Hyderabad");
 String[] splitVals = Str.split("-");
 System.out.println(":"+Arrays.toString(splitVals)); 
 o/p: [Welcome, to, Hyderabad]
 
 String Str = new String("Welcome-to-Hyderabad-City");
 String[] splitVals = Str.split("-",2);
 String[] splitVals = Str.split("-",4);
 System.out.println(":"+Arrays.toString(splitVals)); 
 o/p: [Welcome, to-Hyderabad-City]
 o/p: [Welcome, to, Hyderabad, City]  

matches(String regex):  returns true if the given string matches with the given regular expression.

 String Str = "Welcome to Hyderabad City";
 System.out.println(Str.matches("(.*)Hyderabad(.*)"));  // o/p: true
 System.out.println(Str.matches("(.*)Hyderabad"));  //o/p: false

concat(Str):  returns true if the given string matches with the given regular expression.

 String Str = "Welcome to";
 System.out.println(Str.concat("Hyderabad"));
 // o/p: Welcome to Hyderabad

chatAt(int index):  returns the character present in the given string at specified location index. The return type will character.

 String Str = "Welcome to";
 char result = Str.charAt(5);
 System.out.println(result);  // o/p: m
Note: If char contains int value, use below way to convert char to int.
String Str = "137654";
int num= Character.getNumericValue(Str.charAt(3));
System.out.println(num); // o/p: 6

Arrays In Java

You already know that Array is a container which stores multiple values and the length of array will be fixed during declaration itself.

In this post let’s discuss Arrays of single dimensional, multi dimensional, Array’s functions etc.

One dimensional Array:  

long type:   long[] lng_arr = new long[3];
String type: String[] str_arr = new String[3];

similarly we can have arrays of other data types also. [byte[] anArrayOfBytes; short[]  anArrayOfShorts;  long[] anArrayOfLongs; float[] anArrayOfFloats;  double[] anArrayOfDoubles;  boolean[] anArrayOfBooleans;
char[] anArrayOfChars; String[] anArrayOfStrings;

Below is how we insert values to Array.

lng_arr[0] = 123; lng_arr[1] = 342; lng_arr[2] = 23;
str_arr [0] = "This"; str_arr [1] = "is"; str_arr [2] = "java_post"; 

You can also insert values to Array like given below. [giving values at the time of declaration itself]

long[] lng_arr = {123, 342, 23};
String[] str_arr = {"This", "is", "java_post"};

Now let’s see how we can print entire array itself. [using Arrays.toString(arr) we can achieve this]. For multi dimensional arrays we should use  Arrays.deepToString(arr).

System.out.println("lng_arr :"+lng_arr);  o/p: [J@3d04a311
System.out.println("lng_arr :"+Arrays.toString(lng_arr)); o/p: [123, 342, 23]
System.out.println("str_arr :"+Arrays.toString(str_arr)); o/p: [This,  is,  java_post]

Now let’s print single required value from the array: (for printing single value from the array, using of Arrays.toString(arr) is not required, which is used to print entire array in string foramt.

System.out.println("lng_arr[0] :"+lng_arr[0]);  o/p: 123
System.out.println("str_arr[2]:"+str_arr[2]);  o/p: java_post

Multi dimensional Array:  

long type:   long[][] lng_arr = new long[3][2];  
// [[a1, b1], [a2, b2], [a3, b3]]
(3 * 2) matrix would be like given below.
[a1, b1]
[a2, b2]
[a3, b3]
where [0][0] = a1;  [0][1] = b1;  [1][0] = a2;  [1][1] = b2;  [2][0] = a3;  [2][1] = b3; 

String type: String[][] str_arr = new String[2][3];  
// [[a1, b1,c1], [a2, b2, c2]]

similarly we can have arrays of other data types also. [byte[][] anArrayOfBytes; short[][]  anArrayOfShorts;  long[][] anArrayOfLongs; float[][] anArrayOfFloats;  double[][] anArrayOfDoubles;  boolean[][] anArrayOfBooleans;
char[][] anArrayOfChars; String[][] anArrayOfStrings;

Below is how we insert values to Array.

lng_arr[0][0] = 123;   lng_arr[0][1] = 342;    lng_arr[1][0] = 23;  lng_arr[1][1] = 223;  lng_arr[2][0] = 13;     lng_arr[2][1] = 323; 

str_arr [0][0] = “Mr. “;  str_arr [0][1] = “Mrs. “;    str_arr [0][2] = “Ms. “;  str_arr [1][0] = “Swamy “;  str_arr [1][1] = “Kumar”;    str_arr [1][2] = “Sita”; 

You can also insert values to Array like given below. [giving values at the time of declaration itself]

long[][] lng_arr = {{123, 342}, {23, 223}, {13, 323}};
String[][] str_arr = {{"Mr. ", "Mrs. ","Ms. "},{"Swamy","Kumar","Sita"}};

Now let’s see how we can print entire array itself. [using Arrays.deepToString(arr) we can achieve this].

System.out.println("lng_arr :"+Arrays.deepToString(lng_arr ));  
o/p: [[123, 342], [23,223], [13,323]]

System.out.println("str_arr :"+Arrays.deepToString(str_arr )); 
o/p: [[Mr. , Mrs. , Ms], [Swamy, Kumar, Sita]]

Now let’s print single required value from the array: (for printing single value from the array, using of Arrays.toString(arr) is not required, which is used to print entire array in string foramt.

System.out.println("lng_arr[0][1]:"+lng_arr[0][1]);  o/p: 342
System.out.println("str_arr[1][2]:"+str_arr[1][2]);  o/p:  sita

Arrays functions:  

Sort:   Sorting of Array can be achieved using Arrays.sort() method.

Given your array like below

long[] lng_arr = {18, 13, 23, 16, 20};
Arrays.sort(lng_arr);  
System.out.println("lng_arr:"+  Arrays.toString(lng_arr));  
o/p:  [13, 16, 18, 20, 23]

Sort some portion of Array: 

Sorting of Array can be achieved using Arrays.sort() method.

Given your array like below

long[] lng_arr = {18, 13, 23, 16, 20, 34, 12, 7};
Arrays.sort(lng_arr, 2, 5);  
System.out.println("lng_arr:"+  Arrays.toString(lng_arr)); 
o/p:  [18, 13, 16, 20, 23, 34  ,12, 7]

Get a value from array at specified index:

long[] lng_arr1 = {18, 13, 23, 16, 20, 34, 12, 7};
System.out.println(lng_arr1[4]);  // o/p:  20

Note: For list you need to use the get function.
List<Long> lst = new List<>();  
lst.add(27); lst.add(34); lst.add(23);
lst.get(1); //o/p: 34

To Print Entire Array: use Arrays.toString for one dimensional array and use  Arrays.deepToString for multi dimensional arrays and arrays converted from list.

long[] lng_arr1 = {18, 13, 23, 16, 20};
long[][] lng_arr2 = {{123, 342}, {23, 223}, {13, 323}};
System.out.println(Arrays.toString(lng_arr1)); 
System.out.println(Arrays.deepToString(lng_arr2));  
o/p:  [18, 13, 23, 16, 20]
[[123, 342], [23,223], [13,323]]

length: use length to find the length of an array.

long[] lng_arr = {18, 13, 23, 16, 20};
System.out.println(lng_arr.length);   o/p:  5

Note: To find the length of a list use size function.
List<Long> lst = new List<>();  
lst.add(27); lst.add(34); lst.add(23); 
lst.size(); //o/p: 3

To find the length of a string use length() function.
String val = "ravi";
System.out.println(val.length()); //o/p: 4

Happy Coding !

 

 

Singleton Implementation with Double Checked Locking in Java

-> Singleton implementation is nothing but creating the object instance only once and reusing the same instance when ever needed, instead creating a new one each time when needed.
-> In the below code instance is of lazy loading initializing type as the instance of class is declared in static variable but which is initialized only when the method getInstacne is invoked. Eager loading will be like declaring and initializing at the same time.like shown below.
private volatile static Singleton instance = new Singleton();

Double checked locking Idiom:

-> Now lets talk about Double checked locking idiom in singleton implementation. Here object is null or not will be checked twice and then object for the class will be created.
-> Why Volatile is used?: In double checked locking idiom, suppose if thread A is entered first null condition and then second null condition, then it will create an object for the class. Now suppose if thread B is entered first null condition, at the same time for thread A object is getting created (but instance creation is not completed yet) then as the null condition fails it’ll just return the same object instance which not completely initialized (half baked object), which leads to unexpected behavior of object.
So when voltaile is used, which makes the object getting published only when it is completely initialized, which avoids above problem.
-> The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. This results in Thread B failing because it is using a partially constructed version of instance.

Code:

public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

 

Few References:

http://javarevisited.blogspot.in/2014/05/double-checked-locking-on-singleton-in-java.html

 

 

Data Types in Java

Primitive Data types:

In Java there are eight (8) primitive data types. For all those primitive data types wrapper classes also available.

If you define the primitive data types as global variables they hold some default values which are given below.

/* Primitive data types and their default values*/
static byte by; //0
static char c; // space
static short sh; //0
static int i; //0
static long l; //0
static float f; //0.0
static double d; //0.0
static boolean b; //false

Note: If you define the primitive data types as local variables they hold nothing and you must initialize them.

Wrapper Classes (Non Primitive Data types):

If you define the wrapper class data types as global variables then they hold some default values which is null

 /* Wrapper Class data types */
static Byte by1; //null
static Character c1; //null
static Short sh1; //null
static Integer i1; //null
static Long l1; //null
static Float f1; //null
static Double d1; //null
static Boolean b1; //null

static BigDecimal bd; //null
static String s; //null

Note: If you define these wrapper class data types as local variables they hold nothing and you must initialize them.  There are few more wrapper classes like Array, List etc.

Sorting in Java

Sorting the numbers is easy in Java. Collections utility class provides the ‘sort’ method for sorting the numbers. [Don’t confuse with Collection which is an Interface]. To the Collections  Sort method you need to input numbers in List format. Though numbers present in Array also can be converted to List and then can be sorted. Java also provides another utility class ‘Arrays’ which has also Sort method. You can use either class methods for sorting on your convenience.

Collections.sort method expects List as input [array can also be send by converting to list object using Arrays.asList(arrayObj) method]

Arrays.sort method expects Array as input [List can also be send by converting to Array object using listObj.toArray() method]

Eg1: Sorting Numbers in List

List <Integer> numLst1 = new ArrayList<>();
numLst1.add(20);
numLst1.add(10);
numLst1.add(04);
Collections.sort(numLst1);
//Arrays.sort(numLst1.toArray());
int f = 0;
while(f< numLst1.size()){
System.out.println(numLst1.get(f));
f++;
}

o/p:   [4    10     20]

Eg2: Sorting Numbers in Array

Here we are converting Array to List and then sorting.

Integer[] numLst1 = {10, 30, 05};
Arrays.sort(numLst1);
//Collections.sort(Arrays.asList(numLst1));
int f = 0;
while(f<numLst1.length()){
System.out.println(numLst1[f].intValue());
f++;
}

o/p: [5    10     30]

Eg3: Sorting numbers and finding smallest number

Now let’s get into some deep by taking a requirement which returns the smallest number from the Array which should not be 0. Means if the Array contains numbers like [12, 20, 5, 30, 0, 50] then it should return smallest number as ‘5’ (not zero).

Integer[] returnVal = {10, 5, 20, 0};
Arrays.sort(returnVal);
//Collections.sort(Arrays.asList(returnVal));
int f= 0;
int smallValue = 0;
while(f < returnVal.length){
if (returnVal[f].intValue() !=0){
smallValue = returnVal[f].intValue();
break;
}
f++;
}
System.out.println("smallValue:"+smallValue);

o/p:   5

Sorting Numbers in HashSet & HashMap [not with the help of Sort method]

This can be achieved with the help of TreeSet. From TreeSet if you try to move to HashSet again then the insertion order will be lost. So keep the sorted result in TreeMap only or store them into LinkedHashSet where the insertion order is maintained. Similarly for HashMap sorting can be achieved with the help of TreeMap.


HashSet<Integer> hs = new HashSet<>();
hs.add(10);
hs.add(6);
hs.add(20);
hs.add(12);
System.out.println("hs:"+hs);
TreeSet<Integer> ts = new TreeSet<>();
ts.addAll(hs);
System.out.println("ts:"+ts);

o/p:     hs:[20, 6, 10, 12]      ts:[6, 10, 12, 20]

equals() vs contentEquals() vs ==

Why equals method is used?

To compare two string contents [One string can be in stack memory and other can be in Heap memory, still it compares the contents of the strings]

String s1 = “abc”;

String s2 =  “abc”;

String s3 = new String (“abc”);

System.out.println(s1.equals(s2));  // o/p: True  [hashcodes are same in this case]

System.out.println(s1.equals(s3));   // o/p: True [hashcodes are different in this case]

Why ‘==’ is used?

It is an operator which compares the Hashcodes (not the content present inside them).

String s1 = “abc”;

String s2 =  “abc”;

String s3 = new String (“abc”);

System.out.println(s1==s2);  // o/p: True  [hashcodes are same in this case]

System.out.println(s1==s3);   // o/p: False [hashcodes are different in this case]

Why contentEquals is used?

It is used to compare the String object with StringBuffer/StringBuilder/ Char Array objects.

Note:

  • You can’t compare String object with StringBuffer object using equals method.
  • You can compare String object with another String object using equals and contentEquals methods. [both are same, but equals is specific to compare strings only]

 

String s1 =”abc”;

String s2 =new StringBuilder(“abc”);

System.out.println(s1.contentEquals(s2)); // o/p: true [hashcodes are different in this case]