Saturday, 30 July 2016

Java New Date Time API Example

 LocalDate represents only a date.
 LocalTime represents only a time.
 LocalDateTime class represents both date and time.
 Instant represents timestamp.

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.OffsetTime;
import java.time.Year;

public class NewDateAndTimeAPI {

public static void main(String[] args) {
System.out.println("WOKING WITH DATES\n--------------------------");
// to increase date by plus 1
LocalDate tommarowDate = LocalDate.now().plusDays(1);
System.out.println("NEXT DAY DATE\t:"+tommarowDate);

// to increase month by plus 1
LocalDate nextMonthDate = LocalDate.now().plusMonths(1);
System.out.println("NEXT MONTH DATE\t:"+nextMonthDate);

// to increase year by plus 1
LocalDate nextYearDate = LocalDate.now().plusYears(1);
System.out.println("NEXT YEAR DATE\t:"+nextYearDate);

//to increase date day and year all by plus 1
LocalDate next = LocalDate.now().plusDays(1).plusMonths(1).plusYears(1);
System.out.println("DATE DAY AND YEAR ALL INCREASES BY PLUS 1 : "+next);

//to get only current year
Year currentYear = Year.now();
System.out.println("CURRENT YEAR\t:"+currentYear);

//to get only current month
Month currentMonth = LocalDate.now().getMonth();
System.out.println("CURRENT MONTH\t:"+currentMonth);

//to get only current date
int currentDate = LocalDate.now().getDayOfMonth();
System.out.println("TODAY DATE\t:"+currentDate);

//to get only current week day
DayOfWeek week = LocalDate.now().getDayOfWeek();
System.out.println("TODAY DAY OF WEEK\t:"+week);

//to check weather current or any year is leap year or not
System.out.println("CURRENY YEAR IS LEAP YEAR OR NOT :                      "+LocalDate.now().isLeapYear());

//to check manually any year is leap or not
boolean checkLeap = Year.isLeap(2017);
System.out.println("MANNUALLY CHECKING 2017 IS LEAP OR NOT : "+checkLeap);

System.out.println("---------------------------------\nWORKING WITH TIME\n---------------------------------");
// to know current time only without date
LocalTime currentTime = LocalTime.now();
System.out.println("CURRENT TIME\t:"+currentTime);

// to know current hour from current time
int currentHour = LocalTime.now().getHour();
System.out.println("CURRENT HOUR\t:"+currentHour);

// to know current minute from current time
int currentMinute = LocalTime.now().getMinute();
System.out.println("CURRENT MINUTE\t:"+currentMinute);

// to know current second from current time
int currentSecond = LocalTime.now().getSecond();
System.out.println("CURRENT SECOND\t:"+currentSecond);

// to know current second from current time
int currentMillisecond = LocalTime.now().getNano();
System.out.println("CURRENT NANO SECOND\t:"+currentMillisecond);

System.out.println("---------------------------------\nWORKING WITH DATE & TIME\n---------------------------------");

// to know current date and time
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("CURRENT DATE AND TIME\t:"+dateTime);

System.out.println("---------------------------------\nWORKING WITH TIMESTAMP\n---------------------------------");

// to work with timestamp
Instant ins = Instant.now();
System.out.println(ins);

OffsetTime off = OffsetTime.now();
System.out.println(off);
}


}

Friday, 29 July 2016

Java Lambda Expression Example

The biggest new feature of java-8 is Lambda Expression. It simplifies the development a lot means it cut lines of code. The syntax for it is “parameters -> body” , Some important rules to syntax is
1 > Declaring the types of the parameters is optional.
2 > Using parentheses around the parameter is optional if you have only one parameter.
3 > Using curly braces is optional (unless you need multiple statements).
4 > The “return” keyword is optional if you have a single expression that returns a value.

interface MathOperation{
int operation(int a,int b);
}
public class LambdaExample {

public static void main(String[] args) {
// with variable type declaration
MathOperation add = (int a,int b) -> a+b;
System.out.println("ADDITION\t:"+add.operation(5, 2));
// without variable type declaration
MathOperation sub = (a,b) -> a-b;
System.out.println("SUBSTRACTION\t:"+sub.operation(5, 3));
// with return statement along with curly braces
MathOperation div = (a,b) -> {return a/b ; };
System.out.println("DIVIDE\t\t:"+div.operation(10, 5));
// Traversing Arraylist in one line
List<Integer> l=new ArrayList<Integer>();
for(int i=0;i<10;i++){
l.add(i);
}
l.forEach( n -> System.out.println(n));
// Providing the type of parameter is optional 
l.forEach((Integer n) -> System.out.println(n));
// Sorting Arraylist using Lambda Expression in one line
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(5);
list.add(3);
Collections.sort(list , (i,j) -> i.compareTo(j));
System.out.println("SORTED LIST : "+list);

  // Starting Thread using lambda expression
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
}
}


Tuesday, 26 July 2016

Java Code Showing example of Inheritence

Inheritence is a mechanism by which we inherit all the features of super class in sub class through extends keyword. By extending super class and creating sub class object we have 
1 > by default super class constructor available in sub class
2 > we can call super class variable  
3 > we can call super class method

How inheritance implemented in java?
Inheritance can be implemented in JAVA using below two keywords.
1 > extends
2 > implements 

extends Keyword Example :-
class Customer{
int num = 50;
public Customer() {
System.out.println("Super Class Constructor");
}
void show(){
System.out.println("Super Class Method");
}
}
public class InheritenceExample extends Customer{
public static void main(String[] args) {
InheritenceExample i = new InheritenceExample();
System.out.println("Super Class Variable : "+i.num);
i.show();
}
}

implements Keyword Example :-
The interface keyword is used to declare an interface , a class implements an interface , in interface
1 > All methods are by default Abstract and public.
2 > All variable are by default static and final .
3 > An interface can extends multiple interfaces.
4 > One interface extends another interface not implements

interface Service{
int num = 20;
void show();
}
public class Example implements Service {

@Override
public void show() {
System.out.println("show method");
}
public static void main(String[] args) {
ImplementsKeywordExample i =new ImplementsKeywordExample();
System.out.println("VARIABLE :- "+i.num);
i.show();
}

}

There are two types of inheritance
1 > Multilevel Inheritance : -
class AA{

}class BB extends AA {

}class CC extends BB {

}
2 > Multiple Inheritance : -
Multiple Inheritence is not supported by java because of Diamond Problem .In multiple inheritance there is every chance of multiple properties of multiple objects with  the same name available to the sub class object with same priorities leads for the ambiguity.

class M{

}class N extends M{
}class O extends N{
}class P extends N,O { // not supported by java leads to syntax error. 

}

Monday, 25 July 2016

Java Code Showing example of Encapsulation

Encapsulation is a mechanism through which we hide the data members and access those data members through public method known as getters and setter.
Or
The Process of binding the data with related methods known as Encapsulation .

class Employee{
private String name;
private String empCode;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
}
public class EncapsulationExample {

public static void main(String[] args) {
Employee e = new Employee();
e.setName("abc");
e.setEmpCode("EMP001");

System.out.println("EMP NAME\t:"+e.getName());
System.out.println("EMP CODE\t:"+e.getEmpCode());
}

}

Sunday, 24 July 2016

Java Code to Merge Two Array?

public class MergeTwoArray {

public static void main(String[] args)  {
String a[]={"a","b","c","d","e","f","g"};
String b[]={"h","i","j","k","l","m"};

List al=new ArrayList(Arrays.asList(a));
al.addAll(Arrays.asList(b));

System.out.print(al);
}

}

Thursday, 21 July 2016

Java Code for finding duplicate element from Arraylist

In Method 1 we are using set interface to find duplicate element from list because set only allow unique elements , In Method 2 we are using for loop to find duplicate element . 

public class DuplicateSingleElementFromList {

static int method1(List<Integer> list){
int duplicate = 0;
Set<Integer> set = new HashSet<>();
for(int i=0;i<list.size();i++){
if(!set.add(list.get(i))){
duplicate = list.get(i);
break;
}
}
return duplicate;
}
static int method2(List<Integer> list){
int duplicate = 0;
for(int i=0;i<list.size();i++){
for(int j=1;j<list.size();j++){
if(list.get(i) == list.get(j)){
duplicate = list.get(i);
break;
}
}
}
return duplicate;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i=0;i<100;i++){
list.add(i);
}
list.add(11);
System.out.println("METHOD 1 OUTPUT : "+method1(list));
System.out.println("METHOD 2 OUTPUT : "+method2(list));
}

}

Sunday, 17 July 2016

Java Code Showing Use of String Tokenizer

String Tokenizer belongs to Util Package. And it is use to break String using delimiter such as space , comma(,) , slace either forward(/) or backword(\) or you can use any special symbol or character. 



public class StringTokenizerExample {

public static void main(String[] args) throws IOException{

String str="India is a Great Country.";
StringTokenizer token = new StringTokenizer(str, " ");
while(token.hasMoreTokens()){
System.out.println(token.nextToken());
}
}
}

Saturday, 16 July 2016

Java Program Without Main Method

With the help of static block user can execute Java Program.

public class WithoutMainMethod {

static{
System.out.println("STATIC BLOCK");
}
public static void main(String[] args) {

}
}


Java Code Showing Internal Working of Hashmap

Hash map works on the principle of Hashing ,
Hashing is a technique which convert keys into some integer value known as Hash code .
Default size of hashmap is 16.
This Hashcode is used to store values into Hashmap.
Internally Hashmap uses Table which has array of nodes.
Each Block of table known as bucket.
Each bucket uses LinkedList to store elements and LinkedList store elements in the form node i.e key,hashcode,value and next node address
Example : 
HashMap<String,Integer> map = new HashMap<String, Integer >();
map.put(“ram”,100);
map.put(“shyam”,101);
map.put(“mohan”,102);

How put operation works in Hashmap.
Step 1 > First put operation calculate Hashcode of key . For Example here we calculate Hashcode of key ram  suppose Hashcode of key ram is 1475236 , we cannot create array of this size so we calculate index position from Hashcode (1475236) ,to calculate index position Hashmap divide the Hashcode by Map default size i.e 16 and use remainder (4)as a index to store key in table.







Step 2 > Now we calculate Hashcode of key shyam i.e 64205538 and index is 2 ,hashmap store this key at index 2.









Step 3 > Now we calculate Hashcode of key mohan i.e 4452852 and index is 4 ,hashmap store this key at index 4 .If any element is already available at particular index then bucket internally uses LinkedList to store element .This process continue for all the keys in Hashmap.








How get operation works in Hashmap.
map.get(“ram”);
map.get(“shyam”);
map.get(“mohan”);

Get also do the same operation as Put do , get operation also first calculate Hash code of key suppose Hash code of key ram is 1475236 and then it calculate the index from Hash code i.e.  4
And Now it look up at index 4 and matches the hash code , if Hash code matches then it match the key using equals() method and if key matches then it return the value . This operation continue till it get values of all keys.

public class HashmapInternalWorking {

public static void test() {
   int size = 16; // slot size
   Integer[] keys = { 1, 10, 16, 100, 1000, 10000, 2000000, 100000000 };
   HashMap<Integer, Object> map = new HashMap<Integer, Object>();

   for (Integer key : keys) {
       int hash = hash(key.hashCode());
       int i = indexFor(hash, size);

       map.put(key, "[" + hash + " : " + i + "]");
   }

   for (Integer key : map.keySet()) {
       System.out.printf("key: %9s, [inner hash : slot index]: %s,\n", key, map.get(key));
   }
}

static int hash(int h) {
   h ^= (h >>> 20) ^ (h >>> 12);
   return h ^ (h >>> 7) ^ (h >>> 4);
}

static int indexFor(int h, int length) {
   return h & (length - 1);
}
public static void main(String[] args) {
test();
}

}

Thursday, 14 July 2016

Java Program For Fibbonacci Series


public class FibonnaciSeries {
public static void main(String[] args) {
int n=5;
                int a=0;
int b=1;
int c;
System.out.print(a+","+b+",");
for(int i=0;i<n;i++){
c=a+b;
a=b;
b=c;
System.out.print(c+",");
}
}
}

Here n is length of series User can change accordingly.

Java Code to Calculate Factorial

public class Factorial {

public static void main(String[] args) {
System.out.print("Enter Number For Factorial : ");
Scanner sc=new Scanner(System.in);
int num = sc.nextInt();
int out =1;
for(int j=1;j<=num;j++){
out = out * j;
}
System.out.println("OUTPUT : "+out);
}
}

Java Code Showing use of Comparator Interface

class School {
private String name;
private int rollNo;
public School(String name,int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
@Override
public String toString() {
return "Name : "+name+"\t"+"Roll No : "+rollNo;
}
}
class SortByRollNo implements Comparator<School>{
@Override
public int compare(School s1, School s2) {
return (s1.getRollNo() < s2.getRollNo() ? -1 : (s1.getRollNo() > s2.getRollNo()) ? 1 : 0);
}
}
class SortByName implements Comparator<School>{
@Override
public int compare(School s1, School s2) {
return s1.getName().compareTo(s2.getName());
}
}
public class ComparatorExample {

public static void main(String[] args) {
School s=new School("Pushkar",104);
School s1=new School("Alok",101);
School s2=new School("Sanjay",102);
School s3=new School("Zimmy",103);
List<School> list = new ArrayList<School>();
list.add(s);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("SORTING BY ROLL NO : \n");
Collections.sort(list,new SortByRollNo());
Iterator<School> ir = list.iterator();
School sc = null;
while(ir.hasNext()){
sc = ir.next();
System.out.println(sc);
}
System.out.println("SORTING BY NAME : \n");
Collections.sort(list,new SortByName());
Iterator<School> ir1 = list.iterator();
School sc1 = null;
while(ir1.hasNext()){
sc1 = ir1.next();
System.out.println(sc1);
}
}

}

Java Code to Check Year is Leap Year Or Not

public class CheckLeap {

static void show(int year){
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
System.out.println("YEAR IS LEAP YEAR");
} else {
System.err.println("YEAR IS NOT LEAP YEAR");
}
}
public static void main(String[] args) {
show(2015);
}

}

Java Code Showing use of Comparable Interface


class Employee implements Comparable<Employee>{
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int compareTo(Employee emp) {

return (this.id < emp.id) ? -1 : (this.id > emp.id) ? 1 : 0;
}
}
public class ComparableExample {

public static void main(String[] args) {
Employee e = new Employee();
e.setId(10);
Employee e1 = new Employee();
e1.setId(-1);
Employee e2 = new Employee();
e2.setId(12);
List<Employee> list = new ArrayList<Employee>();
list.add(e);
list.add(e1);
list.add(e2);
Iterator<Employee> it = list.iterator();
Employee emp = null;
System.out.println("BEFORE LIST");
while(it.hasNext()){
emp = it.next();
System.out.println(emp.getId());
}
Collections.sort(list);
Iterator<Employee> it1 = list.iterator();
Employee emp1 = null;
System.out.println("AFTER LIST");
while(it1.hasNext()){
emp1 = it1.next();
System.out.println(emp1.getId());
}
}
}


Java Code to Create Dead Lock

If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thread 1 acquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen. 


public class DeadLockDemo {
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
}

Java Code Showing Use of Volatile Variable

public class VolatileVariable {
private static volatile VolatileVariable instance;

public static VolatileVariable getInstance(){
if(instance == null){
synchronized (VolatileVariable.class) {
if(instance == null){
System.out.println("CREATING OBJECT");
instance = new VolatileVariable();
}
}
}
return instance;
}
public static void main(String[] args) {
VolatileVariable.getInstance();
}
}

Java Code Showing Use of Thead Yield Method


class producer extends Thread{
public void run(){
for(int i=0;i<2;i++){
System.out.println("Producer "+i);
Thread.yield();
}
}
}

class consumer extends Thread{
public void run(){
for(int i=0;i<2;i++){
System.out.println("consumer "+i);
Thread.yield();
}
}
}
public class YieldMethod {
public static void main(String[] args) {
Thread p=new producer();
Thread c=new consumer();
p.start();
c.start();
}
}

Java Code To Reverse Each word of String


public class ReverseWord {

public static void main(String[] args) {
String s1="Java Concept Of The Day";
String[] s2=s1.split(" ");
for(int j=0;j<s2.length;j++){
String token=s2[j];
for(int i=token.length()-1;i>=0;i--){
System.out.print(token.charAt(i));
}
System.out.print(" ");
}
}
}

Java Code to Reverse String With White Spaces


public class ReverseStringWithSpaces {

public static void main(String[] args) {
String s1="I Am Not String";
char[] s2=s1.toCharArray();
char[] resultArray=new char[s2.length];
for(int i=0;i<s2.length;i++){
if(s2[i] == ' '){
resultArray[i]=' ';
}
}
int count=resultArray.length-1;
for(int j=0;j<s2.length;j++){
if(s2[j] != ' '){
if(resultArray[count] == ' '){
count--;
}
resultArray[count]=s2[j];
count--;
}
}
System.out.println(s1);
System.out.println(resultArray);
}
}

Java Code to Reverse String

Case 1 > Using For Loop

static void method_1(){
String s1="abc";
for(int i=s1.length()-1;i>=0;i--){
System.out.print(s1.charAt(i));
}
System.out.println();

}

Case 2 > Using String Buffer

static void method_2(){
String s1="abc";
StringBuffer sb=new StringBuffer(s1);
sb.reverse();
System.out.println(sb);
}

Case 3 >  Using Recursive Method

static String recursive_method(String s1){
if(s1==null || s1.length() <=1){
return s1;
}
return recursive_method(s1.substring(1))+s1.charAt(0);
}

Java Code to Remove White Spaces from String



Case 1 > Using Predefined Method

static void method_1(){
String s1="abc d e f";
System.out.println("OUTPUT M1 = "+s1.replaceAll("\\s", ""));

}

Case 2 > Using charAt() Method

static void method_2(){
String s1="abc d e f";
StringBuffer sb=new StringBuffer();
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)!=' ' ){
sb.append(s1.charAt(i));
}
}
System.out.println("OUTPUT M2 = "+sb);

}

Java Code to Check Palindrome



Case 1 > String Palindrome

public static void stringPalindrome(){
String s1="Malayalam";
String s2="";
for(int i=s1.length()-1;i>=0;i--){
s2+=s1.charAt(i);
}
if(s1.equalsIgnoreCase(s2)){
System.out.println("String is Palindrome");
}
else{
System.err.println("String is Not Palindrome");
}
}

Case 2 > Int Palindrome

public static void intPalindrome(){
int n=121;
int palindrome = n;
int reverse=0;
while(palindrome != 0) {
int rem=palindrome % 10;
reverse = reverse * 10 + rem;
palindrome = palindrome / 10;
}
if(n == reverse){
System.out.println("Int is Palindrome");
}
else{
System.err.println("Int is Not Palindrome");
}
}

Java Code to Create Immutable Class



Rule 1 : Make Class Final
Rule 2 : Make Data Members Final
Rule 3 : Make Parameterized Constructor
Rule 4 : Make Only Getters Not Setters

final class ImmutableCheck{
private final String variable;

public ImmutableCheck(String variable) {
this.variable=variable;
}
public String getVariable() {
return variable;
}

}

Java Code to Remove All Spaces



Case 1 > Using Predefined Method

static void method_1(){
String s1="abc d e f";
System.out.println("OUTPUT M1 = "+s1.replaceAll("\\s", ""));
}

Case 2 > Using charAt() Method

static void method_2(){
String s1="abc d e f";
StringBuffer sb=new StringBuffer();
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)!=' ' ){
sb.append(s1.charAt(i));
}
}
System.out.println("OUTPUT M2 = "+sb);
}


Java Code to Count Numbers of Characters From String




public class CountNumberOfCharacters {

public static void main(String[] args) {
String s1="abcb";
Map<Character, Integer> map=new HashMap<>();
for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
}
else{
map.put(ch, 1);
}
}
Set<Character> set=map.keySet();
for(Character c:set){
System.out.println("CHARACTER = "+c+" , OCCURENCE = "+map.get(c));
}
}

}

Java Code to Print Stars (*)



public class Star1 {
public static void main(String[] args) {
for(int i=0;i<6;i++){
for(int j=0;j<=i;j++){
System.out.print("#");
}
System.out.println("");
}
}
}

OUTPUT -
*
**
***
****
*****
******

Java program take array as input count element occurrence and then find element with maximum occurrence



public class Test{

public static void main(String[] args) {
try {
Scanner sc=new Scanner(System.in);
System.out.print("ENTER INPUT ARRAY SIZE : ");
int inputArraySize = sc.nextInt();
System.out.println("ENTER "+inputArraySize+" ARRAY ELEMENTS :");
int[] inputArr=new int[inputArraySize];
for(int i=0;i<inputArraySize;i++){
inputArr[i] = sc.nextInt();
}
Map<Integer, Integer> map=new HashMap<Integer, Integer>();
for(int i=0;i<inputArr.length;i++){
if(map.containsKey(inputArr[i])){
map.put(inputArr[i], map.get(inputArr[i])+1);
}
else{
map.put(inputArr[i], 1);
}
}
int max = Collections.max(map.values());

List<Integer> keys = new ArrayList<Integer>();
for(Entry<Integer, Integer> entry : map.entrySet()){
if(entry.getValue() == max){
keys.add(entry.getKey());
}
}
System.out.println("OUTPUT\nElement\tCount");
System.out.println(Collections.min(keys)+"\t"+max);
} catch (Exception e) {
System.err.println("** ENTER NUMERIC DIGITS ONLY **");
}
}

}