Showing posts with label Java Tutorial. Show all posts
Showing posts with label Java Tutorial. Show all posts

Wednesday, 13 May 2020

Lambda Expression in JAVA



-> The Lambda expression is used to provide the implementation of an interface which has functional interface.

->  It saves a lot of code.

-> In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.

-> Java lambda expression is treated as a function, so compiler does not create .class file.



Functional Interface

-> Lambda expression provides implementation of functional interface.

-> An interface which has only one abstract method is called functional interface.

-> Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.


Syntax

(argument-list) -> {body}


Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.



Example :  Addition of two numbers using lamda expression

@FunctionalInterface
interface Calc{

   int add(int n1,int n2);

}




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

     
       Calc addition=(n1,n2)->{

          return n1+n2;
       };
   
 
       System.out.println("Addition "+addition.add(10,20)); 


       
 }


}


Output

Addition 30

Comparator Interface in java


-> Comparator used to sorting the object element by using multiple sorting sequence.

-> We can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.

-> The comparator interface provide two methods like compare(Object obj1,Object obj2) and equals(Object obj).



1) compare(Object obj1,Object obj2) function

Its compares first object(obj1) and second object(obj2) and return int value

Syntax : public int compare(Object obj1,Object obj2)


positive integer = if the current object is greater than the specified object.
negative integer = if the current object is less than the specified object.
zero = if the current object is equal to the specified object.



2) equals(Object obj1) function

Its used to compare current object with specified object

Syntax : public boolean equals(Object obj1)




Example : Sorting by name and Emp id by using comparator

import java.util.*; 
import java.io.*;

// User - Defined Class

class Employee { 
int empid; 
String empname; 
int empage; 
Employee(int empid,String empname,int empage){ 
this.empid=empid; 
this.empname=empname; 
this.empage=empage; 

}


class sortByAge implements Comparator{
                         
public int compare(Object o1,Object o2){ 
Employee s1=(Employee)o1; 
Employee s2=(Employee)o2; 

if(s1.empage==s2.empage) 
return 0; 
else if(s1.empage>s2.empage) 
return 1; 
else 
return -1; 

   
}
 

class sortByName implements Comperator{
   
public int compare(Object o1,Object o2){ 
Employee s1=(Employee)o1; 
Employee s2=(Employee)o2; 

return s1.empname.compareTo(s2.empname);
   
}   
}


// Main Class



public class TestSort1{ 
public static void main(String args[]){ 
ArrayList<Employee> al=new ArrayList<Employee>(); 
al.add(new Employee(1,"Ajith",23)); 
al.add(new Employee(6,"Vijay",27)); 
al.add(new Employee(4,"Surya",21)); 
 
 
System.out.println("Sorting By Age"); 
Collections.sort(al, new sortByAge()); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 
}


System.out.println("Sorting By Name");
Collections.sort(al, new sortByName()); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 






Output

Sorting By Age

4 Surya 21
1 Ajith 23
6 Vijay 27


Sorting By Name

1 Ajith 23
4 Surya 21
6 Vijay 27

Comparable interface in java



-> Comparable is an interface of comparing the objects with other objects os the same type. This is also called "natural ordering"

-> by using compare interface, we can sort the elements based on single data member only.

-> It provides single method name as compareTo(object) and provides single sorting sequence only.

-> The interface found in java.lang.package


compareTo(Object obj) method

The method used to compare the current object with specified object. Please find the below return values

positive integer = if the current object is greater than the specified object.
negative integer = if the current object is less than the specified object.
zero = if the current object is equal to the specified object.



Example 1: Sort by Integer Value (Ascending Order) by using Comparable

import java.util.*; 

// User - Defined Class

class Employee implements Comparable<Employee>{ 
int empid; 
String empname; 
int empage; 
Employee(int empid,String empname,int empage){ 
this.empid=empid; 
this.empname=empname; 
this.empage=empage; 

 
public int compareTo(Employee st){ 
if(empage==st.empage) 
return 0; 
else if(empage>st.empage) 
return 1; 
else 
return -1; 

}



// Main Class



public class TestSort1{ 
public static void main(String args[]){ 
ArrayList<Employee> al=new ArrayList<Employee>(); 
al.add(new Employee(1,"Ajith",23)); 
al.add(new Employee(6,"Vijay",27)); 
al.add(new Employee(4,"Surya",21)); 
 
Collections.sort(al); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 







Output

4 Surya 21
1 Ajith 23
6 Vijay 27


********************************************************


Example 2: Sort by Integer Value (Decending Order) by using Comparable


import java.util.*; 

// User - Defined Class

class Employee implements Comparable<Employee>{ 
int empid; 
String empname; 
int empage; 
Employee(int empid,String empname,int empage){ 
this.empid=empid; 
this.empname=empname; 
this.empage=empage; 

 
public int compareTo(Employee st){ 
if(empage==st.empage) 
return 0; 
else if(empage<st.empage) 
return 1; 
else 
return -1; 

}



// Main Class



public class TestSort1{ 
public static void main(String args[]){ 
ArrayList<Employee> al=new ArrayList<Employee>(); 
al.add(new Employee(1,"Ajith",23)); 
al.add(new Employee(6,"Vijay",27)); 
al.add(new Employee(4,"Surya",21)); 
 
Collections.sort(al); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 







Output


6 Vijay 27
1 Ajith 23
4 Surya 21


Monday, 30 March 2020

Difference between String, String Builder and String Buffer

Immutable : Cannot change value
Mutable : Can change the Value


String :

 String is Immutable.
 If we update any existing String then it will create String object. It won't override existing value.

Ex : 
String S1="Testing"
print (S1)

String concat(String s1){
S1 = S1+"Java"
}

O/P

S1: Testing


String Builder

String Builder is mutable.
we can change value. if any thing update then it will override existing object itself.

Ex : 
StringBuilder S1="Testing"
print (S1)

String concat(String s1){
S1 = S1.append("Java")
}

O/P

S1: Testing Java


String Buffer

Both String Buffer and String builder same. Except one concept.
String Buffer is thread safe. we can refer the String buffer object via multi thread.

String Buffer is mutable. we can change value. if any thing update then it will override existing object itself.

Ex : 
StringBuffer S1="Testing"
print (S1)

String concat(String s1){
S1 = S1.append("Java")
}

O/P

S1 : Testing Java





When to use

String : if String object value contant entire program.
String Builder : If String object value need to change at any time.
String Buffer : If String object value need to change at any time. It can be access same value via multithread.

Tuesday, 6 December 2016

How to convert Java source file to Jar and working with function inside java file.




Type of JAR file

1) Executable JAR
2) Non-Executable JAR


Follow the below steps for convert JAVA source file to Non-Executable JAR file.
------------------------------------------------------------------------------

1) Create java file by using below code


public class SampleCode{



// create new Excel sheet in workbook

public static void createExcelSheet(Workbook wb, String SheetName, String ExcelPath) throws IOException
{
wb.createSheet(SheetName);
FileOutputStream output_file =new FileOutputStream(new File(ExcelPath));
wb.write(output_file);
output_file.flush();
output_file.close();

}


// verify Excel version

public static Workbook verifyExcelVersion(String FilePath) throws FileNotFoundException, IOException
{
Workbook book1=null;
String fileExtn=FilenameUtils.getExtension(FilePath);

if(fileExtn.equals("xls"))
book1=new HSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsx"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsm"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
return book1;
}




}


2) Save above source file under one package.
Example (Package) -> SampleCode.java

3) Right on  Example (Package) -> Export -> Java -> JAR file -> Click Next

4) In JAR File Specification Window

i)   verify expected Package selected or not.
ii)  select "Export Generated class files and resources".
iii) select "compress the contents of the JAR file".
iv)  provide the path in "Select the export destination"
v)   click Next.

5) In JAR Packaging Options window

i) select "Export class files with compile Errors"
ii) Select "Export class files with compile warnings"
ii) Select "Save the descriptions of this JAR in workspace"
iv) provide the path in "Description file".
v)  click Next

6) In JAR Manifest Specification window

i)   click "Generate the Manifest file".
ii)  click "seal some packages".
iii) click finish

7) Once we cick finsh two files withh get genrated in mentioned path

i) FileName.jar
ii) FileName.jardesc

8) The above JAR is ready to some other project to use existion code. This JAR is called Non Executable JAR file.




How to use and execute function with in JAR file to another package.
-------------------------------------------------------------------

1) create the project

2) Add FileName.jar file in to configure Build path.

3) Then we can use existing functions which available in FileName.jar file.



public static void main(String agrs[])
{

SampleCode obj1=new SampleCode();
Workbook book2=obj1.verifyExcelVersion(ToFilePath);
Sheet sheet2=null;


obj1.createExcelSheet(wb,"Sheet2",Download_FilePath);

}

4) By using above method we can use functions which available in FileName.jar file.

How to get Hashmap key and Hashmap value





By using below below code we can get Hashmap key and Hashmap value


Map,.




for (Map.Entry<String,String> entry : map1.entrySet()) {

System.out.println("HashMap key="+entry.getKey());
System.out.println("HashMap value="+entry.getValue());

}


How to change font color in Excel Sheet by using Apache POI




By using below code we can change the font color in Apache POI



private static void updateColor(String FilePath,int row,int col,String Sheet, String color1) throws FileNotFoundException, IOException {

Workbook book2=verifyExcelVersion(FilePath);
Sheet sheet2=book2.getSheet(Sheet);

// update Font with colors

CellStyle style=book2.createCellStyle();
Font font=book2.createFont();

if(color1.equals("RED"))
font.setColor(IndexedColors.RED.getIndex());
if(color1.equals("GREEN"))
font.setColor(IndexedColors.GREEN.getIndex());
if(color1.equals("BLUE"))
font.setColor(IndexedColors.BLUE.getIndex());

style.setFont(font);


    sheet2.getRow(row).getCell((short) col).setCellStyle(style);
   
     FileOutputStream output_file =new FileOutputStream(new File(FilePath));
     book2.write(output_file);
     output_file.flush();
     output_file.close();
     sheet2=null;
     book2=null;


}

How to display message box in java




We can display the message box during the selenium automation by using Java Swing


public static void main(String args[])
{
msgbox("The verification part is done. We can procced with update the timesheets");
}

private static void msgbox(String string) {
JOptionPane.showMessageDialog(null, string);

}

Saturday, 4 June 2016

how to break out of nested loops java



break;

By using break we can come out from single loop.

But if we want to come out from all nested loop then we shoule use lables for acheiving this concept.



Example:

int points = 0;
int goal = 100;
someLabel:
while (goal <= 100) {
   for (int i = 0; i < goal; i++) {
      if (points > 50) {
         break someLabel;
      }
   points += i;
   }
}
// you are going here after break someLabel;

Saturday, 23 January 2016

Getting Error Message : java.lang.IllegalStateException: Cannot get a text value from a numeric formula cell



Reason :
If we read string value from Formula cell then we are getting this exception.


Solution:

Use string value in cell.

Getting Error Message : java.lang.IllegalStateException: Cannot get a text value from a numeric cell



Reason:

If we read string value from integer cell then we are getting this exception.






Solution :



Use String data in Excel

Or

Add (') in front of integer then its considered as string while reading the data from cell.



Getting Config Build Path Error in Eclipse indigo (Java 8)




We are getting the below two error while configure the build path

1) The project was not built since its build path is incomplete. Cannot find the class file for java.util.Map$Entry. Fix the build path then try building this project.

2) The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files.



Solution :

Please check the our eclipse version is support the Java 8 or not.

Eclipse Kepler and Luna versions are have in built Java 8 version. So we can use these Eclipse version for Java 8.

How to search the string in perticular excel sheet using Apche POI



    public int findString(String FilePath,String SheetName,String Text) throws IOException
    {
        FileInputStream fsIP= new FileInputStream(new File(FilePath));
        HSSFWorkbook wb = new HSSFWorkbook(fsIP); //Access the workbook
//        HSSFSheet worksheet = wb.getSheet("TestData"); //Access the worksheet, so that we can update / modify it.
        HSSFSheet worksheet = wb.getSheet(SheetName);
       
          for (Row row : worksheet) {
              for (Cell cell : row) {
                  if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                      if (cell.getRichStringCellValue().getString().trim().equals(Text)) {
                          return row.getRowNum();
                       
                      }
                  }
              }
          }
        return 0;
                    
     
    }
   


Note : Please use latest Apache POI for using this code or use Apache poi files which are supports all predefined functions.

Saturday, 2 January 2016

How to set Break point and Debug in Eclipse


Breakpoint in Eclipse/Selenium


Breakpoint
-> By double click on left side, then we create breakpoints.

Conditional Breakpoint
-> Sometime we need breakpoint, if only some Conditions like Errors and exception. For that we can conditional breakpoint.
-> Right click on crated breakpoint -> Breakpoint Properties


*****************************************


Debug in Eclipse/Selenium




    F5 – Step Into
    F6 – Step Over
    F7 – Step Return
    F8 – Run until next breakpoint is reached

Table 1. Debugging key bindings / shortcuts
Key  Description
F5  Executes the currently selected line and goes to the next line in your program. If the selected line is a method call the debugger steps into the associated code.
F6  F6 steps over the call, i.e. it executes a method without stepping into it in the debugger.
F7  F7 steps out to the caller of the currently executed method. This finishes the execution of the current method and returns to the caller of this method.
F8  F8 tells the Eclipse debugger to resume the execution of the program code until is reaches the next breakpoint or watchpoint.

Saturday, 16 May 2015

How to identify eclipse 32 bit or 64 bit installed in our system



Method 1

-> Open the task Manager

-> For 32 bit : Its run as eclipse.exe *32 in task manager

-> For 64 bit : Its run as eclipse.exe in task manager


Method 2

-> Verify eclips.ini file . Configuration Settings file in eclips installed folder.

-> Check the 4rd line,
../../../plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.0.v20100503

-> For 32 bit : Its contains only x86_1

-> For 64 bit : Its contains x86_64_1

Above line from 64 bit

How to identify jdk 32 bit or 64 bit installed our system



Method 1:

-> For 32 bit : jdk or jre installed in below location

C:\Program Files (x86)Java


-> For 64 bit : jdk or jre installed in below location

C:\Program Files\Java




Method 2

-> Open the task Manager

-> For 32 bit : Its run as javaw.exe *32 in task manager

-> For 64 bit : Its run as javaw.exe in task manager

Thursday, 14 August 2014

How to use For Each loop in Java



-> It was introduced in JDK 1.5

-> Its mainly used to traverse the elements from array or collections.

-> The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.


Syntex:

for(data_type variable : array | collection)
{

}


Example :

class ForEachExample1{ 
  public static void main(String args[]){ 
   int arr[]={12,13,14,44}; 
 
   for(int i:arr){ 
     System.out.println(i); 
   } 
 
 }  

     

Output:12
       13
       14
       44

Tuesday, 8 July 2014

How to verify java installed in our system




Use below method to know about java installed or not. Also we know about which version of the java installed in System.

1) Goto command Prompt (Type "cmd" in Run)

2) Type below command in command Prompt

c:\users>java -version

and press enter then we can see the below output to know about the Java information from our system


c:\users>java -version
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)

3) If java not there in our system we should download and installed from below link

http://java.com/en/download/index.jsp


Thursday, 8 May 2014

difference between iterator,Arraylist and list iterator in java


Arraylist :

-> ArrayList is an actual data structure, an implementation of the List interface
-> ArratList is actual list of the object content the value.
-> Its have the method like add(object), remove(object), get(index), etc.


1) boolean add(E e) - This method appends the specified element to the end of this list.

2) void add(int index, E element) - This method inserts the specified element at the specified position in this list.

3) boolean addAll(Collection<? extends E> c) - This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator

4) boolean addAll(int index, Collection<? extends E> c) - This method inserts all of the elements in the specified collection into this list, starting at the specified position.

5) void clear() - This method removes all of the elements from this list.

6) Object clone() - This method returns a shallow copy of this ArrayList instance.

7) boolean contains(Object o) - This method returns true if this list contains the specified element.

8) void ensureCapacity(int minCapacity) - This increases the capacity of this ArrayList.

9) E get(int index) - This method returns the element at the specified position in this list.

10) int indexOf(Object o) - This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

11) boolean isEmpty() - This method returns true if this list contains no elements.

12) int lastIndexOf(Object o) - This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

13) E remove(int index) - This method removes the element at the specified position in this list.

14) boolean remove(Object o) - This method removes the first occurrence of the specified element from this list, if it is present.

15) protected void removeRange(int fromIndex, int toIndex) - This method removes from this list all of the elements whose index is between fromIndex(inclusive) and toIndex(exclusive).

16) E set(int index, E element) - This method replaces the element at the specified position in this list with the specified element.

17) int size() - This method returns the number of elements in this list.

18) Object[] toArray() - This method returns an array containing all of the elements in this list in proper sequence (from first to last element).

19) <T> T[] toArray(T[] a) - This method returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that
of the specified array.

20) void trimToSize() - This method trims the capacity of this ArrayList instance to be the list's current size.




Iterator :

-> Iterator is just an interface that allows you to navigate through any data structure.
-> Iterator is helpful for navigate and access the data.
-> Iterator have the below method
-> Iterator is used for map, set, and list.

1) boolean hasNext( ) - Returns true if there are more elements. Otherwise, returns false.

2) Object next( ) - 1Returns the next element. Throws NoSuchElementException if there is not a next element.

3) void remove( ) - Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).



ListIterator:

-> ListIterator is a subclass which extends Iterator.
-> ListIterator allow bidirectional traversal of a list, and the modification of elements.
-> ListIterator is only used for lists, and not used for map, set, and list.


1) void add(Object obj) - Inserts obj into the list in front of the element that will be returned by the next call to next( ).

2) boolean hasNext( ) - Returns true if there is a next element. Otherwise, returns false.

3) boolean hasPrevious( ) - Returns true if there is a previous element. Otherwise, returns false.

4) Object next( ) - Returns the next element. A NoSuchElementException is thrown if there is not a next element.

5) int nextIndex( ) - Returns the index of the next element. If there is not a next element, returns the size of the list.

6) Object previous( ) - Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.

7) int previousIndex( ) - Returns the index of the previous element. If there is not a previous element, returns -1.

8) void remove( ) - Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.

9) void set(Object obj) - Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

Difference between final,finally,finalize



Final:

-> Final is access modifier, its applicable for variable,method and class
-> IF variable is final - we can change the value.its constent
-> If method is final - The sub class cannot overwrite
-> If class is final - we can not extends this class. not able to create sub class.