Showing posts sorted by relevance for query JAVA. Sort by date Show all posts
Showing posts sorted by relevance for query JAVA. Sort by date Show all posts

Top 7 Java 8 Books

Top 7  Java 8 Books
Java 8 is the most significant release of Java SE in recent years. Its brand-new features and functional style of programming can change the way programmers write Java code fundamentally. Java 8 focuses on the following primarily new features:
  • Lambda Expressions.
  • The Streams API and parallel data processing.
  • New changes to Interfaces and multiple inheritances.
  • The new Date and Time API.
  • The Nashorn Javascript Engine

1. Java SE 8 for the Really Impatient

Java SE 8 ImpatientAuthor: Cay S. Horstmann
Publisher: Addison-Wesley Professional
Published Date: January 24, 2014
Paperback: 240 pages
Read Full Customer Reviews
Content Coverage:
  • Lambdas Expressions
  • The Stream API
  • Programming with Lambdas
  • JavaFX
  • The New Date and Time API
  • Concurrency Enhancements
  • The Nashorn Javascript Engine
  • Miscellaneous Goodies
  • Java 7 Features that You May Have Missed




More information about Java SE 8 for the Really Impatient on Amazon


2. Java 8: The Fundamentals [Kindle Edition]

Java 8 FundamentalsAuthor: Dane Cameron
Publisher: Cisdal Publishing
Published Date: March 15, 2014
File Size: 2247 KB
Read Full Customer Reviews
Content Coverage:
  • Lambda Expressions
  • Streams API
  • Interfaces
  • Java Date and Time API
  • Nashorn








More information about Java 8: The Fundamentals on Amazon


3. Java 8 Lambdas: Pragmatic Functional Programming

Java 8 LambdasAuthor: Richard Warburton
Publisher: O'Reilly Media
Published Date: April 7, 2014
Paperback: 182 pages
Read Full Customer Reviews
Content Coverage:
  • Lambda Expressions
  • Streams
  • Libraries
  • Enhanced Collections and Collectors
  • Data Parallelism
  • Testing, Debugging and Refactoring
  • Design and Architectural Principles
  • Lambda-Enabled Concurrency



More information about Java 8 Lambdas: Pragmatic Functional Programming on Amazon

4. Java 8 Pocket Guide

Java 8 PocketAuthor: Robert Liguori and Patricia Liguori
Publisher: O'Reilly Media
Published Date: April 28, 2014
Paperback: 242 pages
Read Full Customer Reviews
Content Coverage:
  • Part I: Language
    • Naming Conventions
    • Lexical Elements
    • Fundamental Types
    • Reference Types
    • Object-Oriented Programming
    • Statements and Blocks
    • Exception Handling
    • Java Modifiers
  • Part II: Platform
    • Java Platform, Standard Edition
    • Development Basics
    • Memory Management
    • Basic Input and Output
    • New I/O API (NIO.2)
    • Concurrency
    • Java Collections Framework
    • Generics Framework
    • The Java Scripting Framework API
    • Date and Time API
    • Lambda Expressions
  • Part III: Appendixes
    • Fluent APIs
    • Third-Party Tools
    • UML Basics
More information Java 8 Pocket Guide on Amazon


5. Java SE 8 for Programmers

Java SE 8 ProgrammersAuthor: Paul Deitel and Harvey Deitel
Publisher: Prentice Hall
Published Date: April 9, 2014
Paperback: 1104 pages
Read Full Customer Reviews
Content Coverage:
  • Introduction to Java and Test-driving a Java Application
  • Introduction to Java Applications; Input/Output and Operators
  • Introduction to Classes, Objects, Methods and Strings
  • Control Statements: Part 1; Assignment, ++ and -- Operators
  • Control Statements: Part 2; Logical Operators
  • Methods: A Deeper Look
  • Arrays and ArrayLists
  • Classes and Objects: A Deeper Look
  • Object-Oriented Programming: Inheritance
  • Object-Oriented Programming: Polymorphism and Interfaces
  • Exception Handling: A Deeper Look
  • Swing GUI Components: Part 1
  • Graphics and Java 2D
  • Strings, Characters and Regular Expressions
  • Files, Streams and Object Serialization
  • Generic Collections
  • Java SE 8 Lambdas and Streams
  • Generic Classes and Methods
  • Swing GUI Components: Part 2
  • Concurrency
  • Accessing Databases with JDBC
  • JavaFX GUI
  • ATM Case Study, Part 1: Object-Oriented Design with the UML
  • ATM Case Study, Part 2: Implementing an Object-Oriented Design
More information about Java SE 8 for Programmers on Amazon


6. Java 8 New Features: A Practical Heads-Up Guide

Java 8 New FeaturesAuthor: Richard Reese
Publisher: P8tech
Published Date: May 15, 2014
Paperback: 443 pages
File Size (Kindle Edition): 4522 KB
Read Full Customer Reviews
Content Coverage:
  • Chapter 1: Java 8 and Interface Enhancements
  • Chapter 2: Lambda Expressions
  • Chapter 3: Streams
  • Chapter 4: Date and Time
  • Chapter 5: Odds and Ends
  • Appendix: Date and Time Classes
More information about Java 8 New Features on Amazon


7. Java 8 in Action

Java 8 in ActionAuthor: Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft
Publisher: Manning Publications
Published Date: August 28th, 2014
Paperback: 424 pages
Read Full Customer Reviews
Content Coverage:
  • Part I: Fundamentals
    • Java 8: why should you care?
    • Passing code with behavior parameterization
    • Lambda Expressions
  • Part II: Functional-Style Data Processing
    • Processing Data with Streams
    • Collecting Data with Streams
    • Parallel Data Processing and Performance
  • Part III: Effective Java 8 Programming
    • Refactoring, Testing, Debugging
    • Default Methods
    • Optional: A Better Alternative to Null
    • CompletableFuture: composable asynchronous programming
    • New Date and Time API
  • Part IV: Beyond Java 8
    • Thinking Functionally
    • Functional Programming Technique
    • Blending OOP and FP: comparing Java 8 and Scala
    • Conclusions and “where next” for Java

ClassNotFoundException vs. NoClassDefFoundError

ClassNotFoundException vs. NoClassDefFoundError
This is a very common question in Java interviews.

Here we will learn to distinguish between two similar, but different problems that can crop up in your code.

Similarities - 

  • ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime. However, they occur at different scenarios. 

Differences - 

  • ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath. 
  • NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time. 

Let us see some examples -

ClassNotFoundException 

ClassNotFoundException is a runtime exception that is thrown when an application tries to load a class at runtime using the Class.forName() or loadClass() or findSystemClass() methods ,and the class with specified name are not found in the classpath. For example, you may have come across this exception when you try to connect to MySQL or Oracle databases and you have not updated the classpath with required JAR files. Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files. For example, the below program will throw ClassNotFoundException if the mentioned class "oracle.jdbc.driver.OracleDriver" is not found in the classpath.
public class CustomClassNotFoundException

{

    public static void main(String[] args)

    {

        try

        {

            Class.forName("oracle.jdbc.driver.OracleDriver");

        }catch (ClassNotFoundException e)

        {

            e.printStackTrace();

        }

    }

}

If you run the above program without updating the classpath with required JAR files, you will get an exception like:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

at java.net.URLClassLoader.findClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName(Unknown Source)

at pack1.CustomClassNotFoundException.main(CustomClassNotFoundException.java:17)

NoClassDefFoundError 

NoClassDefFoundError is an error that is thrown when the Java Runtime System tries to load the definition of a class, and that class definition is no longer available. The required class definition was present at compile time, but it was missing at runtime. For example, compile the program below.
class A

{

  // some code

}

public class B

{

    public static void main(String[] args)

    {

        A a = new A();

    }

}

When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:
Exception in thread "main" java.lang.NoClassDefFoundError: A

at A.main(A.java:10)

Caused by: java.lang.ClassNotFoundException: A

at java.net.URLClassLoader.findClass(URLClassLoader.java:381)

at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)

at java.lang.ClassLoader.loadClass(ClassLoader.java:357)


Recap

ClassNotFoundException
NoClassDefFoundError
It is an exception. It is of type java.lang.Exception.
It is an error. It is of type java.lang.Error.
It occurs when an application tries to load a class at run time which is not updated in the classpath.
It occurs when java runtime system doesn't find a class definition, which is present at compile time, but missing at run time.
It is thrown by the application itself. It is thrown by the methods like Class.forName(), loadClass() and findSystemClass().
It is thrown by the Java Runtime System.
It occurs when classpath is not updated with required JAR files.
It occurs when required class definition is missing at runtime.

Step by step JDK installaiton guide in Redhat linux

Step by step JDK installaiton guide in Redhat linux

JDK 1.6 Installation:

Step 1:

Download: jdk-6u7-linux-x64-rpm.bin from java.sun.com

Step 2:

Run the bin file from terminal. It will install java version "1.6.0_07".

Step 3:

Remove java from var/lib/alternatives

rm /var/lib/alternatives/java

Step 4:

Change to Root folder

cd /root

Now Java Version command will show the Java which is installed by default with CentOS

java -version

Result:

java version "1.4.2"

gij (GNU libgcj) version 4.1.2 20071124 (Red Hat 4.1.2-42)

Step 5:

Add both Java Version 1.4.2 and Java 1.6.0_07 entries using alternatives command

/usr/sbin/alternatives --install /usr/bin/java java /usr/lib/jvm/jre-1.4.2-gcj/bin/java 1

/usr/sbin/alternatives --install /usr/bin/java java /usr/java/jdk1.6.0_07/bin/java 2

Make jdk1.6.0 as default java version.

/usr/sbin/alternatives --config java

How to iterate Map in Java

In next section of this Java tutorial we will see what all possible ways, to iterate map
For Example


HashMap<String, String> creditCardMap = new HashMap<String, String>();
creditCardMap .put<"silver", "citibank");
creditCardMap .put<"gold", "Wells Fargo");

Here will see, what all possible ways to itereate loop

  • Iterate Map using forEach - (Java 5)
  • Iterating Map KeySet Iterator
  • Iterate HashMap in using EntrySet and forEach
  • Iterating HashMap using EntrySet and Java iterator

 

Iterate Map using forEach - (Java 5):

Here we will use new foreach loop introduced in JDK5 for iterating over any map in java and using KeySet of map for getting keys. this will iterate through all values of Map and display key and value together.


HashMap<String, String> creditCardMap = new HashMap<String, String>();
creditCardMap.put("silver", "citibank");
creditCardMap.put("gold", "Wells Fargo");

for (String key : creditCardMap.keySet()) {
System.out.println("------------------------------------------------");
System.out.println("Iterating or looping map using java5 foreach loop");
System.out.println("key: " + key + " value: " + creditCardMap.get(key));
}

Output:
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: silver value: citibank
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: gold: Wells Fargo

 

Iterating Map KeySet Iterator:
In this Example of looping hashmap in Java we have used Java Iterator instead of for loop, rest are similar to earlier example of looping:


Set<String> keySet = creditCardMap.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
System.out.println("------------------------------------------------");
System.out.println("Iterating Map in Java using KeySet Iterator");
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + creditCardMap.get(key));
}

Output:
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: silver value: citibank
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: gold: Wells Fargo


Iterate HashMap in using EntrySet and forEach
In this Example of traversing Map in Java, we have used EntrySet instead of KeySet. EntrySet is a collection of all Map Entries and contains both Key and Value.


Set<Map.Entry<String, String>> entrySet = creditCardMap.entrySet();
for (Entry entry : entrySet) {
System.out.println("------------------------------------------------");
System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

output:
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: silver value: citibank
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: gold: Wells Fargo

Iterating HashMap using EntrySet and Java iterator
This is the fourth and last example of looping Map and here we have used Combination of Iterator and EntrySet to display all keys and values of a Java Map.


Set<Map.Entry<String, String>> entrySet1 = loans.entrySet();
Iterator<Entry<String, String>> entrySetIterator = entrySet1.iterator();
while (entrySetIterator.hasNext()) {
System.out.println("------------------------------------------------");
System.out.println("Iterating HashMap in Java using EntrySet and Java iterator");
Entry entry = entrySetIterator.next();
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

ourpur:

===========
Iterating or looping map using java5 foreach looop
key: silver value: citibank
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: gold: Wells Fargo


Vijay D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Thulasiram P

Follow Me @Google+

Introduction to Java Annotations

Introduction to Java Annotations
Annotations:
It provides information about program, and it is not part of program , so it won?t affect execution.
Uses of Annotations:
Basically annotations are used in many tools to know the information about program. Here I am going to list out few examples
  • Compiler uses annotations to detect errors and warnings.

  • Software tools uses annotation information to generate code, XML..etc

  • Some annotation are available to be examined runtime.

Java annotations also called as meta data. It is introduced in JDK 1.5 onwords. Before we write basic annotations, we need to understand about the following
  • How to create custom basic annotations

  • How to use annotations in Java Application


How to write custom Basic annotation:
Annotation is created by using @ sign followed by keyword interface.
Syntax:


Rules:
  • Annotation supports to declare using public and default.

  • Annotation methods can?t have parameters.

  • Annotation methods return types are limited to primitives, String, Enums, Annotation or array of these.

  • Annotation methods can have default values.

  • Annotations by default extends with java.lang.annotation.Annotation interface.

  • Annotations can?t include any extend clause.

How to use annotations in Java Application:
  • Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements.

  • Each annotation often appears, by convention, on its own line.


Java supports two types of annotations
  • Regular Annotations:

  • Are applied to regular java classes, methods, statements.
  • Meta Annotations

  • Are applied to annotation definitions to describe the behavior of the annotation being declared and how it
    can be used.

Predefined Annotations in Java
@Deprecated, is used to tell the developer that a function
shouldn't be used anymore. It generally means that in a later
version of the code, that function will go away. When a developer does use this function, the compiler will warn the developer about this.
@Override tells the compiler that you intend to have a function override the parent's version of it. If there is a typo, the compiler knows there's a problem and will throw an error.
@Override also tells the developer that this code is overriding a parent's version. Easier to read than a non existent
comment to the same effect.
@SuppressWarnings@SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.
In the following example, a deprecated method is used, and the compiler usually generates a warning. In this case, however,
the annotation causes the warning to be suppressed.
// use a deprecated method and tell 
   // compiler not to generate a warning
   @SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
        // deprecation warning
        // - suppressed
        objectOne.deprecatedMethod();
    }
@SafeVarargs @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe
operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
@FunctionalInterface @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be
a functional interface, as defined by the Java Language Specification.

Deployment Error in starting Jboss 5.1 GA

Deployment Error in starting Jboss 5.1 GA
Issue:
Failed to boot JBoss:
java.lang.IllegalStateException: Incompletely deployed:

DEPLOYMENTS IN ERROR:
  Deployment "AttachmentStore" is in error due to: java.lang.IllegalArgumentExce
ption: Wrong arguments. new for target java.lang.reflect.Constructor expected=[j
ava.net.URI] actual=[java.io.File]

DEPLOYMENTS MISSING DEPENDENCIES:
  Deployment "ProfileServicePersistenceDeployer" is missing the following depend
encies:
    Dependency "AttachmentStore" (should be in state "Installed", but is actuall
y in state "**ERROR**")
  Deployment "ProfileServiceDeployer" is missing the following dependencies:
    Dependency "AttachmentStore" (should be in state "Installed", but is actuall
y in state "**ERROR**")
  Deployment "ProfileService" is missing the following dependencies:
    Dependency "jboss.kernel:service=KernelController" (should be in state "Inst
alled", but is actually in state "**ERROR**")
    Dependency "ProfileServiceDeployer" (should be in state "Installed", but is
actually in state "Instantiated")
  Deployment "ProfileServiceBootstrap" is missing the following dependencies:
    Dependency "jboss.kernel:service=Kernel" (should be in state "Installed", bu
t is actually in state "**ERROR**")
    Dependency "ProfileService" (should be in state "Installed", but is actually
 in state "Instantiated")

        at org.jboss.kernel.plugins.deployment.AbstractKernelDeployer.internalVa
lidate(AbstractKernelDeployer.java:278)
        at org.jboss.kernel.plugins.deployment.AbstractKernelDeployer.validate(A
bstractKernelDeployer.java:174)
        at org.jboss.bootstrap.microcontainer.ServerImpl.doStart(ServerImpl.java
:142)
        at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:
450)
        at org.jboss.Main.boot(Main.java:221)
        at org.jboss.Main$1.run(Main.java:556)
        at java.lang.Thread.run(Thread.java:722)
13:26:32,312 INFO  [ServerImpl] Runtime shutdown hook called, forceHalt: true
13:26:32,315 INFO  [ServerImpl] Shutdown complete
Environment:
  • OS: Windows 7
  • JDK:java version "1.7.0_51"
  • JBOSS: Jboss 5.1 GA
Resolution:
  • Navigate \server\default\conf\bootstrap\profile.xml
  • Search "AttachmentStore" in profile.xml file
  • Add new class parameter inside tag
       
       
    Before:
       
     
    
      
      
      
     
       
    After:
       
     
    
      
      
      
     
       
  • Save profile.xml.
  • Start JBoss service
      \bin>run.bat all
     
  • Verify JBoss services on Jboss web console.
    http://localhost:8080/web-console/

Top 20 collection framework interview questions and answers in java

Top 20 collection framework interview questions and answers in java

1.Why Map interface doesn’t extend Collection interface?

  • Set is unordered collection and does not allows duplicate elements.
  • List is ordered collection allows duplicate elements.
  • Where as Map is key-value pair.
  • It is viewed as set of keys and collection of values.
  • Map is a collection of key value pairs so by design they separated from collection interface.

 

 

2.What is difference between HashMap and Hashtable?

  • Synchronization or Thread Safe 
  • Null keys and null values 
  • Iterating the values 
  •  Default Capacity

    3.Differences between comparable and comparator?

    • Comparable Interface is actually from java.lang package.
    • It will have a method compareTo(Object obj)to sort objects
    • Comparator Interface is actually from java.util package.
    • It will have a method compare(Object obj1, Object obj2)to sort objects

    4.How can we sort a list of Objects?

    •  To sort the array of objects we will use  Arrays.sort() method.
    • If we need to sort collection of object we will use Collections.sort().

     

    5.What is difference between fail-fast and fail-safe?

    • Fail fast is nothing but immediately report any failure. whenever a problem occurs fail fast system fails. 
    • in java Fail fast iterator while iterating through collection of objects sometimes concurrent modification exception will come there are two reasons for this.
    • If one thread is iterating a collection and another thread trying to modify the collection.
    • And after remove() method call if we try to modify collection object

     

    6. What is difference between Iterator ,ListIterator and Enumeration?

    • Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
    • Enumeration uses elements() method.
    • Iterator is implemented on all Java collection classes.
    • Iterator uses iterator() method.
    • Iterator can traverse in forward direction only.
    • ListIterator is implemented only for List type classes
    • ListIterator uses listIterator() method.

    7.What is difference between Set and List in Java?

    • A set is a collection that allows unique elements.
    • Set having no index.
    • Set allows only one null value.
    • Set having classes like :
    • HashSet
    • LinkedHashMap
    • TreeSet
    • List having index.
    • List allows n number of null values.
    • List will display Insertion order with index.
    • List having classes like :
    • Vector
    • ArrayList
    • LinkedList

    8.Differences between arraylist and vector?

    • Vector was introduced in  first version of java . that's the reason only vector is legacy class.
    • ArrayList was introduced in java version1.2, as part of java collections framework.
    • Vector is  synchronized. 
    • ArrayList is not synchronized.

    9.What are the classes implementing List interface?

    • ArrayList     
    • LinkedList     
    • Vector

    10. Which all classes implement Set interface ?

    • HashSet
    • LinkedHashSet
    • TreeSet

    11.How to make a collection thread safe?

    • Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment.
    • By using Collections.synchronizedList(list)) we can make list classes thread safe.
    • By using 
      java.util.Collections.synchronizedSet()  we can make set classes thread safe.

    12.Can a null element added to a TreeSet or HashSet?

    • One null element can be added to hashset.
    • TreeSet also allow null value once.

    13. Explain Collection’s interface hierarchy?

     

    14.Which design pattern Iterator follows?

    • Iterator design pattern

    15.Which data structure HashSet implements

    • Hashset implements hashmap internally.

    16.Why doesn't Collection extend Cloneable and Serializable?

    • List and Set and queue extends Collection interface.
    • SortedMap extends Map interface.

    17.What is the importance of hashCode() and equals() methods? How they are used in Java?

    • equals() and hashcode() methods defined in "object" class. 
    • If equals() method return true on comparing two objects then hashcode() of those two objects must be same.

    18.What is difference between array & arraylist?

    • Array is collection of similar type of objects and fixed in size.
    • Arraylist is collection of homogeneous and heterogeneous elements.

    19.What is the Properties class?

    • Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key and the value is String.

    20.How to convert a string array to arraylist?

    • Using arrayList.toArray();