Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

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

Sunday

FizzBuzz sample Program in Java 8

public static String fizzBuzzInJava8(int number) 
{
 String result = Optional.of(number) .map(n -> (n % 3 == 0 ? "Fizz" : ""+ (n % 5 == 0 ? "Buzz" : "")) .get();

 return result.isEmpty() ? Integer.toString(number) : result; 
}

Advantages and Disadvantages of using Static Methods inside Class in Java

Advantages and Disadvantages of using Static Methods inside Class in Java

Advantages:


  1. Static methods are thread safe.
  2. Globally accessible
  3. Can be accessed by using Class Name.
Disadvantages:
  1. Static members are part of class and thus remain in memory till application terminates and can't be ever garbage collected. Using excess of static members sometime predicts that you fail to design your product and trying to cop of with static / procedural programming. It denotes that object oriented design is compromised. This can result in memory over flow.
  2. To synchronize need some more efforts.

Tuesday

How to find the length of StringBuffer sample Program

How to find the length of StringBuffer sample program



public class Sample {

    public static void main(String args[])
    {
   StringBuffer sb = new StringBuffer("This is my first sample program");
   System.out.println("The length of the string buffer is: "+sb.length());
    }
}




Thursday

Java Comparator sample program example

Java Comparator sample program example

import java.util.Comparator;


public class Employee {

private String empName;
private String department;
private int age;
public Employee(String empName,String department,int age) {
this.empName = empName;
this.department = department;
this.age = age;
}

public static class OrderByName implements Comparator<Employee>
{

@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return e1.empName.compareTo(e2.empName);
}

}

public static class OrderByDepartment implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return e1.department.compareTo(e2.department);
}
}

public static class OrderByAge implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return e1.age>e2.age?1:(e1.age<e2.age?-1:0);
}
}
/**
* @return the empName
*/
public String getEmpName() {
return empName;
}
/**
* @param empName the empName to set
*/
public void setEmpName(String empName) {
this.empName = empName;
}
/**
* @return the department
*/
public String getDepartment() {
return department;
}
/**
* @param department the department to set
*/
public void setDepartment(String department) {
this.department = department;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}

}



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


public class Sample {

    public static void main(String args[])
    { 
   Employee e1 = new Employee("vaisakh","IT",21);
   Employee e2 = new Employee("rajkumar","EEE",22);
   Employee e3 = new Employee("binu","MECH",20);
   
   List<Employee> list = new ArrayList<Employee>();
   list.add(e1);
   list.add(e2);
   list.add(e3);

   Collections.sort(list, new Employee.OrderByName());
   System.out.println("Ordering based on name "+list);
   Collections.sort(list, new Employee.OrderByDepartment());
   System.out.println("Ordering based on department "+list);
   Collections.sort(list, new Employee.OrderByAge());
   System.out.println("Ordering based on age "+list);
    }
}

Java Program to Find the Fibonacci series of a number

Java Program to Find the Fibonacci series of a number

public class Sample {

public static int findFibbonacci(int fibbNum)
{
if(fibbNum==1 || fibbNum==2)
{
return 1;
}
int f1=1;int f2=1;int fib=1;
for(int i=3;i<=fibbNum;i++)
{
fib=f1+f2;
f1=f2;
f2=fib;
}
return fib;
}
    public static void main(String args[])
    {
 
    for(int i=1;i<10;i++)
    {
    System.out.println(findFibbonacci(i));
    }
    }
}


Java Program to Replace a Character from a String by index position

Java Program to Replace a Character from a String by index position

public class Sample {

public static String replaceChar(int index,String str,char replaceChar)
{
char[] charStr = str.toCharArray();
charStr[index] = replaceChar;
return String.valueOf(charStr);
}
    public static void main(String args[])
    {
   System.out.println(replaceChar(6,"malayalam",'b'));
    }
}

Java Program to Replace a Character with another Character form a String

Java Program to Replace a Character with another Character form a String

public class Sample {

public static String replaceChar(char character,String str,char replaceChar)
{
int l = str.length();
char[] charStr = str.toCharArray();
for(int i=0;i<l;i++)
{
if(charStr[i]==character)
{
charStr[i]=replaceChar;
}
}
return String.valueOf(charStr);
}
    public static void main(String args[])
    {
   System.out.println(replaceChar('a',"malayalam",'b'));
    }
}

Sunday

How to get the current date and time in Java Date() and Calendar()

How to get the current date and time in Java Date() and Calendar()

Example Program:

public final class Test {

//static String[] strArray = new String[10];
//static String[] strArray1 = new String[10];
    public static void main(String args[])
    {

     DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
      //get current date time with Date()
      Date date = new Date();
      System.out.println(dateFormat.format(date));
 
      //get current date time with Calendar()
      Calendar cal = Calendar.getInstance();
      System.out.println(dateFormat.format(cal.getTime()));
    }
 
}

How to compare Arrays in Java

How to compare Arrays in Java

For Comparing Arrays we use equals() and deepEquals() methods.

Example:

public final class Test {
static String[] strArray = new String[10];
static String[] strArray1 = new String[10];
    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="abc";
    strArray[2]="abc";
    strArray[3]="abc";
    strArray[4]="abc";
   
    strArray1[0]="abc";
    strArray1[1]="abc";
    strArray1[2]="abc";
    strArray1[3]="abc";
    strArray1[4]="abc";
   
    if(Arrays.equals(strArray, strArray1))
    {
    System.out.println("Both are equal");
    }else
    {
    System.out.println("Both are not equal");
    }
    }
 
}

Find the longest String in an Array java with Example

Find the longest String in an Array java with Example

Example:

public final class Test {

static String[] strArray = new String[10];

public static String getLongString(String[] array)
 {
   int maxLength = 0;
   String longestString = null;
   for (String s : array)
   {
     if (s.length() > maxLength)
     {
       maxLength = s.length();
       longestString = s;
     }
   }
   return longestString;
 }

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="ramesh";
    strArray[2]="java api";
    strArray[3]="strengh";
    strArray[4]="d";
    System.out.println("Longest String: "+getLongString(strArray));
    }
 
}

How to convert Java Object Array to List in Java

How to convert Java Object Array to List in Java

We studied how to create a Array, how to sort it etc. Now we are going to convert the Array to List .

Example:

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    List list = Arrays.asList(strArray);
    Iterator li = list.iterator();
    while(li.hasNext())
    {
    System.out.println(li.next());
    }
    }
 
}

Java String Array Contains with Examples

Java String Array Contains with Examples

We already studied Java String Array and Sorting a String Array. Now we check whether a String Array contains.

Example:

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    for(int i=0;i<strArray.length;i++)
    {
    if(strArray[2].equals("ghi"))
    System.out.println("true");
    }
    }
 
}

How to sort a Java String Array

How to sort a Java String Array

We already studied what is String array in Java. Now we will sort the previously created String Array.

Example:

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    Arrays.sort(strArray);
   
    for(int i=0;i<strArray.length;i++)
    {
    System.out.println(strArray[i]);
    }
    }
 
}

String Array in Java with Examples

String Array in Java with Examples

Array is a container to store some values of a single type.The length of the array is fixed at the time of creation and it can't be changed. The String array is used to store String values. In String array you can't store other types.

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    for(int i=0;i<strArray.length;i++)
    {
    System.out.println(strArray[i]);
    }
    }
    }

Difference between Maven and Ant and Jenkins and Hudson

Difference between Maven and Ant and Jenkins and Hudson

Commonly Maven and Ant are java build tools. Main difference between Maven and Ant is Maven supports Dependency Management.You can setup your CI environment using Jenkins or Hudson and automatically build, test and deploy your Java project. Now last, main difference between Jenkins and Hudson, both are originate from same source code but one is closed source while other is open source.

All are Java build tools supports unit testing and project management.The out put of build is .JAR,.WAR or .EAR files.
Main difference between ANT and Maven is that In ANT you need to define every thing i.e. source directory, build directory, target directory etc while Maven adopts principle of Convention over configuration. Which means Maven has predefined project structure i.e. standard directory for source files, test files and resources.

Maven VS Ant:
Maven comes after Ant and it offers more functionality than Ant. The key factors of Maven over Ant are as follows.

  1. Versioning managed by bean
  2. Maven provides Conventions
  3. Extensibility and reusability
  4. Better Quality
  5. Less Time Spent
Differences:
  1. Less Configuration needed.It works on principle of Convention over configuration.
  2. Maven supports dependency management. All the jar files are stored in a repository.It automatically downloads dependency during build process.But Ant stores it in a ${lib}.
  3. Maven offers a consistent and common interface to build Java projects.By looking the pom.xml you can easily understood the path and what are the project dependencies.




Thursday

Java Exception Interview Questions

Java Exception Interview Questions

Java Exceptions is a large topic and lot of topics are need to be covered. Here i will give you some introduction about Exceptions in Java.
What is Exception in Java?
                                               An Exception is a programming error. Exceptions are of two types. Checked Exceptions and Unchecked Exceptions. An Error is not an Exception.

  1. What is an Exception in Java? :  Exception is a programming error in Java.Exceptions are inherited from Throwable,exception,Runtime. Exceptions are handled by try and catch statements.
  2. Difference between Checked and Unchecked Exception in Java: Checked Exceptions are handled by try and catch. They occur at Compile time.ex:- IOException Unchecked Exceptions are those programming errors. ex:- Nullpointer exception.
  3. Is it necessary to follow try with catch block: No it's not necessary to have a catch block after try. you can also use finally after try block.
  4. What is the difference between throw and throws in Java: 

1)throw is used to explicitly throw an exception.
 throws is used to declare an exception.
    
2)checked exceptions can not be propagated with throw only.
checked exception can be propagated with throws.

3)throw is followed by an instance.
throws is followed by class.

4)throw is used within the method.
throws is used with the method signature.

5)You cannot throw multiple exception
You can declare multiple exception e.g. public void method()throws IOException,SQLException.


6. How to write Custom Exception in Java: A Custom Exception is an User Defined Exception. It should inherit the Exception base class.
package com.sis.crm.exception.util;

public class AlreadyExistException extends Exception{
@Override
public String getMessage() {
return super.getMessage();
}

public AlreadyExistException(String message, Throwable exception) {
super((exception != null && (message == null || message.length() == 0)) ? exception.getMessage() : message, exception);
}

@Override
public String toString() {
return super.toString();
}

}

7. What is the difference between Final,Finalize, and Finally keyword in Java:  Final keyword is used for creating immutable class in java. Finalize keyword is used for Garbage Collection in Java. Finally keyword is used to execute some code that is to close some resources etc. example if an error occurs in try block and error occurs in catch block, and finally is used to close some database connection etc.

10 Best programming Practices for Java Naming Conventions

10 Best programming Practices for Java Naming Conventions

Each and Every Programmer are well and best in coding, are they aware of how to code and how the naming conventions must follow.There are best practices and bad practices. Best practices are the one that has to be followed while coding and bad practices are the that has to be avoided while coding. Best Coding reflects your ability in programming. Best Naming Conventions increases the readability and the software quality. These are common regardless of the Programming language. Java, C++,.Net all should follow the naming Conventions.

Java Naming Conventions for Variables,Methods,Class etc...

These are the Naming Conventions came across years of programming practices. lets look at some of the Naming Conventions.

  1. Give Meaningful Names:
                                                Always give names that are meaningful and related to the program. It allows easy understanding of the need for the variable and use of this variable. eg:- joiningDate. if it's given jDate, it's not able to easily understand. it can be followed for variable names,Class,methods and packages.

2. Prefer shorter names rather than longer one:
                                                                               You should prefer shorter names rather than longer names. If it's shorter then it's easy to read and understand.

3. Follow Java Naming Conventions:
                                                              Java also provides some naming conventions. for example here are some of the naming conventions.  Class name should start with Uppercase letter. ex:- Employee. Variables should start with lowercase letter and second word should be uppercase letter(CAMEL CASE). Constants are all Upper Case letters. ex:- MAX_LIMIT.

4. Avoid Pointless Names:
                                             For example variables like abc,temp, etc. It's a bad programming practice.

5. Follow Classical Programming Convention:
                                                                             As already mentioned Pointless Names are bad programming practices. But you can use simple variables like 'i' , 'j'.

while(i<n)
{
n++;
}

                                                                  
6. Avoid Clusters in Programming:
                                                         For example "_test" etc are need to be avoided.you should use meaningful and unique names.

7. Avoid Duplication:
                                    Avoid usage of similar names. For example employee and employees are same but it will leads to complication. These are encountered while code reviews.

Sunday

How to convert a map to list in Java with example

How to convert a map to list in Java with example

Before doing this you must have clear idea of List and Map in Java. List is an Interface implementing the Collection Interface.List allows duplicate values.Some Classes implementing List Interfaces are ArrayList,LinkedList etc.Map is not a Collection.Some Classes implementing the Map Interfaces are HashMap,TreeMap etc.

Logic:
  1. First we have to convert the Map into a Set using entryset.
  2. Second we have to convert Set into List.
Example:

public class HelloWorld{

public static void main(String[] args) {
HashMap<String, Integer> mapOne = new HashMap<String, Integer>();

mapOne.put("one", 1);
mapOne.put("two", 2);
mapOne.put("three", 3);
mapOne.put("four", 4);
mapOne.put("five", 5);
        
        Set<Entry<String, Integer>> set = mapOne.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
        Iterator<Entry<String, Integer>> it = list.iterator();
        
        while (it.hasNext()) {
            Entry<String, Integer> entry = it.next();
            System.out.println("Map Converted to List : " + entry);
        }
}
}


Output:
Map Converted to List : two=2
Map Converted to List : five=5
Map Converted to List : one=1
Map Converted to List : four=4
Map Converted to List : three=3

Difference between method overloading and method overriding in Java

Difference between method overloading and method overriding in Java

This is one of the important tricky programming interview questions asked in Java. Here are the basic differences between method overloading and method overriding in Java.


  1. Method Overloading occurs while compile time and Method Overriding occurs while runtime.
  2. Method Overloading occurs in same class and sub class, but overriding occurs only in subclass.
  3. Static methods can be overloaded, but you can't override static methods.
  4. For overloading method signature has to be changed, but for overriding it's not needed.
  5. Private and final methods can be overloaded but cannot override.

SOLID Principle in OOPS

SOLID Principle in OOPS Programming

The SOLID principles are useful to build a neat an good software. These are the programming and design principles of programming.
SOLID===>

  1. Single Responsibility Principle
  2. Open-Closed Principle
  3. Liskov Substitution Principle
  4. Interface Segregation Principle
  5. Dependency Inversion principle
1. Single Responsibility Principle(SRP):
                                                                   Each and Every Class should have a single responsibility. The Class should be changed for one and only reason.

2. Open-Closed Principle(OCP):
                                                     A Class should be Open for extension and close for modification.

3.Liskov Substitution Principle(LSP):                   
                                                     Objects of parent class can be replaced by objects of child class, without altering the properties of the program.

4.  Interface  Segregation Principle(ISP):
                                                          Program should generate client specific interfaces rather than general purpose interfaces.

5. Dependency Inversion principle(DIP):
                                                         A Class should depend on Abstractions rather than Concretions.