Showing posts with label corejava. Show all posts
Showing posts with label corejava. Show all posts

August 23, 2021

Sort with given object multiple properties names, age using JAVA8

List can be sorted using Java 8 Lambda Expressions, moving right past syntactic sugar and into real and powerful functional semantics. The implementation of all of these examples and code snippets can be found over on gitHub: https://github.com/ramanujadasu/tutorials/tree/master/core-java-modules/core-java-lambdas

List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), 
      new Human("Jack", 12)
    );


Basic Sort Without Lambdas:

    Collections.sort(humans, new Comparator<Human>() {
        @Override
        public int compare(Human h1, Human h2) {
            return h1.getName().compareTo(h2.getName());
        }
    });


Basic Sort With Lambda Support:

    humans.sort(
      (Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));


Basic Sorting With No Type Definitions:

	humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));

Sort Using Reference to Static Method:

public static int compareByNameThenAge(Human lhs, Human rhs) {
    if (lhs.name.equals(rhs.name)) {
        return Integer.compare(lhs.age, rhs.age);
    } else {
        return lhs.name.compareTo(rhs.name);
    }
}

humans.sort(Human::compareByNameThenAge);

Sort Extracted Comparators:

Collections.sort(
      humans, Comparator.comparing(Human::getName));

Reverse Sort:

Comparator<Human> comparator
      = (h1, h2) -> h1.getName().compareTo(h2.getName());
    
    humans.sort(comparator.reversed());


Sort With Multiple Conditions:

List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 12), 
      new Human("Sarah", 10), 
      new Human("Zack", 12)
    );
    
    humans.sort((lhs, rhs) -> {
        if (lhs.getName().equals(rhs.getName())) {
            return Integer.compare(lhs.getAge(), rhs.getAge());
        } else {
            return lhs.getName().compareTo(rhs.getName());
        }
    });

Sort With Multiple Conditions -Composition:

humans.sort(
      Comparator.comparing(Human::getName).thenComparing(Human::getAge)
    );

Sorting a List With Stream.sorted():

List<String> letters = Lists.newArrayList("B", "A", "C");
	
List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
==
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    
	Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
	
    	List<Human> sortedHumans = 
	      humans.stream().sorted(nameComparator).collect(Collectors.toList());

Or
  	List<Human> sortedHumans = humans.stream()
      	.sorted(Comparator.comparing(Human::getName))
      	.collect(Collectors.toList());


Sorting a List in Reverse With Stream.sorted():

List<String> letters = Lists.newArrayList("B", "A", "C");

    List<String> reverseSortedLetters = letters.stream()
      .sorted(Comparator.reverseOrder())
      .collect(Collectors.toList());
==
 List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    
	Comparator<Human> reverseNameComparator = 
      	(h1, h2) -> h2.getName().compareTo(h1.getName());

    	List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator)
    	 .collect(Collectors.toList());

Or
	List<Human> reverseSortedHumans = humans.stream()
      	.sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder()))
     	 .collect(Collectors.toList());

Null Values:
  List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12));

    humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
==
List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12), null);

    humans.sort((h1, h2) -> {
        if (h1 == null) {
            return h2 == null ? 0 : 1;
        }
        else if (h2 == null) {
            return -1;
        }
        return h1.getName().compareTo(h2.getName());
    });

Or	
   humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName)));
Or
   humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName)));

Reference:
https://www.baeldung.com/java-8-sort-lambda

Read more ...

Custom Marker Interface Implementation in Java

Marker interface has no method. Java has built-in marker interface like Serializable, Cloneable & Event Listener etc that are understand by JVM.

We can create our own marker interface, but it has nothing to do with JVM, we can add some checks with instanceOf.


Create the empty interface

interface Marker{    }

Write a class and implements the interface 

class A implements Marker {
  //do some task
}

Main class to check the marker interface instanceof 

class Main {
    public static void main(String[] args) {
        A ob = new A(){
        if (ob instanceof A) {
            // do some task
        }
    }
}

Reference: 
https://stackoverflow.com/questions/11008033/how-to-write-our-own-marker-interface-in-java/35278304 
https://en.wikipedia.org/wiki/Marker_interface_pattern
Read more ...

Can we use return statement in finally block in java?

Bellow program output is always 2, as we are returning 2 from the finally block. Remember the finally always executes whether there is a exception or not. So when the finally block runs it will override the return value of others. Writing return statements in finally block is not required, in fact you should not write it.

 
public class Test {
    public static int test(int i) {
        try {
            if (i == 0)
                throw new Exception();
            return 0;
        } catch (Exception e) {
            return 1;
        } finally {
            return 2;
        }
    }

    public static void main(String[] args) {
        System.out.println(test(0));
        System.out.println(test(1));
    }
}

Output:
2
2

Reference: 
https://stackoverflow.com/questions/18205493/can-we-use-return-in-finally-block

Read more ...

August 10, 2018

Given strings are Anagram or not?

Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.
check-whether-two-strings-are-anagram-of-each-otherWe strongly recommend that you click here and practice it, before moving on to the solution.


Program:
public class Anagram {
public static void main(String[] args) {
String input1 = "d1asu";
String input2 = "adsu";
System.out.println("Given string are input1: " + input1 + ", input2: " + input2);
System.out.println("" + isAnagram(input1, input2));
}
private static String isAnagram(String input1, String input2) {
String result = "Given strings are not anagram";
boolean isAnagram = false;
if (!input1.isEmpty() && !input2.isEmpty() && (input1.length() == input2.length())) {
char[] arr = input1.toCharArray();
StringBuilder sb = new StringBuilder(input2);
for (char a : arr) {
int index = sb.indexOf("" + a);
if (index != -1) {
sb.deleteCharAt(sb.indexOf("" + a));
}
}
isAnagram = sb.toString().isEmpty();
}
if (!isAnagram) {
return result;
}
return "Given strings is anagram";
}
}
Output:
Given string are input1: d1asu, input2: adsu
Given strings are not anagram
Reference:
https://www.devglan.com/java-programs/anagram-test
https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/


Read more ...

Given String is Pangram or not?


Given a string check if it is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet.
Examples : The quick brown fox jumps over the lazy dog ” is a Pangram [Contains all the characters from ‘a’ to ‘z’]
“The quick brown fox jumps over the dog” is not a Pangram [Doesn’t contains all the characters from ‘a’ to ‘z’, as ‘l’, ‘z’, ‘y’ are missing]
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
We create a mark[] array of Boolean type. We iterate through all the characters of our string and whenever we see a character we mark it. Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25.
After iterating through all the characters we check whether all the characters are marked or not. If not then return false as this is not a pangram else return true.

Program:

public class Panagram {


public static void main(String[] args) {
String input = "The quick brown fox jumps over the lazy dog";
System.out.println("Panagram test string : "+input);

System.out.println(""+ checkPanagram(input));
}

/**
*Returns true if the string     is pangram else false
* @param input
* @return
*/
private static String checkPanagram(String input) {
String result = "Given string is not panagram";
  // Create a hash table to mark the
        // characters present in the string
        // By default all the elements of
        // mark would be false.
boolean[] mark = new boolean[26];

if(input == null) {
return "Given input is invalid";
}
// For indexing in mark[]
int index = 0;
// Traverse all characters
for(int i=0;i // If uppercase character, subtract 'A'
            // to find index.
if( 'A' <= input.charAt(i) && input.charAt(i)  <= 'Z') {
index = input.charAt(i) - 'A';
System.out.println("current value: "+input.charAt(i)+", index :"+index);
}
// If lowercase character, subtract 'a'
            // to find index.
if( 'a' <= input.charAt(i) && input.charAt(i)  <= 'z') {
index = input.charAt(i) - 'a';
System.out.println("current value: "+input.charAt(i)+", index :"+index);
}
// Mark current character
mark[index] = true;

}
System.out.println("mark: "+mark+", length: "+mark.length);
// Return false if any character is unmarked
for(int j =0;j if(mark[j] == false) {
return result;
}
}
// If all characters were present
return "The Given String is panagram.";
}

}



Output:
Panagram test string : The quick brown fox jumps over the lazy dog
current value: T, index :19
current value: h, index :7
current value: e, index :4
current value: q, index :16
current value: u, index :20
current value: i, index :8
current value: c, index :2
current value: k, index :10
current value: b, index :1
current value: r, index :17
current value: o, index :14
current value: w, index :22
current value: n, index :13
current value: f, index :5
current value: o, index :14
current value: x, index :23
current value: j, index :9
current value: u, index :20
current value: m, index :12
current value: p, index :15
current value: s, index :18
current value: o, index :14
current value: v, index :21
current value: e, index :4
current value: r, index :17
current value: t, index :19
current value: h, index :7
current value: e, index :4
current value: l, index :11
current value: a, index :0
current value: z, index :25
current value: y, index :24
current value: d, index :3
current value: o, index :14
current value: g, index :6
mark: [Z@70dea4e, length: 26
The Given String is panagram.


References:
https://www.geeksforgeeks.org/pangram-checking/

Read more ...

July 23, 2018

JAVA9: JSHELL (jshell) tool will be a command-line tool

In this article we will discuss about jshell(Java Shell) Java 9 feature. We can explore jShell with JDK 9 Early Access Release.  As of now the general availability of JDK9 is scheduled to 27th July, 2017. The jShell feature is proposed as part of JEP 222. The motivation behind jshell is to provide interactive command line tools to explore the features of java quickly. It is very useful tool to get the glimpse of Java features very quickly for the new learners. Already Java is incorporating functional programming features from Scala. In the same direction they want REPL(Read-Eval-Print Loop) interactive shell for Java as Scala, Ruby, JavaScript, Haskell, Clojure, and Python.

                       The jshell tool will be a command-line tool with features like, a history of statements with editing, tab completion, automatic addition of needed terminal semicolons, and configurable predefined imports.
After downloading the JDK 9, set the PATH variable to access jshell. Now, we will see how to use jshell. Below is the simple program using jshell. We no need to write a class with public static void main(String[] args) method to run simple hello world application.
C:\Users\ABC>jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell> System.out.println("Sayo to jshell!!!");
Say hello to jshell!!!

jshell>
Now we will write method which will add two variables and invoke method via jshell.
jshell> public class Sample {
   ...> public int add(int a, int b) {
   ...> return a+b;
   ...> }
   ...> }
|  created class Sample
jshell> Sample s = new Sample();
s ==> Sample@49993335

jshell> s.add(10,9);
$4 ==> 19
jshell>
Now, we will create a static method with StringBuilder class without importing it, as jshell does that for you.
jshell> public class Sample {
   ...> public static void join() {
   ...> StringBuilder sb = new StringBuilder();
   ...> sb.append("Smart").append(" ").append("Techie");
   ...> System.out.println("Theng is " + sb.toString());
   ...> }
   ...> }
|  created class Sample

jshell> Sample.join();
The string is Smart Techie

jshell>


Read more ...

November 11, 2017

Difference between SLF4J and LOG4J

SLF4J is basically an abstraction layer. It is not a logging implementation. It means that if you're writing a library and you use SLF4J, you can give that library to someone else to use and they can choose which logging implementation to use with SLF4J e.g. log4j or the Java logging API. It helps prevent projects from being dependent on lots of logging APIs just because they use libraries that are dependent on them.
So, to summarise: SLF4J does not replace log4j, they work together. It removes the dependency on log4j from your library/app.
Take a look here: http://www.slf4j.org/, or even here: http://commons.apache.org/logging/ (Apache Commons Logging is similar to SLF4J) for more info on this concept.

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.

If you using SLF4J along with Log4j, if required Log4j can be swapped with another logging framework like Logback without compiling the source code. Logback is the reference implementation for SLF4J.
Read more ...

August 22, 2017

Few java basic understanding interview questions and answers



JVM architecture in Java and the different components of the JVM.

What is the JVM?
Virtual Machine is a software implementation of a physical machine. Java was developed with the concept of WORA (Write Once Run Anywhere), which runs on a VM. Thecompiler compiles the Java file into a Java .class file, then that .class file is input into the JVM, which Loads and executes the class file. Below is a diagram of the Architecture of the JVM.
JVM Architecture Diagram:
How Does the JVM Work?
As shown in the above architecture diagram, the JVM is divided into three main subsystems:
  1. Class Loader Subsystem
  2. Runtime Data Area
  3. Execution Engine
1. Class Loader Subsystem
Java's dynamic class loading functionality is handled by the class loader subsystem. It loads, links. and initializes the class file when it refers to a class for the first time at runtime, not compile time. 
1.1 Loading
Classes will be loaded by this component. Boot Strap class Loader, Extension class Loader, and Application class Loader are the three class loader which will help in achieving it.
  1. Boot Strap ClassLoader – Responsible for loading classes from the bootstrap classpath, nothing but rt.jar. Highest priority will be given to this loader.
  2. Extension ClassLoader – Responsible for loading classes which are inside ext folder (jre\lib).
  3. Application ClassLoader –Responsible for loading Application Level Classpath, path mentioned Environment Variable etc.
The above Class Loaders will follow Delegation Hierarchy Algorithm while loading the class files.
1.2 Linking
  1. Verify – Bytecode verifier will verify whether the generated bytecode is proper or not if verification fails we will get the verification error.
  2. Prepare – For all static variables memory will be allocated and assigned with default values.
  3. Resolve – All symbolic memory references are replaced with the original referencesfrom Method Area.
1.3 Initialization
This is the final phase of Class Loading, here all static variables will be assigned with the original values, and the static block will be executed.
2. Runtime Data Area
The Runtime Data Area is divided into 5 major components:
  1. Method Area – All the class level data will be stored here, including static variables. There is only one method area per JVM, and it is a shared resource.
  2. Heap Area – All the Objects and their corresponding instance variables and arrays will be stored here. There is also one Heap Area per JVM. Since the Method and Heap areas share memory for multiple threads, the data stored is not thread safe.
  3. Stack Area – For every thread, a separate runtime stack will be created. For every method call, one entry will be made in the stack memory which is called as Stack Frame. All local variables will be created in the stack memory. The stack area is thread safe since it is not a shared resource. The Stack Frame is divided into three subentities:
    1. Local Variable Array – Related to the method how many local variables are involved and the corresponding values will be stored here.
    2. Operand stack – If any intermediate operation is required to perform, operand stackacts as runtime workspace to perform the operation.
    3. Frame data – All symbols corresponding to the method is stored here. In the case of any exception, the catch block information will be maintained in the frame data.
  4. PC Registers – Each thread will have separate PC Registers, to hold the address of current executing instruction once the instruction is executed the PC register will be updated with the next instruction.
  5. Native Method stacks – Native Method Stack holds native method information. For every thread, a separate native method stack will be created.
3. Execution Engine
The bytecode which is assigned to the Runtime Data Area will be executed by the Execution Engine. The Execution Engine reads the bytecode and executes it piece by piece.
  1. Interpreter – The interpreter interprets the bytecode faster, but executes slowly. The disadvantage of the interpreter is that when one method is called multiple times, every time a new interpretation is required.
  2. JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter. The Execution Engine will be using the help of the interpreter in converting byte code, but when it finds repeated code it uses the JIT compiler, which compiles the entire bytecode and changes it to native code. This native code will be used directly for repeated method calls, which improve the performance of the system.
    1. Intermediate Code generator – Produces intermediate code
    2. Code Optimizer – Responsible for optimizing the intermediate code generated above
    3. Target Code Generator – Responsible for Generating Machine Code or Native Code
    4. Profiler – A special component, responsible for finding hotspots, i.e. whether the method is called multiple times or not.
  3. Garbage Collector: Collects and removes unreferenced objects. Garbage Collection can be triggered by calling "System.gc()", but the execution is not guaranteed. Garbage collection of the JVM collects the objects that are created.
Java Native Interface (JNI)JNI will be interacting with the Native Method Libraries and provides the Native Libraries required for the Execution Engine.
Native Method Libraries:It is a collection of the Native Libraries which is required for the Execution Engine.


Few of the basic java interview questions:
Language-Fundamentals

Reference website:
Intellipaat
Indiabix
Placement.Freshersworld
JVM-architecture-explained
Read more ...

My Favorite Site's List

#update below script more than 500 posts