Monday, April 30, 2018

Swap four variables without using fifth variables !!

Problem statement: Swap four variables without using fifth variables !!

Problem solving: 
  1. public class SwapFourNumberWithoutFifthVariable {
  2. public static void main(String[] args) {
  3. int a = 10;
  4. int b = 20;
  5. int c = 30;
  6. int d = 40;

  7. a = a + b + c + d;
  8. b = a - (b + c + d);
  9. c = a - (b + c + d);
  10. d = a - (b + c + d);
  11. a = a - (b + c + d);
  12. System.out.println("after swap value of a: " + a);
  13. System.out.println("after swap value of b: " + b);
  14. System.out.println("after swap value of c: " + c);
  15. System.out.println("after swap value of d: " + d);
  16. }
  17. }
Output:
after swap value of a: 40
after swap value of b: 10
after swap value of c: 20
after swap value of d: 30

Swap three variables without using fourth variable !!

  1. public class SwapThreeNumberWithoutFourthVariable {
  2. public static void main(String[] args) {
  3. int a = 10;
  4. int b = 20;
  5. int c = 30;

  6. a = a + b + c;
  7. b = a - (b + c);
  8. c = a - (b + c);
  9. a = a - (b + c);
  10. System.out.println("after swap value of a: " + a);
  11. System.out.println("after swap value of b: " + b);
  12. System.out.println("after swap value of c: " + c);
  13. }
  14. }
Output:
after swap value of a: 30
after swap value of b: 10
after swap value of c: 20

Swap two variables without using third variable !!

  1. public class SwapTwoNumberWithoutThirdVariable {
  2. public static void main(String[] args) {
  3. int a = 10;
  4. int b = 20;

  5. a = a + b;
  6. b = a - b;
  7. a = a - b;
  8. System.out.println("after swap value of a: " + a);
  9. System.out.println("after swap value of b: " + b);
  10. }
  11. }
Output:
after swap value of a: 20
after swap value of b: 10

Swap two variables using third variable !

  1. public class SwapTwoNumberWithThirdVariable {
  2. public static void main(String[] args) {
  3. int a = 10;
  4. int b = 20;

  5. int temp;
  6. temp = a;
  7. a = b;
  8. b = temp;
  9. System.out.println("after swap value of a: " + a);
  10. System.out.println("after swap value of b: " + b);
  11. }
  12. }
Output: 
after swap value of a: 20
after swap value of b: 10

Compare two file content if it is equal or not !!

Using FileUtils:
  1. import java.io.File;
  2. import org.apache.commons.io.FileUtils;

  3. public class CompareFileContent {
  4. public static void main(String[] args) throws Exception {
  5. File file1 = new File("D:\\data.txt");
  6. File file2 = new File("D:\\data1.txt");
  7. boolean isEqual = FileUtils.contentEquals(file1, file2);
  8. System.out.println(isEqual == true ? "equal" : "not equal");
  9. }
  10. }
Output:
equal

data.txt - file:
Hi guys !!
This is Ishaan from India.
and I'm reading the data from a text file line by line using BufferedReader.
Isn't it interesting !! to read the data from a file line by line 
irrespective of amount of data that a file is having.

data1.txt - file:
Hi guys !!
This is Ishaan from India.
and I'm reading the data from a text file line by line using BufferedReader.
Isn't it interesting !! to read the data from a file line by line 
irrespective of amount of data that a file is having.

Count the characters in a file or size of a file !!

Using File:
  1. import java.io.File;

  2. public class CountCharInFile {
  3. public static void main(String[] args) throws Exception {
  4. File file = new File("D:\\data.txt");
  5. int fileDataLen = (int) file.length();
  6. System.out.println(fileDataLen);
  7. }
  8. }
Output: 
241

data.txt file:
Hi guys !!
This is Ishaan from India.
and I'm reading the data from a text file line by line using BufferedReader.
Isn't it interesting !! to read the data from a file line by line 
irrespective of amount of data that a file is having.

Read properties from an xml file !!

Using Properties class:
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.util.Enumeration;
  4. import java.util.Properties;

  5. public class ReadPropertiesXmlFile {
  6. public static void main(String[] args) throws Exception {
  7. File file = new File("D:\\prop.xml");
  8. FileInputStream fileInput = new FileInputStream(file);
  9. Properties properties = new Properties();
  10. properties.loadFromXML(fileInput);
  11. fileInput.close();

  12. Enumeration enuKeys = properties.keys();
  13. while (enuKeys.hasMoreElements()) {
  14. String key = (String) enuKeys.nextElement();
  15. String value = properties.getProperty(key);
  16. System.out.println(key + ": " + value);
  17. }
  18. }
  19. }
Output:
favoriteSeason: spring
favoriteDay: today
favoriteFruit: apple

prop.xml - file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Here are some favorites</comment>
<entry key="favoriteSeason">spring</entry>
<entry key="favoriteFruit">apple</entry>
<entry key="favoriteDay">today</entry>

</properties>

Read the data from properties file !!

Using Properties class:
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.util.Enumeration;
  5. import java.util.Properties;

  6. public class ReadPropertiesFiles {
  7. public static void main(String[] args) throws IOException {

  8. File file = new File("D:\\contacts.properties");
  9. FileInputStream fis = new FileInputStream(file);
  10. Properties prop = new Properties();
  11. prop.load(fis);
  12. fis.close();

  13. Enumeration enuKeys = prop.keys();
  14. while (enuKeys.hasMoreElements()) {
  15. String key = (String) enuKeys.nextElement();
  16. String value = prop.getProperty(key);
  17. System.out.println(key + " = " + value);
  18. }
  19. }
  20. }
Output:
delhi = sumit
japan = chet
bangalore = raju
chennai = ishaan

Read file using BufferedReader !!

Using BufferedReader:
  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.BufferedReader;

  4. public class ReadFileByBufferedReader {

  5. public static void main(String[] args) throws Exception {
  6. File file = new File("D://data.txt");
  7. FileReader fr = new FileReader(file);
  8. BufferedReader br = new BufferedReader(fr);
  9. StringBuffer sb = new StringBuffer();

  10. String line = br.readLine(); // read the line
  11. while (null != line) {
  12. sb.append(line); // append the line
  13. sb.append("\n");
  14. line = br.readLine(); // read the line
  15. }
  16. System.out.println(sb.toString());
  17. fr.close();
  18. }
  19. }
Output:
Hi guys !!
This is Ishaan from India.
and I'm reading the data from a text file line by line using BufferedReader.
Isn't it interesting !! to read the data from a file line by line 
irrespective of amount of data that a file is having.

Read data from a file using BufferedReader !!

Using BufferedReader:
  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.BufferedReader;

  4. public class ReadFileByBufferedReader {

  5. public static void main(String[] args) {
  6. try {
  7. File file = new File("D://data.txt");
  8. FileReader fr = new FileReader(file);
  9. BufferedReader br = new BufferedReader(fr);
  10. String line = br.readLine(); // read the line
  11. while (null != line) {
  12. System.out.println(line); // print the line
  13. line = br.readLine(); // read the next line
  14. }
  15. fr.close();
  16. } catch (Exception e) {
  17. System.out.println("excepton occured in " + e);
  18. }
  19. }
  20. }
Note: extension support .java/.txt/.xml/.yml/.html/.css etc file

Output:
Hi guys !!
This is Ishaan from India.
and I'm reading the data from a text file line by line using BufferedReader.
Isn't it interesting !! to read the data from a file line by line
irrespective of amount of data that a file is having.

II Approach:

  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.BufferedReader;

  4. public class ReadFileByBufferedReader {

  5. public static void main(String[] args) {
  6. File file = null;
  7. FileReader fr = null;
  8. BufferedReader br = null;
  9. try {
  10. file = new File("D://data.txt");
  11. fr = new FileReader(file);
  12. br = new BufferedReader(fr);
  13. String line = br.readLine(); // read the next line

  14. while (line != null) {
  15. System.out.println(line); // print the line
  16. line = br.readLine(); // read the next line
  17. }
  18. } catch (Exception e) {
  19. System.out.println("excepton occured in " + e);
  20. } finally {
  21. try {
  22. if (fr != null) {
  23. fr.close();
  24. }
  25. if (br != null) {
  26. br.close();
  27. }
  28. } catch (Exception e) {
  29. System.out.println("excepton occured in finally block " + e);
  30. }
  31. }
  32. }
  33. // support .java/.txt/.xml/.yml/.html/.css etc file
  34. }

Sunday, April 29, 2018

Read data from a file using FileReader class !!

Read file using FileReader:
  1. import java.io.File;
  2. import java.io.FileReader;

  3. public class ReadFileByFileReader {
  4. public static void main(String[] args) {
  5. try {
  6. File file = new File("D:\\data.txt");
  7. FileReader fr = new FileReader(file);

  8. int length = (int) file.length();
  9. char c[] = new char[length];

  10. fr.read(c);
  11. String data = new String(c);

  12. System.out.println(data);
  13. fr.close();
  14. } catch (Exception e) {
  15. System.out.println("excepton occured in " + e);
  16. }
  17. }
  18. }
Output:
Hi guys !!
This is Ishaan from India.
and I'm reading the data from a text file line by line using BufferedReader.
Isn't it interesting !! to read the data from a file line by line 
irrespective of amount of data that a file is having.


Read / Write data in a file for transient field using ObjectOutputStream

Using ObjectOutputStream class & transient keyword:
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.ObjectOutputStream;
  4. import java.io.Serializable;

  5. class Employee implements Serializable {

  6. private static final long serialVersionUID = 1L;
  7. int id;
  8. String name;
  9. // double salary;
  10. transient double salary;

  11. public Employee(int id, String name, double salary) {
  12. this.id = id;
  13. this.name = name;
  14. this.salary = salary;
  15. }

  16. @Override
  17. public String toString() {
  18. return "[id: " + id + ", name: " + name + ", salary: " + salary + "]";
  19. }
  20. }

  21. public class WriteByObjectOutputStreamExe {

  22. public static void main(String[] args) throws Exception {
  23. File file = new File("D:\\data1.txt");
  24. FileOutputStream fileStream = new FileOutputStream(file);
  25. ObjectOutputStream objStream = new ObjectOutputStream(fileStream);

  26. Employee e1 = new Employee(101, "suresh", 2000);

  27. objStream.writeObject(e1);
  28. objStream.flush();
  29. objStream.close();
  30. }
  31. }
Output:
ͭ sr  com.ishaan.filehandling.Employee        I idL namet Ljava/lang/String;xp   et suresh

Read transient field data from a file using ObjectInputStream:
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.ObjectInputStream;

  4. public class ReadFileByObjectInputStreamExe {

  5. public static void main(String[] args) throws Exception {
  6. File file = new File("D:\\data1.txt");
  7. FileInputStream fileStream = new FileInputStream(file);
  8. ObjectInputStream objStream = new ObjectInputStream(fileStream);

  9. Employee emp = (Employee) objStream.readObject();

  10. System.out.println(emp.toString());
  11. objStream.close();
  12. }
  13. }
Output: 
[id: 101, name: suresh, salary: 0.0]

Write data from properties to xml file !!

Using Properties class:
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.util.Properties;

  4. public class WritePropertiesXmlFile {
  5. public static void main(String[] args) throws Exception {
  6. Properties properties = new Properties();
  7. properties.setProperty("suresh", "2000");
  8. properties.setProperty("mahesh", "1200");
  9. properties.setProperty("ritesh", "2100");

  10. File file = new File("D:\\test2.xml");
  11. FileOutputStream fileOut = new FileOutputStream(file);
  12. properties.storeToXML(fileOut, "balance-sheet");
  13. fileOut.close();
  14. }
  15. }
Output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>balance-sheet</comment>
<entry key="ritesh">2100</entry>
<entry key="suresh">2000</entry>
<entry key="ishaan">0000</entry>
<entry key="mahesh">1200</entry>
</properties>

Write the data in properties file !!

Using Properties class:
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.util.Properties;

  5. public class WritePropertiesFiles {

  6. public static void main(String[] args) throws IOException {
  7. Properties prop = new Properties();
  8. prop.setProperty("bangalore", "raju");
  9. prop.setProperty("delhi", "ritesh");
  10. prop.setProperty("chennai", "ishaan");
  11. prop.setProperty("japan", "chet");

  12. File file = new File("D:\\contacts.properties");
  13. FileOutputStream fileStream = new FileOutputStream(file);
  14. prop.store(fileStream, "store the contacts");
  15. fileStream.close();
  16. }
  17. }
Output:
#store the contacts
#Sun Apr 29 20:22:15 IST 2018
delhi=ritesh
japan=chet
chennai=ishaan
bangalore=raju

Write the data using PrintWriter in java !!

Using PrintWriter:
  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.PrintWriter;
  4. import java.io.IOException;

  5. public class WriteByPrintWriterExe {
  6. public static void main(String[] args) throws IOException {
  7. File file = new File("D:\\data1.txt");
  8. FileWriter fw = new FileWriter(file);
  9. PrintWriter pw = new PrintWriter(fw);

  10. for (int i = 0; i < 5; i++) {
  11. pw.write("using PrintWriter !!");
  12. pw.append("\n");
  13. }
  14. pw.close();
  15. }
  16. }
Output:
using PrintWriter !!
using PrintWriter !!
using PrintWriter !!
using PrintWriter !!
using PrintWriter !!

Read file using ObjectInputStream !!

Using ObjectInputStream:
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.ObjectInputStream;

  4. public class ReadFileByObjectInputStreamExe {

  5. public static void main(String[] args) throws Exception {
  6. File file = new File("D:\\data1.txt");
  7. FileInputStream fileStream = new FileInputStream(file);
  8. ObjectInputStream objStream = new ObjectInputStream(fileStream);

  9. Employee emp = (Employee) objStream.readObject();

  10. System.out.println(emp.toString());
  11. objStream.close();
  12. }
  13. }
Employee.java:
  1. import java.io.Serializable;
  2. class Employee implements Serializable {

  3. private static final long serialVersionUID = 1L;
  4. int id;
  5. String name;
  6. double salary;
  7. // transient double salary;

  8. public Employee(int id, String name, double salary) {
  9. this.id = id;
  10. this.name = name;
  11. this.salary = salary;
  12. }

  13. @Override
  14. public String toString() {
  15. return "[id: " + id + ", name: " + name + ", salary: " + salary + "]";
  16. }
  17. }
Output: 
[id: 101, name: suresh, salary: 2000.0]

Write data in a file using ObjectOutputStream !!

Using ObjectOutputStream:
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.ObjectOutputStream;
  4. import java.io.Serializable;

  5. class Employee implements Serializable {

  6. private static final long serialVersionUID = 1L;
  7. int id;
  8. String name;
  9. double salary;
  10. // transient double salary;

  11. public Employee(int id, String name, double salary) {
  12. this.id = id;
  13. this.name = name;
  14. this.salary = salary;
  15. }

  16. @Override
  17. public String toString() {
  18. return "[id: " + id + ", name: " + name + ", salary: " + salary + "]";
  19. }
  20. }

  21. public class WriteByObjectOutputStreamExe {

  22. public static void main(String[] args) throws Exception {
  23. File file = new File("D:\\data1.txt");
  24. FileOutputStream fileStream = new FileOutputStream(file);
  25. ObjectOutputStream objStream = new ObjectOutputStream(fileStream);

  26. Employee e1 = new Employee(101, "suresh", 2000);

  27. objStream.writeObject(e1);
  28. objStream.flush();
  29. objStream.close();
  30. }
  31. }
Output:
ͭ sr  com.ishaan.filehandling.Employee        I idD salaryL namet Ljava/lang/String;xp   e@à €     t suresh


Write the data in a file using OutputStreamWriter !!

Using OutputStreamWriter: 
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.OutputStreamWriter;

  4. public class WriteByOutputStreamWriterExe {

  5. public static void main(String[] args) throws Exception {

  6. File file = new File("D:\\data1.txt");
  7. FileOutputStream fileStream = new FileOutputStream(file);
  8. OutputStreamWriter outputStream = new OutputStreamWriter(fileStream);

  9. for (int i = 0; i < 5; i++) {
  10. outputStream.write("using OutputStreamWriter !!");
  11. outputStream.append("\n");
  12. }
  13. outputStream.close();
  14. }
  15. }

Output: 
using OutputStreamWriter !!
using OutputStreamWriter !!
using OutputStreamWriter !!
using OutputStreamWriter !!
using OutputStreamWriter !!

Write the data in a file using OutputStreamWriter !!

Using OutputStreamWriter: 
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.OutputStreamWriter;
  4. import java.io.BufferedWriter;

  5. public class WriteByOutputStreamWriterExe {

  6. public static void main(String[] args) throws Exception {

  7. File file = new File("D:\\data1.txt");
  8. FileOutputStream fileStream = new FileOutputStream(file);
  9. OutputStreamWriter outputStream = new OutputStreamWriter(fileStream);
  10. BufferedWriter bw = new BufferedWriter(outputStream);

  11. for (int i = 0; i < 5; i++) {
  12. bw.write("Using FileOutputStream. Isn't is interesting !! :)");
  13. bw.newLine();
  14. }
  15. bw.close();
  16. }
  17. }
Output: 
Using FileOutputStream. Isn't is interesting !! :)
Using FileOutputStream. Isn't is interesting !! :)
Using FileOutputStream. Isn't is interesting !! :)
Using FileOutputStream. Isn't is interesting !! :)
Using FileOutputStream. Isn't is interesting !! :)

Write the data in a file using BufferedWriter !!

Using BufferedWriter:
  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.BufferedWriter;
  4. import java.io.IOException;

  5. public class WriteByBufferedWriterExe {

  6. public static void main(String[] args) throws IOException {
  7. String contents = "writing data using BufferedWriter. Isn't it interesting !!)";

  8. File file = new File("D:\\data1.txt");
  9. FileWriter fw = new FileWriter(file);
  10. BufferedWriter bw = new BufferedWriter(fw);

  11. for (int i = 0; i < 5; i++) {
  12. bw.write(contents);
  13. bw.newLine(); // bw.append("\n");
  14. }
  15. bw.close();
  16. }
  17. }


Output:
writing data using BufferedWriter. Isn't it interesting !! :)
writing data using BufferedWriter. Isn't it interesting !! :)
writing data using BufferedWriter. Isn't it interesting !! :)
writing data using BufferedWriter. Isn't it interesting !! :)
writing data using BufferedWriter. Isn't it interesting !! :)

Write the data in a file using Files class !!

Using Files class:
  1. import java.nio.file.Files;
  2. import java.nio.file.Paths;
  3. import java.nio.file.Path;
  4. import java.io.IOException;

  5. public class WriteByFiles {
  6. public static void main(String[] args) throws IOException {
  7. String content = "writing data to data1.txt file using Files class !!";
  8. String uri = "D:\\data1.txt";
  9. Path path = Paths.get(uri);
  10. Files.write(path, content.getBytes());
  11. }
  12. }
Output:
writing data to data1.txt file using Files class !!

Write same data multiple times in a file using FileWriter class !!

Using FileWriter:
  1. import java.io.File;
  2. import java.io.FileWriter;

  3. public class WriteByFileWriterExe {

  4. public static void main(String[] args) throws Exception {
  5. File file = new File("D:\\data1.txt");
  6. FileWriter fw = new FileWriter(file);

  7. for (int i = 0; i < 5; i++) {
  8. fw.write("using FileWriter !!");
  9. fw.append("\n");
  10. }
  11. fw.close();
  12. }
  13. }
Output:

using FileWriter !!
using FileWriter !!
using FileWriter !!
using FileWriter !!
using FileWriter !!

Write the data in a file using FileWriter class !!

Using FileWriter: 
  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.IOException;

  4. public class WriteByFileWriter {

  5. public static void main(String[] args) throws IOException {
  6. File file = new File("D:\\data1.txt");
  7. FileWriter contacts = new FileWriter(file);
  8. contacts.write("suresh - 9999999999\n");
  9. contacts.write("ritesh - 0000000000\n");
  10. contacts.write("mahesh - 8888888888");
  11. contacts.close();
  12. }
  13. }
Output:
suresh - 9999999999
ritesh - 0000000000
mahesh - 8888888888

Difference b/w FileOutputStream and FileWriter in java ?

  • FileOutputStream class is meant for writing streams of raw bytes / java object such as image data.
  • FileWriter class is meant for writing character data to a file. 
  • Similarity b/w FileOutputStream & FileWriter: Both the classes belongs to java.io package

What are the necessary steps to work with JDBC ?

There are 5 steps to work with JDBC as illustrated with an example below:
  1. import java.sql.DriverManager;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.Statement;
  5. import java.math.BigDecimal;
  6. import java.sql.Blob;

  7. public class JDBCConfiguration {

  8. public static void main(String[] args) {

  9. Connection con = null;
  10. Statement stmt = null;
  11. ResultSet rs = null;
  12. try {

  13. // 1. Load the driver
  14. Class.forName("com.mysql.jdbc.Driver");

  15. // 2. Get the DB connection via driver
  16. String dbURL = "jdbc:mysql://ishaan-pc:3306/mydb?user=root&password=root";
  17. con = DriverManager.getConnection(dbURL); // DriverManager : class
  18. // getConnection() : static

  19. // 3. Execute the SQL query via connection
  20. String query = "SELECT * FROM EMPLOYEE";
  21. stmt = con.createStatement();
  22. rs = stmt.executeQuery(query);

  23. // 4. Process the result
  24. while (rs.next()) {
  25. int id = rs.getInt("empid");
  26. String name = rs.getString("empname");
  27. long age = rs.getLong("age");
  28. double salary = rs.getDouble("salary");
  29. BigDecimal serialNumber = rs.getBigDecimal("serialnum");
  30. boolean status = rs.getBoolean("status");
  31. /*
  32. * BLOB - Binary Large Object that contains a variable amount of
  33. * data. Values are treated as binary strings.We don't need to
  34. * specify length while creating a column
  35. */
  36. Blob picture = rs.getBlob("emppicture");

  37. System.out.println("emp id: " + id);
  38. System.out.println("emp name: " + name);
  39. System.out.println("emp age: " + age);
  40. System.out.println("emp salary: " + salary);
  41. System.out.println("emp serial no: " + serialNumber);
  42. System.out.println("Is emp active?: " + status);
  43. System.out.println("emp photo: " + picture);

  44. }
  45. } catch (Exception e) {
  46. System.out.println("exception occured due to : " + e);
  47. } finally {

  48. // 5. Close all the JDBC objects
  49. try {
  50. if (con != null) {
  51. con.close();
  52. }
  53. if (stmt != null) {
  54. stmt.close();
  55. }
  56. if (rs != null) {
  57. rs.close();
  58. }
  59. } catch (Exception e) {
  60. System.out.println("exception occured in finally block : " + e);
  61. }
  62. }
  63. }
  64. }
Output: 
emp id: 101
emp name: ishaan
emp age: 21
emp salary: 9000
emp serial no: 11229933994439101
Is emp active?: true
emp photo: 👨

java.lang.Class.forName() method features !!

Class.forName(String fullyQualifiedClassName): It loads the class or interface at run time (dynamically) into the memory and returns the Class object associated with the class or interface with the given string name

  1. public class ClassForNameImpl {
  2. public static void main(String[] args) {
  3. try {
  4. Class<?> cls1 = Class.forName("com.ishaan.jdbc.LoadDemoClass");
  5. System.out.println("return value of forName() method: " + cls1);
  6. System.out.println("--------------------------------------");
  7. String qualifiedClassName = cls1.getName();
  8. System.out.println("return value of getName() method: " + qualifiedClassName);

  9. System.out.println("--------------------------------------");
  10. String onlyClassName = cls1.getSimpleName();
  11. System.out.println("return value of getSimpleName() method: " + onlyClassName);

  12. System.out.println("--------------------------------------");
  13. ClassLoader cLoader = cls1.getClassLoader();
  14. System.out.println("return value of getClassLoader() method: " + cLoader);

  15. System.out.println("--------------------------------------");
  16. System.out.println("return value of getSystemClassLoader() method: " + ClassLoader.getSystemClassLoader());
  17. System.out.println("--------------------------------------");
  18. System.out.println("return value of loadClass() method: " + cLoader.loadClass(qualifiedClassName));

  19. System.out.println("#########################################");

  20. Class<?> cls2 = Class.forName("java.util.ArrayList");
  21. System.out.println("return value of forName() method: " + cls2);

  22. System.out.println("--------------------------------------");
  23. String qualifiedClassName2 = cls2.getName();
  24. System.out.println("return value of getName() method: " + qualifiedClassName2);

  25. System.out.println("--------------------------------------");
  26. String onlyClassName2 = cls2.getSimpleName();
  27. System.out.println("return value of getSimpleName() method: " + onlyClassName2);

  28. System.out.println("--------------------------------------");
  29. ClassLoader cLoader2 = cls2.getClassLoader();
  30. System.out.println("return value of getClassLoader() method: " + cLoader2);

  31. System.out.println("--------------------------------------");
  32. System.out.println("return value of getSystemClassLoader() method: " + ClassLoader.getSystemClassLoader());
  33. System.out.println("--------------------------------------");
  34. System.out.println("return value of loadClass() method: " + cLoader.loadClass(qualifiedClassName2));

  35. System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");

  36. Class<?> cls3 = Class.forName("java.lang.Thread");
  37. System.out.println("return value of forName() method: " + cls3);

  38. System.out.println("--------------------------------------");
  39. String qualifiedClassName3 = cls3.getName();
  40. System.out.println("return value of getName() method: " + qualifiedClassName3);

  41. System.out.println("--------------------------------------");
  42. String onlyClassName3 = cls3.getSimpleName();
  43. System.out.println("return value of getSimpleName() method: " + onlyClassName3);

  44. System.out.println("--------------------------------------");
  45. ClassLoader cLoader3 = cls3.getClassLoader();
  46. System.out.println("return value of getClassLoader() method: " + cLoader3);

  47. System.out.println("--------------------------------------");
  48. System.out.println("return value of getSystemClassLoader() method: " + ClassLoader.getSystemClassLoader());
  49. System.out.println("--------------------------------------");
  50. System.out.println("return value of loadClass() method: " + cLoader.loadClass(qualifiedClassName3));

  51. } catch (Exception e) {
  52. System.out.println("Class not found, please pass the fully qualified class name as an input argument for the method Class.forName() !!");
  53. System.out.println(e.getMessage())
  54. }
  55. }
  56. }
Output: 

return value of forName() method: class com.ishaan.jdbc.LoadDemoClass
--------------------------------------
return value of getName() method: com.ishaan.jdbc.LoadDemoClass
--------------------------------------
return value of getSimpleName() method: LoadDemoClass
--------------------------------------
return value of getClassLoader() method: sun.misc.Launcher$AppClassLoader@73d16e93
--------------------------------------
return value of getSystemClassLoader() method: sun.misc.Launcher$AppClassLoader@73d16e93
--------------------------------------
return value of loadClass() method: class com.ishaan.jdbc.LoadDemoClass
#########################################
return value of forName() method: class java.util.ArrayList
--------------------------------------
return value of getName() method: java.util.ArrayList
--------------------------------------
return value of getSimpleName() method: ArrayList
--------------------------------------
return value of getClassLoader() method: null
--------------------------------------
return value of getSystemClassLoader() method: sun.misc.Launcher$AppClassLoader@73d16e93
--------------------------------------
return value of loadClass() method: class java.util.ArrayList
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
return value of forName() method: class java.lang.Thread
--------------------------------------
return value of getName() method: java.lang.Thread
--------------------------------------
return value of getSimpleName() method: Thread
--------------------------------------
return value of getClassLoader() method: null
--------------------------------------
return value of getSystemClassLoader() method: sun.misc.Launcher$AppClassLoader@73d16e93
--------------------------------------
return value of loadClass() method: class java.lang.Thread


Can we override static method in java?

No ! we cannot override the static methods. Since static method belongs to class level not object level.

class StaticExe1 {
public static void run() {
System.out.println("run of StaticExe1");
}
public  void fly() {
System.out.println("fly of non-static Exe1");
}
}

class StaticExe2 extends StaticExe1 {
public static void run() {
System.out.println("run of StaticExe2");
}
public  void fly() {
System.out.println("fly of non-static Exe2");
}
}
class StaticExe3 extends StaticExe2 {
public static void run() {
System.out.println("run of StaticExe3");
}
public  void fly() {
System.out.println("fly of non-static Exe3");
}
}

public class StaticMethod {

public static void main(String[] args) {

StaticExe2 ex = new StaticExe3();
ex.run();
ex.fly();
}


}
Output:
run of StaticExe2

fly of non-static Exe3

Saturday, April 28, 2018

Sort a Map by value !!

Sorting a Map by value in Java:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortMapByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("z", 2);
map.put("q", 0);
map.put("p", 5);
map.put("s", 8);
map.put("o", 0);
map.put("r", 9);
map.put("v", 8);
System.out.println(map);
Set<Entry<String, Integer>> entrySet = map.entrySet();
List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>(entrySet);

Collections.sort(lists, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output:

{p=5, q=0, r=9, s=8, v=8, z=2, o=0}
--------------------
q :: 0
o :: 0
z :: 2
p :: 5
s :: 8
v :: 8
r :: 9

Sort a HashMap by key !!

Sorting a HashMap by key in Java:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortMapByKey {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("z", 1);
map.put("q", 2);
map.put("p", 3);
map.put("s", 4);
map.put("o", 5);
System.out.println(map);
Set<Entry<String, Integer>> entrySet = map.entrySet();
List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>(entrySet);

Collections.sort(lists, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o1.getKey()).compareTo(o2.getKey());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output: 
{p=3, q=2, s=4, z=1, o=5}
--------------------
o :: 5
p :: 3
q :: 2
s :: 4
z :: 1

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...