Tuesday 16 October 2018

                                                         NIO Package Example


//Read Data From File Using Nio
=================================================================================
package govind;

import java.util.List;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

Path path = Paths.get("E:/nio.txt");
try {
byte[] bs = Files.readAllBytes(path);
List<String> strings = Files.readAllLines(path);

System.out.println("Read bytes: \n"+new String(bs));
System.out.println("Read lines: \n"+strings);
} catch (Exception e) {
e.printStackTrace();
}
}
}


===============================================================================================

Write Data into a file using Nio

package govind;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class WriteDataInFileUsingNioPackage {

public static void main(String[] args) {
Path path = Paths.get("e:/datawrite.txt");
try {
String str = "Java is More Interesting Progrmming language";
byte[] bs = str.getBytes();
Path writtenFilePath = Files.write(path, bs,StandardOpenOption.APPEND);
System.out.println("Written content in file:\n"+ new String(Files.readAllBytes(writtenFilePath)));
} catch (Exception e) {
e.printStackTrace();
}

}
}



=====================================================================================

read data from one file and copy to another file in java using Nio



package govind;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileCopyExampleUsingNioPackage {
public static void main(String[] args) {
Path sourcePath = Paths.get("e:/sourcefile.txt");
Path targetPath = Paths.get("e:/targetfile.txt");

try {
Path path = Files.copy(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);//copy with REPLACE_EXISTING option
System.out.println("Target file Path : "+path);
System.out.println("Copied Content : \n"+new String(Files.readAllBytes(path)));
} catch (Exception e) {
e.printStackTrace();
}



}
}

Sunday 14 October 2018

                                             Exception Handling Interview question


What is an exception in java?
In java exception is an object. Exceptions are created when an abnormal situations are arised in our program. Exceptions can be created by JVM or by our application code. All Exception classes are defined in java.lang. In otherwords we can say Exception as run time error.
State some situations where exceptions may arise in java?
1) Accesing an element that does not exist in array.
2) Invalid conversion of number to string and string to number.
(NumberFormatException)
3) Invalid casting of class
(Class cast Exception)
4) Trying to create object for interface or abstract class
(Instantiation Exception)
What is Exception handling in java?
Exception handling is a mechanism what to do when some abnormal situation arises in program. When an exception is raised in program it leads to termination of program when it is not handled properly. The significance of exception handling comes here in order not to terminate a program abruptly and to continue with the rest of program normally. This can be done with help of Exception handling.
What is an error in Java?
Error is the subclass of Throwable class in java. When errors are caused by our program we call that as Exception, but some times exceptions are caused due to some environment issues such as running out of memory. In such cases we can’t handle the exceptions. Exceptions which cannot be recovered are called as errors in java.
Ex : Out of memory issues.
 What are advantages of Exception handling in java?
1) Separating normal code from exception handling code to avoid abnormal termination of program.
2) Categorizing in to different types of Exceptions so that rather than handling all exceptions with Exception root class we can handle with specific exceptions. It is recommended to handle exceptions with specific Exception instead of handling with Exception root class.
3) Call stack mechanism : If a method throws an exception and it is not handled immediately, then that exception is propagated or thrown to the caller of that method. This propagation continues till it finds an appropriate exception handler ,if it finds handler it would be handled otherwise program terminates abruptly.
In how many ways we can do exception handling in java?
We can handle exceptions in either of the two ways :
1) By specifying try catch block where we can catch the exception.
2) Declaring a method with throws clause .
List out five keywords related to Exception handling ?
1) Try
2) Catch
3) throw
4) throws
5) finally
Explain try and catch keywords in java?
In try block we define all exception causing code. In java try and catch forms a unit. A catch block catches the exception thrown by preceding try block. Catch block cannot catch an exception thrown by another try block. If there is no exception causing code in our program or exception is not raised in our code jvm ignores the try catch block.
Syntax :
try{ }
Catch(Exception e) { }
Can we have try block without catch block?
Each try block requires at least one catch block or finally block. A try block without catch or finally will result in compiler error. We can skip either of catch or finally block but not both.
Can we have multiple catch block for a try block?
In some cases our code may throw more than one exception. In such case we can specify two or more catch clauses, each catch handling different type of exception. When an exception is thrown jvm checks each catch statement in order and the first one which matches the type of exception is execution and remaining catch blocks are skipped.
Try with multiple catch blocks is highly recommended in java.
If try with multiple catch blocks are present the order of catch blocks is very important and the order should be from child to parent.
Explain importance of finally block in java?
Finally block is used for cleaning up of resources such as closing connections, sockets etc. if try block executes with no exceptions then finally is called after try block without executing catch block. If there is exception thrown in try block finally block executes immediately after catch block.
If an exception is thrown,finally block will be executed even if the no catch block handles the exception.
Can we have any code between try and catch blocks?
We shouldn’t declare any code between try and catch block. Catch block should immediately start after try block.
try{
//code
}
System.out.println(“one line of code”); // illegal
catch(Exception e){//}
Can we have any code between try and finally blocks?
We shouldn’t declare any code between try and finally block. finally block should immediately start after catch block.Ifthere is no catch block it should immediately start after try block.
try{
//code
}
System.out.println(“one line of code”); // illegal
finally{//}
Can we catch more than one exception in single catch block?
From Java 7, we can catch more than one exception with single catch block. This type of handling reduces the code duplication.
Note : When we catch more than one exception in single catch block , catch parameter is implicity final.
We cannot assign any value to catch parameter.
Ex : catch(ArrayIndexOutOfBoundsException || ArithmeticException e)
{}
In the above example e is final we cannot assign any value or modify e in catch statement.
What are checked Exceptions?
1) All the subclasses of Throwable class except error,Runtime Exception and its subclasses are checked exceptions.
2) Checked exception should be thrown with keyword throws or should be provided try catch block, else the program would not compile. We do get compilation error.
Examples :
1) IOException,
2) SQlException,
3) FileNotFoundException,
4) InvocationTargetException,
5) CloneNotSupportedException
6) ClassNotFoundException
7) InstantiationException
What are unchecked exceptions in java?
All subclasses of RuntimeException are called unchecked exceptions. These are unchecked exceptions because compiler does not checks if a method handles or throws exceptions.
Program compiles even if we do not catch the exception or throws the exception.
If an exception occurs in the program,program terminates . It is difficult to handle these exceptions because there may be many places causing exceptions.
Example : 1) Arithmetic Exception
3) ArrayIndexOutOfBoundsException
4) ClassCastException
5) IndexOutOfBoundException
6) NullPointerException
7) NumberFormatException
8) StringIndexOutOfBounds
9) UnsupportedOperationException
Explain differences between checked and Unchecked exceptions in java?


What is default Exception handling in java?
When JVM detects exception causing code, it constructs a new exception handling object by including the following information.
1) Name of Exception
2) Description about the Exception
3) Location of Exception.
After creation of object by JVM it checks whether there is exception handling code or not. If there is exception handling code then exception handles and continues the program. If there is no exception handling code JVM give the responsibility of exception handling to default handler and terminates abruptly.
Default Exception handler displays description of exception,prints the stacktrace and location of exception and terminates the program.
Note : The main disadvantage of this default exception handling is program terminates abruptly.
Explain throw keyword in java?
Generally JVM throws the exception and we handle the exceptions by using try catch block. But there are situations where we have to throw userdefined exceptions or runtime exceptions. In such case we use throw keyword to throw exception explicitly.
Syntax : throw throwableInstance;
Throwable instance must be of type throwable or any of its subclasses.
After the throw statement execution stops and subsequent statements are not executed. Once exception object is thrown JVM checks is there any catch block to handle the exception. If not then the next catch statement till it finds the appropriate handler. If appropriate handler is not found ,then default exception handler halts the program and prints the description and location of exception.
In general we use throw keyword for throwing userdefined or customized exception.
Can we write any code after throw statement?
After throw statement jvm stop execution and subsequent statements are not executed. If we try to write any statement after throw we do get compile time error saying unreachable code.
Explain importance of throws keyword in java?
Throws statement is used at the end of method signature to indicate that an exception of a given type may be thrown from the method.
The main purpose of throws keyword is to delegate responsibility of exception handling to the caller methods, in the case of checked exception.
In the case of unchecked exceptions, it is not required to use throws keyword.
We can use throws keyword only for throwable types otherwise compile time error saying incompatible types.
An error is unchecked , it is not required to handle by try catch or by throws.
Syntax : Class Test{
Public static void main(String args[]) throws IE
{ }
}
Note : The method should throw only checked exceptions and subclasses of checked exceptions.
It is not recommended to specify exception superclasses in the throws class when the actual exceptions thrown in the method are instances of their subclass.
Explain the importance of finally over return statement?
finally block is more important than return statement when both are present in a program. For example if there is any return statement present inside try or catch block , and finally block is also present first finally statement will be executed and then return statement will be considered.
Explain a situation where finally block will not be executed?
Finally block will not be executed whenever jvm shutdowns. If we use system.exit(0) in try statement finally block if present will not be executed.
Can we use catch statement for checked exceptions?
If there is no chance of raising an exception in our code then we can’t declare catch block for handling checked exceptions .This raises compile time error if we try to handle checked exceptions when there is no possibility of causing exception.
What are user defined exceptions?
To create customized error messages we use userdefined exceptions. We can create user defined exceptions as checked or unchecked exceptions.
We can create user defined exceptions that extend Exception class or subclasses of checked exceptions so that userdefined exception becomes checked.
Userdefined exceptions can extend RuntimeException to create userdefined unchecked exceptions.
Note : It is recommended to keep our customized exception class as unchecked,i.e we need to extend Runtime Exception class but not Excpetion class.
Can we rethrow the same exception from catch handler?
Yes we can rethrow the same exception from our catch handler. If we want to rethrow checked exception from a catch block we need to declare that exception.
Can we nested try statements in java?
Yes try statements can be nested. We can declare try statements inside the block of another try
statement.
Explain the importance of throwable class and its methods?
Throwable class is the root class for Exceptions. All exceptions are derived from this throwable class. The two main subclasses of Throwable are Exception and Error. The three methods defined in throwable class are :
1) void printStackTrace() :
This prints the exception information in the following format :
Name of the exception, description followed by stack trace.
2) getMessage()
This method prints only the description of Exception.
3) toString():
It prints the name and description of Exception.
Explain when ClassNotFoundException will be raised ?
When JVM tries to load a class by its string name, and couldn’t able to find the class
classNotFoundException will be thrown. An example for this exception is when class name is misspelled and when we try to load the class by string name hence class cannot be found which raises ClassNotFoundException.
Explain when NoClassDefFoundError will be raised ?
This error is thrown when JVM tries to load the class but no definition for that class is found
NoClassDefFoundError will occur. The class may exist at compile time but unable to find at runtime. This might be due to misspelled classname at command line, or classpath is not specified properly , or the class file with byte code is no longer available.

Saturday 13 October 2018





How to convert int to String in java?

package govind;

public class StringToIntConversion
{
public static void main(String[] args) {
int x=100;
String s1 = String.valueOf(x);
System.out.println(s1);//Now it will return "100"
System.out.println(x+400);//500 because + is binary plus operator
System.out.println(s1+400);//100400 because + is string concatenation operator
int y=200;
String s2 = Integer.toString(y);
System.out.println(s2);//"200"
System.out.println(s2+400);//200400 because + is string concatenation operator
int z=300;
String s3 = String.format("%d", z);
System.out.println(s3);//"300"
System.out.println(s3+400);//300400 because + is string concatenation operator
}
}


//op:----------------------------

100
500
100400
200
200400
300
300400

Tuesday 9 October 2018

        Spring jdbc template (curd operation ) example in java

=======================================================================

//Employee.java

package govind.icjs.curd;

public class Employee {

private Integer id;
private String empName;
private String empAddress;
private String empEmail;
private String empDesignation;
private Float empSalary;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public String getEmpEmail() {
return empEmail;
}
public void setEmpEmail(String empEmail) {
this.empEmail = empEmail;
}
public String getEmpDesignation() {
return empDesignation;
}
public void setEmpDesignation(String empDesignation) {
this.empDesignation = empDesignation;
}
public Float getEmpSalary() {
return empSalary;
}
public void setEmpSalary(Float empSalary) {
this.empSalary = empSalary;
}



}


=================================================================================================================================
package govind.icjs.curd;
// EmployeeDao.java
import java.util.List;

import javax.sql.DataSource;

public interface EmployeeDao {


   public void setDataSource(DataSource ds);

   public void insertData(Integer id,String empName,String empAddress,String empEmail,String empDesignation,Float empSalary);

   public Employee getEmployee(Integer id);
 
   public List<Employee> getAllEmployee();
 
   public void delete(Integer id);
 
   public int update(Integer id,String emp_name,String emp_address);

}


=======================================================================================================================================
//EmployeeDaoImpl.java
============================================
package govind.icjs.curd;


import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;


public class EmployeeDaoImpl implements EmployeeDao {

private DataSource datasource;
private JdbcTemplate jdbcTemplate;

@Override
public void setDataSource(DataSource datasource) {
this.datasource=datasource;
this.jdbcTemplate=new JdbcTemplate(datasource);

}
    @Override
public void insertData(Integer id, String empName, String empAddress, String empEmail, String empDesignation,
Float empSalary) {
String sql="insert into emp_jdbctemplate(id,emp_name,emp_address,emp_email,emp_designation,emp_salary)values(?,?,?,?,?,?)";
jdbcTemplate.update(sql,new Object[]{id,empName,empAddress,empEmail,empDesignation,empSalary});
    System.out.println("Insert Data Successfully");
}

@Override
public Employee getEmployee(Integer id) {
String sql="select * from emp_jdbctemplate where id=?";
Employee emp = jdbcTemplate.queryForObject(sql, new Object[]{id},new EmployeeMapper());
return emp;

   
   
}

@Override
public List<Employee> getAllEmployee() {

String sql="select * from emp_jdbctemplate";
List<Employee> emp = jdbcTemplate.query(sql, new EmployeeMapper());
return emp;


}

@Override
public void delete(Integer id) {
String sql="delete from emp_jdbctemplate where id="+id+" ";
jdbcTemplate.update(sql);
System.out.println("Delete Data Successfully and id="+id);

}
 
@Override
public int update(Integer id,String emp_name,String emp_address)
    {
String sql="update emp_jdbctemplate set emp_name=?,emp_address=? where id=?";
    return jdbcTemplate.update(sql,new Object[]{emp_name,emp_address,id});
}
}


==============================================================================================================================================
//EmployeeMapper.java
======================================
package govind.icjs.curd;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;


public class EmployeeMapper implements RowMapper<Employee>{

public Employee mapRow(ResultSet rs, int rownum) throws SQLException {
    Employee e=new Employee();
e.setId(rs.getInt("id"));
e.setEmpName(rs.getString("emp_name"));
e.setEmpAddress(rs.getString("emp_address"));
e.setEmpEmail(rs.getString("emp_email"));
e.setEmpDesignation(rs.getString("emp_designation"));
e.setEmpSalary(rs.getFloat("emp_salary"));
return e;

}


}


===========================================================================================================================================
// EmployeeMain.java
=============================
package govind.icjs.curd;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeMain {

public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
    EmployeeDaoImpl edi = (EmployeeDaoImpl)ac.getBean("edaoimpl");

     System.out.println("-------------------Insert Data-----------------");
    edi.insertData(111,"sanjay", "ashoknagar", "sanjay@gmail.com","employee", 30000.00f);

    System.out.println("-------------------Delete Data-------------------");
        edi.delete(103);
     
       System.out.println("------------------Update Data----------------------");
    int status=edi.update(101, "harsh", "munirka");
    if(status>0)
{
System.out.println("-------Update data successfully-----");
}

else
{
System.out.println("---------Updated not Successfully------");
}
 
 
   Employee emp = edi.getEmployee(106);
   System.out.println(emp.getEmpName()+" "+emp.getEmpAddress()+" "+emp.getEmpEmail()+" "+emp.getEmpDesignation()+" "+emp.getEmpSalary());
   System.out.println("-----------------Data Retrieve successfully based on id----------");



    System.out.println("---------------------Retrieve all data------------------");
    List<Employee> l = edi.getAllEmployee();
    for(Employee e1:l)
    {
    System.out.println(e1.getId()+" "+e1.getEmpName()+" "+e1.getEmpAddress()+" "+e1.getEmpDesignation()+" "+e1.getEmpSalary());
    }
    System.out.println("------------Retrieve all data successfully--------------");



}

}


===========================================================================================================================================
applicationContext.xml
================================
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/govind" />
<property name="username" value="postgres" />
<property name="password" value="postgres" />
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"></property>
</bean>
<bean id = "edaoimpl"
      class = "govind.icjs.curd.EmployeeDaoImpl">
      <property name = "dataSource" ref ="datasource" /> 
   </bean>
</beans>



  =======================================================================================================================================

required jar files
=====================
commons-logging-1.1.2.jar
org.springframework.beans.jar
org.springframework.context.jar
postgresql-9.4-1200-jdbc41.jar
spring-core-3.2.3.release.jar
spring-dao-2.0.6.jar
spring-jdbc-3.2.4.release.jar

Database Structure
========================================================================





Sunday 7 October 2018


                                      Comparable And Comparator Concept in java?




Comparable and Comparator in Java are very useful for sorting collection of objects. Java provides some inbuilt methods to sort primitive types array or Wrapper classes array or list. Here we will first learn how we can sort an array/list of primitive types and wrapper classes and then we will use java.lang.Comparableand java.util.Comparator interfaces to sort array/list of custom classes.


ava provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj) method which is used by sorting methods, you can check any Wrapper, String or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.


But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Java Comparator interface because Comparable.compareTo(Object o)method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.

Java Comparator

Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.





package govind;

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Integer> al=new ArrayList<>();
al.add(10);
al.add(4);
al.add(6);
al.add(3);
al.add(50);
System.out.println("before sorting");
for(int i:al)//autoboxing
{
System.out.println(i);
}

System.out.println("after sorting");
Collections.sort(al);
for(int i:al)//autoboxing
{
System.out.println(i);
}

}



}


o/p:------------------------------------------------

before sorting
10
4
6
3
50
after sorting
3
4
6
10
50


==========================================================================================================================================

package govind;

public class Product {

String pname;
int price;
public Product(String pname,int price) {
super();
this.pname = pname;
this.price = price;
}
@Override
public String toString() {
return "Product [pname=" + pname + ", price=" + price + "]";
}




}



package govind;

import java.util.ArrayList;
import java.util.Collections;

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

ArrayList<Product> productList=new ArrayList<>();
productList.add(new Product("laptop", 45000));
productList.add(new Product("Desktop", 25000));
productList.add(new Product("T.v", 15000));
productList.add(new Product("Mobile", 10000));
productList.add(new Product("Jeans", 1500));
productList.add(new Product("Shirt", 1000));
System.out.println(productList);
//Collections.sort(productList);//error





}

}



o/p:-----------------------


compile time error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Product>)

at govind.ProductList.main(ProductList.java:17)
=========================================================================================================================================

Comparable Concept:-------


package govind;

public class ProductComparable implements Comparable<ProductComparable> {

private String pname;
private int Price;
public ProductComparable(String pname, int price) {
super();
this.pname = pname;
Price = price;
}

@Override
public String toString() {
return "ProductComparable [pname=" + pname + ", Price=" + Price + "]";
}



   // if u want to sort on the basis of price
   //@Override
public int compareTo(ProductComparable pricecompare) {
if(Price>pricecompare.Price)
{
return 1;
    }
else if(Price<pricecompare.Price)
{
return -1;
}
else
{
return 0;
}

}



/*if u want to sort on the basis of pname:

@Override
public int compareTo(ProductComparable productName) {

return pname.compareTo(productName.pname);
}*/



}




package govind;

import java.util.ArrayList;
import java.util.Collections;

public class ProductComparableMain {

public static void main(String[] args) {
ArrayList<ProductComparable> productList=new ArrayList<>();
productList.add(new ProductComparable("Laptop", 45000));
productList.add(new ProductComparable("Desktop", 25000));
productList.add(new ProductComparable("T.v", 15000));
productList.add(new ProductComparable("Mobile", 10000));
productList.add(new ProductComparable("Jeans", 1500));
productList.add(new ProductComparable("Shirt", 1000));
System.out.println("Before Sorting");
System.out.println(productList);
System.out.println("After Sorting on the basis of price");
Collections.sort(productList);
System.out.println(productList);
}

}



o/p:-----------------------------------

Before Sorting
[ProductComparable [pname=Laptop, Price=45000], ProductComparable [pname=Desktop, Price=25000], ProductComparable [pname=T.v, Price=15000], ProductComparable [pname=Mobile, Price=10000], ProductComparable [pname=Jeans, Price=1500], ProductComparable [pname=Shirt, Price=1000]]
After Sorting on the basis of price
[ProductComparable [pname=Shirt, Price=1000], ProductComparable [pname=Jeans, Price=1500], ProductComparable [pname=Mobile, Price=10000], ProductComparable [pname=T.v, Price=15000], ProductComparable [pname=Desktop, Price=25000], ProductComparable [pname=Laptop, Price=45000]]



=============================================================================================================================================


Comparator Concept in java:--------------------

package govind;

public class Product {

String pname;
int price;
public Product(String pname,int price) {
super();
this.pname = pname;
this.price = price;
}
@Override
public String toString() {
return "Product [pname=" + pname + ", price=" + price + "]";
}




}




package govind;

import java.util.Comparator;

public class ProductNameComparator implements Comparator<Product>{

@Override
public int compare(Product p1, Product p2) {
return p1.pname.compareTo(p2.pname);
}





}



package govind;

import java.util.Comparator;

public class ProductPriceComparator  implements Comparator<Product>{

@Override
public int compare(Product p1, Product p2) {

return p1.price-p2.price;
}

}



package govind;

import java.util.ArrayList;
import java.util.Collections;

public class ProductListComparator {


public static void main(String[] args) {

ArrayList<Product> productList=new ArrayList<>();
productList.add(new Product("laptop", 45000));
productList.add(new Product("Desktop", 25000));
productList.add(new Product("T.v", 15000));
productList.add(new Product("Mobile", 10000));
productList.add(new Product("Jeans", 1500));
productList.add(new Product("Shirt", 1000));
System.out.println("************ Sorting on the basis of product name****************");
System.out.println("before sorting");
System.out.println(productList);
System.out.println("after sorting");
Collections.sort(productList,new ProductNameComparator());
System.out.println(productList);

System.out.println("************ Sorting on the basis of price****************");
System.out.println("before sorting");
System.out.println(productList);
System.out.println("after sorting");
Collections.sort(productList,new ProductPriceComparator());
System.out.println(productList);
}
}


o/p:----------------------------------------------------------------------------------

************ Sorting on the basis of product name****************
before sorting
[Product [pname=laptop, price=45000], Product [pname=Desktop, price=25000], Product [pname=T.v, price=15000], Product [pname=Mobile, price=10000], Product [pname=Jeans, price=1500], Product [pname=Shirt, price=1000]]
after sorting
[Product [pname=Desktop, price=25000], Product [pname=Jeans, price=1500], Product [pname=Mobile, price=10000], Product [pname=Shirt, price=1000], Product [pname=T.v, price=15000], Product [pname=laptop, price=45000]]
************ Sorting on the basis of price****************
before sorting
[Product [pname=Desktop, price=25000], Product [pname=Jeans, price=1500], Product [pname=Mobile, price=10000], Product [pname=Shirt, price=1000], Product [pname=T.v, price=15000], Product [pname=laptop, price=45000]]
after sorting
[Product [pname=Shirt, price=1000], Product [pname=Jeans, price=1500], Product [pname=Mobile, price=10000], Product [pname=T.v, price=15000], Product [pname=Desktop, price=25000], Product [pname=laptop, price=45000]]


                                                     JAVA-SCRIPT OBJECT 


<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object.</p>

<p id="demo"></p>

<script>
var employee = {
    firstName : "govind",
    middleName : "ballabh",
    lastName  : "khan",
    age       : 27,
    salary : 10000.00,
    empId:"0105OIST"
};

//Adding New Properties
employee.nationality="english";

//deleting properties
delete employee.age;

document.getElementById("demo").innerHTML = "Full Name="+
employee.firstName + " "+employee.middleName+" "+employee.lastName+" " +"and salary="+employee.salary+" "+"Nationality="+employee.nationality+" "+ "+Age= "+employee.age
</script>

</body>
</html>

o/p:-----------------------------------------------
Creating a JavaScript Object.
Full Name=govind ballabh khan and salary=10000 Nationality=english +Age= undefined

=======================================================================================================================================================================

<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object with new keyword</p>

<p id="demo"></p>

<script>
var employee = new Object();
    employee.firstName = "govind";
    employee.middleName = "ballabh";
    employee.lastName  = "khan";
    employee.age = 27;
    employee.salary = 10000.00;
    employee.empId ="0105OIST";

    var t=employee;//java script objects are mutable
    employee.age=26;

   
document.getElementById("demo").innerHTML = "Full Name="+
employee.firstName +" "+employee.middleName+" "+employee.lastName+" " +"and age="+employee.age;//access the propery of object ist way

/*
document.getElementById("demo").innerHTML = "Full Name="+
employee.firstName +" "+employee.middleName+" "+employee.lastName+" " +"and EmployeeId="+employee["empId"]; ////access the propery of object 2nd way */



</script>
</body>
</html>

o/p:-------------------------------------
Creating a JavaScript Object with new keyword
Full Name=govind ballabh khan and age=26

============================================================================================================================================

<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object and function</p>

<p id="demo"></p>

<script>
var employee = {
    firstName : "govind",
    middleName : "ballabh",
    lastName  : "khan",
    age       : 27,
    salary : 10000.00,
    empId:"0105OIST",
   
    fullName : function ()
    {
    return this.firstName+" "+this.middleName+" "+this.lastName;
    }

 

};


//Adding a Method to an Object
/*employee.name = function() {
    return this.firstName + " "+" "+this.middleName+" " + this.lastName;
};*/

document.getElementById("demo").innerHTML = employee.fullName();


/*document.getElementById("demo").innerHTML ="the employee name is "+ employee.name();*/


/*document.getElementById("demo").innerHTML = employee.fullName;//it will return function definition */
</script>

</body>
</html>

o/p:---------------------------------------------------

Creating a JavaScript Object and method
govind ballabh khan

=========================================================================================================================================

<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object and used for in loop </p>

<p id="demo"></p>

<script>

var employee = new Object();
    employee.firstName = "govind";
    employee.middleName = "ballabh";
    employee.lastName  = "khan";
    employee.age = 27;
    employee.salary = 10000.00;
    employee.empId ="0105OIST";

    var txt=" ";
    var x;
   
    for(x in employee)
    {
    txt=txt+employee[x]+" "+"<br>";
    }


document.getElementById("demo").innerHTML = txt;

</script>
</body>
</html>



o/p:------------------------------------------------

Creating a JavaScript Object and used for in loop
govind
ballabh
khan
27
10000
0105OIST

==========================================================================================================================================

<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object with new keyword</p>

<p id="demo"></p>

<script>
var employee = {
    firstName : "govind",
    middleName : "ballabh",
    lastName  : "khan",
    age       : 27,
    salary : 10000.00,
    empId:"0105OIST",
     get employeeId()
     {
      return this.empId;

      //return this.empId.toLowerCase();
     }
     };

   
   
document.getElementById("demo").innerHTML = employee.employeeId;




</script>
</body>
</html>


o/p:---------------------------------------------
Creating a JavaScript Object with get method concept
0105OIST

===========================================================================================================================================


<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object and setter method</p>

<p id="demo"></p>

<script>
var employee = {
    firstName : "govind",
    middleName : "ballabh",
    lastName  : "khan",
    age       : 27,
    salary : 10000.00,
    empId:"0105OIST",
     set sal(value)
     {
       this.salary=value;
     }
     };
 
   employee.sal=11000.00;


   
   
document.getElementById("demo").innerHTML = employee.salary;




</script>
</body>
</html>


o/p:-----------------------------------------------------------

Creating a JavaScript Object and setter method
11000

========================================================================================================================================

<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript constructor</p>

<p id="demo"></p>

<script>

function employee(first,middle,last,age,sal,id)
{

this.firstName=first;
this.middleName=middle;
this.lastName=last;
this.age=age;
this.salary=sal;
this.empId=id;
}

//create a employee object

var employeeFirst= new employee("govind","ballabh","khan",27,10000.00,"0105OIST");

var employeeSecond= new employee("sanjeet","shankar","jha",25,15000.00,"0106OIST");
   
   
document.getElementById("demo").innerHTML = "employeeFirst salary is="+employeeFirst.salary+" employeeSecond salary="+employeeSecond.salary;




</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>

<p>You cannot add a new property to a constructor function if u want to add then prototype concept used </p>

<p id="demo"></p>

<script>

function employee(first,middle,last,age,sal,id)
{

this.firstName=first;
this.middleName=middle;
this.lastName=last;
this.age=age;
this.salary=sal;
this.empId=id;
}

//create a employee object

//employee.nationality="english";
employee.prototype.nationality = "English";

var employeeFirst= new employee("govind","ballabh","khan",27,10000.00,"0105OIST");

var employeeSecond= new employee("sanjeet","shankar","jha",25,15000.00,"0106OIST");
   
   
document.getElementById("demo").innerHTML = "employeeFirst salary is="+employeeFirst.salary+" employeeSecond salary="+employeeSecond.salary+" "+"employee nationality ="+employeeFirst.nationality;




</script>
</body>
</html>



o/p:----------------------

You cannot add a new property to a constructor function if u want to add then prototype concept used
employeeFirst salary is=10000 employeeSecond salary=15000 employee nationality =English