Sunday, May 5, 2019

Java12 new feature: Switch case enhancement


Hi All,

As we all know Java12 has been released on 19th March 19 and some interesting new features introduced by Java. Will create a separate blog for each enhancement which helps the developer community to improve their work by new enhancement.

In this blog will discuss the Switch case enhancements.

Switch case:

Older way:
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        System.out.println(6);
        break;
    case TUESDAY:
        System.out.println(7);
        break;
    case THURSDAY:
    case SATURDAY:
        System.out.println(8);
        break;
    case WEDNESDAY:
        System.out.println(9);
        break;
}

following above code, many break statements make it unnecessarily verbose,
and this visual noise often masks hard to debug errors, where missing
break statements mean that accidental fall-thorugh occurs.

Newer way:
switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}

introduced a much simpler way, isn't is very easy to write.
written "case L ->" to signify that only the code to the right of the label is to be executed if the label is matched. 
The above example used multiple swicth cases in a single line,which make life of developer very easy.
Other enhacment is use of local variable inside switch block,let have a look
Older war:
switch (day) {
    case MONDAY:
    case TUESDAY:
        int temp = ...
        break;
    case WEDNESDAY:
    case THURSDAY:
        int temp2 = ...     // Why can't I call use the same temp?
        break;
    default:
        int temp3 = ...     // Why can't I call use the same temp?
}
            
                                            OR
int numLetters;
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        numLetters = 6;
        break;
    case TUESDAY:
        numLetters = 7;
        break;
    case THURSDAY:
    case SATURDAY:
        numLetters = 8;
        break;
    case WEDNESDAY:
        numLetters = 9;
        break;
    default:
        throw new IllegalStateException("Wat: " + day);
}
Expressing this as a statement is roundabout, repetitive and error-prone.
Newer way:
int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    case THURSDAY, SATURDAY     -> 8;
    case WEDNESDAY              -> 9;
};
Now its possible to compute the value from switch.

Saturday, December 15, 2018

Swapping 2 number without using temp variable

Hello Guys,

Will see ,how to swap 2 numbers in java without using temp variable.


Algo to swap number
--------------------

int a =10;
int b=20;

a=a+b; // which is 30
b=a-b;// now a is 30 and b is 20 so result is 10
a=a-b; now b is 10 and a is 30 so result is 20

Swapping using XOR bitwise operator
----------------------------------
int p=10;
int q=20;

//X^Y is equal return 0 or and if its not equal than return 0
p=p^q;
q=p^q;//here p=q
p=p^q;//here q=p



Thanks,
Vikas


Tuesday, November 29, 2016

Difference between == and equals method with example

Hello Guys,

How == operator and equals method works in java.
So many people ask this question in Java interview and some also give a little program like mentioned below to explain.

Here,we have example for learning about very basic stuff of Java

You can directly run the below program and can see the output.


public class Test {

 public static void main(String[] args) {
String s1= "hi";
String s2= new String("hi");

    if(s1==s2)
System.err.println("Ist case: s1==s2:result:- "+"++++" +" hascode of S1:= "+s1.hashCode()+ " S2: "+ s2.hashCode());

System.out.println("Ist case: s1.equals(s2):result:- "+ s1.equals(s2));

s2=s1;

   if(s1==s2)
  System.err.println("2nd case: s1==s2:result:- "+"_-___"+ "hascode true or false of S1:= "+(s1.hashCode() == s2.hashCode()) );


System.out.println("2nd case: s1.equals(s2):- "+ s1.equals(s2));

    }
}

OutPut:-
----------
Ist case: s1.equals(s2):result:- true
2nd case: s1==s2:result:- _-___hascode true or false of S1:= true
2nd case: s1.equals(s2):- true


Any Suggestion and comments are most welcome!

Thanks,
Vikas



How to Print HashMap in Java


Hello Guys,

How to Print HashMap is very common and frequently ask question now a days for testing programming skills in Java.

So,lets try to understand the  program given below.


import java.util.HashMap;
import java.util.Set;


public class Test extends Thread{

public static void main(String[] args) {
//Creating HashMap key and value as String.
HashMap<String, String> st = new HashMap<String, String>();
//Putting some key and value in Map

st.put("K1", "V1");
st.put("K2", "V2");
st.put("K3", "V3");
st.put("K4", "V4");
st.put("K5", "V5");

//Now iterate or loop Map by using KeySet method of Map
for(String name: st.keySet()){

String key= name.toString();
//Here we are calling get method of Map class by passing key which is we got from KeySet()
String value= st.get(name).toString();
System.out.println("Key:- "+ key +"value:- "+ value );
}
}
}
note:-
1)KeySet returns set view of the keys contained in map.
2)Changes to map will reflect to set and vice-versa also possible.

Its very simple Program and can be use by beginners who just started learning java and collection.

Any comment or Suggestion is most welcome!


Thanks,
Vikas






Tuesday, October 25, 2016

java.lang.OutOfMemoryError: Java heap space

Out Of Memory issue occurred mostly at 2 places.
1)    The java.lang.OutOfMemoryError: Java heap space
2)    The java.lang.OutOfMemoryError: PermGen space

Before discussing the OutOfMemory, would like to give brief detail about heap and non-heap spaces.

Heap
The JVM has a heap that is the runtime data area from which memory for all class instances and arrays are allocated. It is created at the JVM start-up.

If you are familiar with different generations on the heap.
You may aware about new, old and permanent generation of heap space.

Non-Heap
The JVM has memory other than the heap, referred to as non-heap memory. It is created at the JVM startup and stores per-class structures such as runtime constant pool, field and method data, and the code for methods and constructors, as well as interned Strings.

2nd issue or PermGen Space related is coming when Non-Heap Memory is full.

1st Reason is:-
Permanent generation(PermGen) of the heap is used to store String pool and various Metadata required by JVM related to Class, method and other java primitives.

If Project is big, you can easily run out of memory if you have too many unnecessary classes or a huge number of Strings in your project and also not managing object creation.
To resolve this kind of issue you can increase the size of permGen by
export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m

2nd Reason is:-
Memory leak through classLoader.
Most likely occurred by webserver or application server.

Sharing some points with you.

1)Check the Jconsole(for running jconsole, just open cmd and type jconsole&)


In highlighted area you can see the heap and non-heap memory is too high and can cause OutOfMemory.

As we know GC is being called and it will release the space in heap, you can see the figure attached below.
Here I came to know that, server is loading same class again and again on each job run.
So for solving this ,I restrict the class to load again and removed unnecessary String literal also.


So solution can be used:

1) Remove any class which load every time on each call,for an example loading JWSDynamicClientFactory for each soapcall.
2)Remove any unused or unnecessary String creation.
3) Check File I/O operation id happening properly or not


Any suggestion and Questions is most welcome.

Thanks,
Vikas




Friday, August 5, 2016

How to check if file is modified or not in JAVA

Hi Guys,

Below program is use to track the changes in the file.


package com.vks.example;

import java.io.File;

public class FileModifed {

  private static long lastModified = 0L;


static {

lastModified=new File("C://example.txt").lastModified();
  }
public static void main(String[] args) {

//calling isFileModied method in loop to check if file is modified or not.A infinite for loop to check file is modified or not.
  for (int i = 0; i >= 0; i++) {

if (isFileModified())
break;
  }

}

public static boolean isFileModified() {

  File file = new File("C://example.txt");
  if (lastModified >= file.lastModified()) {
  System.out.println(lastModified + "-------- Not Modified-------" + file.lastModified());
return false;
  } else {
lastModified = file.lastModified();
System.out.println("-------- Modified-------");
return true;
  }
    }

}

Any comments or Suggestion are most welcome!!

Thanks,
Vikas

Saturday, September 26, 2015

Project manager or managerial round interview question for experienced Java developer

Project Manager or Managerial round Interview Questions and some tips:

Pre-requisite 
You need to understand your project thoroughly,as many of question you can relate with your project and can provide answer in a good manner and interviewer can also understand that how much you involved in your project.

Now we come to the part of interview question:-
Ques1: How you can achieve loose coupling in spring?
Ques2:- Which is better Hibernate or JDBC?
Ques3: Flow of spring application?how request gone through various layers and how Spring container manage them.
Ques4: can we print whole HashMap without using Key's?
Ques5: What is normalization?what is the purpose of using Normalization?
Ques6: How you integrate the Spring and Hibernate in your application?
Ques7: How HashMap internally works?
Ques8: What is OOPs and why Java is Object Oriented language?
Ques9: If I have 2 tables called employee and salary,how I can get 2nd Max salary for the employee?
Ques10: Why and when yo use @Autowire and @Resource in Spring?
Ques11:  what is the benefit of using Autowiring and and which one is better to use, xml configuration or Annotation and why?
Ques12: Design Pattern used in SpringMVC, IOC?
Ques13: How many design Patterns are there and how they are categorized?


Communication and how to handle pressure:
These are the technical question but in between that interviewer also checks your communication and your attitude, he put you in condition where you can be nervous and could not handle the pressure, which gave him idea that how you handle the pressure. So be calm and give answer in very simple manner, don't get excited if you know the answer,pretend that you are thinking and then start giving your answer but if you don't know the answer then don't try to think about it and just say like I don't know but that's a good question will definitely get the answer of it for enhancing my knowledge in technology.

How pressure create:
Suppose Interview ask you to right some logic or code on whiteBoard to check your presentation skills,but you stuck with the question and gone nervous by which you may not able to present your self in good manner,so if interviewer ask you to perform some task on WhiteBoard then don't hestiate and try to explain whatever you have and how you implemented those things in your project.See yourself as a presenter and give your presentation.

Always remember that if you are nervous then take one deep breath and start again do not put your self in pressure or in nervous state,be confident,be patient.

what to do just before interview:
Relax yourself, don't think about interview. Just think once that you are doing some different task rather then regular tasks on that day and worst case of the interview is you will not select to the company but you can gain some knowledge by giving interview(Always Positive).

Post Interview:
If interviewer ask you to that 'do you have any question' then you can ask some question like about the Company culture ,about Project.
Last, Thanks to interviewer!

In Future will add answer of the technical question mentioned above.
Purpose of sharing this article is that, I have also gone through from such condition and interview, I saw there is not so much content available on internet,So I thought its better to share experience with you guys so you can put your best in Managerial round.
Please share your experience as well in comment block.so other can take tips from there.

Thanks,
Vikas