Thursday, 15 December 2016

Common Interview questions for Java Developer


Tell me about yourself?
Tell me about your project?

What are the different features of oops?
What is Design Pattern? Describe some design patterns with example.
What is singelton Class? Write a code for it.
What is dynamic polymorphism? Write a code for explanation.
What is reflection mechanism in java?
What is CompiletimeException/CheckException and RuntimeException/UncheckedException?
What is static binding/Early binding and dynamic binding/late binding? Show by code.
What is the difference between ArrayList and LinkedList?
(mainly during insertion, deletion or traverse which is more used)
What are the new features Java7 & Java8?
What are the uses of marker interface? What are the different types avaialable for marker interface ?
What are the different type of cloning u used and when ?
What are the different way to create a thread object? write a code to create it.
What are Association, aggregation and composition in Java?
What are differences available for abstract classes and interface?
What is Deadlock,startvation and inter thread communication in java?
What are differences available for HashMap & HashTable?
What is the difference between synchronized block and synchronized method?
What is fail safe and fail fast?
Have you used any static code analysis tools?
Have static code analysis tools will improve performance? (JLint, Sonar and CheckStyle)
Have you done remote debugging? What is your debugging strategy if a production issue come?
What are the uses of volatile and transient variables in java?
What are the differences between differences ways of creating String object?
What are the different ways for garbage collection?
What are the differences between heap and stack memory?
What is the difference between Comparable and Comparator interface?


How HashMap internally works?
How can you sort the employee object on the basis of thier salary ?
How HashSet internally uses HashMap?
How Map & set being iterated?
How can you handle exception during method overriding?
How can you implement your own LinkedList/HashMap in java?
How can i reverse the one array using same array only?
How can i find the duplicate numbers available in any array ?
How can i sort one array using single iteration?
How can i found the 2nd highest number from an array in single iteration?
How will you manage producer and consumer problems? How can you prevent deadlock in java?
How dead lock is different from race conditions
How do you improve performance of an application?
How conscious you were with security issues while coding?
How a bad program can cause security threat?
How can i throw or catch an exception?
how to find that is there is any consecutive repeating characters within a string?
How and which sort algorithm you would use for sorting a char array?
How bitly shortens the URLs ?
How do you delete a node in Binary Search Tree?
How to write a code that causes deadlock?
How would you implement your own thread pool in java?

Thursday, 8 December 2016

Angular JS Frequently asked questions

What is the difference between ng-show and ng-if ?

what are the different ways to share the data across multiple controllers ?

What are difference between controller and directives ?

What are the best features so we love to use angular apart from other js framework ?

What is difference between filter and service ?

What are the different type of scope you used inside angular ?

What is promise, watch, digest, apply, timeout and $q inside angular ?

What are the use of route & state in angular ?

can i use 2 different module inside same application ?

What Single page application means actually for which i'm using angular js ?

What is the difference between $scope and $rootScope ?

How we can write success & error within $http call to communicate within any methods ?

What is the difference between ng-paginate and ng-repeat ?

What is the difference when using ng-click and anchor href ?

What are the uses of restrict in angular js and how many types of restriction are in use ?

when we use query param to share data between multiple controller ?

Wednesday, 7 December 2016

Important Differences available inside Collection Frameworks











Most Frequently used Java Questions

http://howtodoinjava.com/core-java/interviews-questions/real-java-interview-questions-asked-for-oracle-enterprise-manager-project/

1)  What is abstraction and encapsulation in java ?

2)  What is method overloading rules? Can we overload the super class method in sub class?                     Discussion happened with the example.

3)  What is method overriding rules?

4)  What is widening and narrowing in java? discussion happened with example?

5)  Can I have only try block in code?

6)  Threads : producer and consumer problem?

7)  Why wait(), notify() and notifyAll() are defined in Object class?

8)  Can we override wait() or notify() methods?

9)  Difference between wait(), sleep() and yield()?

10) Explain about join() method in thread class

11) Have you faced out of memory error? If yes how you fixed ? Tell different scenarios why it
      comes?

12) Database connection leakage?

13) To avoid this extra overhead every time, double checked locking principle is used what is that ??

14) What is Java Singleton Pattern ?? how are the different way to create a singleton class either by            thread safe or non thread safe ??
http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples

15) Rules of Exceptions during Method Overriding & Overloading
http://www.javatpoint.com/exception-handling-with-method-overriding

16) How to get data from HashMap & HashSet?

17) I have two arrays which contains integer. Write a program to merge those two arrays and remove       duplicate elements? At the end, I need one array which should have unique elements?

18) Write a program on Singleton?

19) Write a program to sort an array and remove duplicates?

20) Write a program to fetch the data from a table using JDBC and result set?

21) What happens if i write return in try block? Will finally executes? What happens if write                      system.exit(), will finally block executes?

22) Different type of design patterns used before ?
http://www.vogella.com/tutorials/DesignPatterns/article.html
http://www.java67.com/2012/09/top-10-java-design-pattern-interview-question-answer.html

23)  Can you override a private or static method in Java?

24) What will happen if we put a key object in a HashMap which is already there?

25) If a method throws NullPointerException in the superclass, can we override it with a method               which throws RuntimeException?

26) Difference between compareTo and compare in java

27) How do you ensure that N thread can access N resources without deadlock?

28) What is the difference between StringBuffer and StringBuilder in Java?

29) Can you access a non-static variable in the static context?

30) is it possible to load a class by two ClassLoader?

31) is it possible for equals() to return false, even if contents of two Objects are same?

32) How does "has before" apply to volatile work?

33) What happens when an exception is thrown by a Thread?

34) Difference between System.exit() and System.halt() method?

35) difference between BLOB and CLOB

36) Why character array is better than String for Storing password in Java?

37) How to create a thread-safe singleton in Java using double-checked locking?

38) Write Java program to create a deadlock in Java and fix it ?

39) Why is String immutable in Java?

40) Why does Java not support operator overloading ?

41) Why is multiple inheritances not supported in Java ?

42) Why wait and notify is declared in Object class instead of Thread ?

43) What happens if your Serializable class contains a member which is not  serializable? How do              you fix it?

44) Why wait and notify  called from synchronized method in Java?

45) Why does Java not support operator overloading ?

46) Why is multiple inheritances not supported in Java ?

47) Can we overload a static method in Java?

48) Can we override a static method in Java?

49) Can we prevent overriding a method without using the final modifier?

50) Can we override a private method in Java?

51) What is covariant method overriding in Java?

52) Can we change the return type of method to subclass while overriding?

53) Can we change the argument list of an overriding method?

54) Can we override a method which throws runtime exception without throws clause?

55) How do you call superclass version of an overriding method in sub class?

56) Can we override a non-static method as static in Java?

57) Can we override the final method in Java?

58) Can we have a non-abstract method inside interface?

59) What is the default method of Java 8?

60) Can we make a class both final and abstract at the same time?

61) Can we overload or override the main method in Java?

62) What is the difference between Association, Aggregation, and Composition in OOP?

63) What problem is solved by Strategy pattern in Java?

64) Which OOP concept Decorator design Pattern is based upon?

65) What is the difference between Decorator, Proxy and Adapter pattern in Java?

66) Consider the following Java code snippet,

which is initializing two variables and both are not volatile, and two threads T1 and T2 are modifying these values as following, both are not synchronized
int x = 0;
boolean bExit = false;

Thread 1 (not synchronized)
x = 1;
bExit = true;

Thread 2 (not synchronized)
if (bExit == true)
System.out.println("x=" + x);
Now tell us, is it possible for Thread 2 to print “x=0”?

Answer: It's impossible for a list of tricky Java questions to not contain anything from multi-threading. This is the simplest one I can get. Answer of this question is Yes, It's possible that thread T2 may print x=0.Why? because without any instruction to compiler e.g. synchronized or volatile, bExit=true might come before x=1 in compiler reordering. Also, x=1 might not become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it?

 When I asked this question to a couple of programmers they answer differently, one suggests to make both threads synchronized on a common mutex, another one said make both variable volatile. Both are correct, as it will prevent reordering and guarantee visibility.

But the best answer is you just need to make bExit as volatile, then Thread 2 can only print “x=1”. x does not need to be volatile because x cannot be reordered to come after bExit=true when bExit is volatile.

WebLogic : The Application Server

1). If an administration server running machine got crashed, how will you restart the server with same configuration on new machine?

    • Oracle WebLogic Server allows the creation of a backup of the server as follows:
      • Install Oracle WebLogic Server on a backup machine.
      • Copy the application files to a backup machine.
      • Copy the configuration files to a backup machine.
      • Restart the Administration Server on a new machine.
    • The new Administration Server contacts the Managed Servers and informs them that it is running on a new IP address.
  • similarly we can also create a backup for tomcat as well, These ways you follow:
                   /tomcat/config
                   /tomcat/webapps
                   Also note down the version of tomcat you use. 
                   In webapps if you use war files, it should be sufficient to backup only all war files.
                   On restore install tomcat of same version, then copy above folders from backup 
                    (replacing files like server.xml)
                   Please test this setup on a test server. But in short this is all you need.
                   Don't forget the tomcat native in tomcat/bin

2). How can you run Multiple Weblogic server instances in a same physical machine?
    • You can run multiple instances of WLS using different configurations on the same physical machine at the same time by either:
      • Assigning multiple IP addresses to a machine (multihoming) and defining each server to use a unique IP address
      • Specifying the same IP address but using different listen ports
    • A multihomed machine:
      • Is a machine with multiple IP addresses
      • Can run a different WLS instance that is bound to each IP address
      • Can be used to configure a cluster on a single machine
    • In Tomcat, it is also possible to achieve by changing the http, https, ajp and shutdown ports.
3). How will you create Domain Template? Explain briefly?
    • A domain template defines the full set of resources within a domain.
    • Oracle provides sample templates for creating any platform domain.
    • There are three ways to create domain templates:
      • WLST offline command line tool
      • pack command
      • Domain Template Builder (config_builder.sh under WL_HOME/common/bin)
    • Use the Domain Template Builder to create a domain template or an extension template.
    • Using the Domain Template Builder:
      • Define a domain and replicate it across multiple projects
      • Distribute a domain packed with an application that has been developed to run in it
    • A template provides configuration information and files to support a feature or application on a tc Runtime instance. The built-in templates that ship with tc Server make it simple to configure tc Runtime features such as SSL or JMX or to add a management application to an instance at creation time, such as Spring Insight. You can create your own templates by creating a subdirectory in the templates directory of your tc Server installation directory and populating it with files accordingly.
4). What are the default Weblogic provided Groups for security realm?
  • Administrators
  • Deployers
  • Operators
  • Monitors
  • AppTesters
  • CrossDomainConnectors
  • AdminChannelUsers
5). What are the default Weblogic provided Roles for security realm?
  • Admin
  • Deployer
  • Operator
  • Monitor
  • AppTester
  • CrossDomainConnectors
  • AdminChannelUsers
  • Anonymous
6). What is the default Weblogic provided domain template file name and location?
  • Wls.jar is the default domain template and the location is
  • WL_HOMEcommontemplatesdomains
7).What are the elements of the Administration console?
  • Change Center
  • Domain Structure
  • How do I…
  • Tool Bar
  • Breadcrumb Navigation
  • System Status
8). What are the Node elements of the Administration console or Domain Structure?
  • Environment (Servers, Clusters, Virtual Hosts, Migratable Targets,  Machines …)
  • Deployment
  • Services (Messaging, JDBC, Persistent Store, JTA, File T3, jCOM …)
  • Security Realms
  • Interoperability
  • Diagnostics (Log Files, Diagnostics Modules, Diagnostics Images, Archives, Context)
9). What are the Tool Bar elements in Weblogic?
  • Welcome Message
  • Connected to
  • Home
  • Log Out
  • Preferences
  • Record
  • Help
  • Search
10). How will you enable the Administration Console?
By default, the Administration Console is enabled. If you disable it, you can re-enable it using the WebLogic Scripting Tool (WLST).
Start the Administration Server, then invoke WLST and use the following commands:
Using WLST to Re-enable the Console 
connect(“username”,”password”)
edit()
startEdit()
cmo.setConsoleEnabled(true)
save()
activate()
The following attribute(s) have been changed on MBeans which require server re-start.MBean Changed : com.bea:Name=mydomain,Type=Domain Attributes changed : 
ConsoleEnabled
Activation complete
ddisconnect()
exit()

http://interviewquestionsanswerspdf.com/2014/03/weblogic-interview-questions-and-answers/

Sunday, 24 April 2016

How to iterate JSON file from child node (tags.Component) and finding their parent nodes (resources name & attributes) ???

package com.codingmania.Resource;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.MissingNode;

import com.codingmania.model.Component;
import com.codingmania.model.Resource;

public class MainResource
{
public static void main(String[] args) throws JsonProcessingException, IOException
{

JsonNode root,moduleNode,resourceNode,instanceNode,primaryNode,attributesNode,jsonValue=null;
ObjectMapper mapper = new ObjectMapper();
List<JsonNode> list = new ArrayList<JsonNode>();

root = mapper.readTree(new File("src/main/resources/terraform.json"));

Map<String, Component> coMap = new HashMap<String, Component>();

moduleNode = root.path("modules");

   System.out.println("-------tag.Component parsing start-------");
 
   for (JsonNode node : moduleNode)
    {
    resourceNode = node.get("resources");
 
    Iterator<String> itr = resourceNode.getFieldNames();
    while (itr.hasNext())
    {
    String resourceName = itr.next();
    instanceNode = resourceNode.path(resourceName);
   
    primaryNode = instanceNode.path("primary");
        System.out.println(primaryNode);

         attributesNode = primaryNode.path("attributes");
       
         jsonValue = attributesNode.path("tags.Component");
 if(jsonValue instanceof MissingNode)
 {
 list.remove(jsonValue);
 }else{
 String componentName = jsonValue.toString();
 componentName = componentName.replace("\"", "");
 Component component = coMap.get(componentName);
 if(component==null){
 component = new Component();
 component.setName(componentName);
 coMap.put(componentName, component);
 }

 Resource r  = new Resource();
 component.addResource(r);
 r.setName(resourceName);
 r.setType(instanceNode.get("type").getTextValue());
 r.setId(primaryNode.get("id").getTextValue());
 Iterator<String> fieldNames = attributesNode.getFieldNames();
 while (fieldNames.hasNext()) {
 String key = fieldNames.next();
 String value = attributesNode.get(key).getTextValue();
 r.addAttribute(key, value);
 }

}
 }

       
    }  

    System.out.println(mapper.writeValueAsString(coMap));
    }  
}
========================= Component.java  =============================
package com.codingmania.model;

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

public class Component {
String name;
List<Resource> resources;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


public List<Resource> getResources() {
return resources;
}

public void setResources(List<Resource> resources) {
this.resources = resources;
}

public void addResource(Resource r) {
if(resources == null){
resources = new ArrayList<>();
}
resources.add(r);

}
}
=======================  Resource.java  =================================
package com.codingmania.model;

import java.util.HashMap;
import java.util.Map;

public class Resource {
String name;
String type;
String id;
Map<String, String> attributes;


public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public Map<String, String> getAttributes() {
return attributes;
}


public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}

public void addAttribute(String key, String value) {
if(attributes == null){
attributes =new HashMap<>();
}
attributes.put(key, value);
}
}
-----------------------------------  terraform.json  -----------------------------------------------

For further requirements, please contact me on 8237976501 due to security reasons.

10 Vital Persons in Our Technologies, you should know at least, when you belong to Java Technologies.

Java Founder                               - James Gosling

Hibernate Founder                      - Gavin King

Spring Founder                           - Rod Jhonson

Struts Founder                             - Craig Mcclanahan

Jboss Founder                              - Marc Fleury

JUnit Founder                              - Kent Beck

JSON                                            - Douglas Crockford

REST WEB SERVICES               - Roy Thomas Fielding

Tomcat & Ant Founder                 - James Duncan Davidson

Collection Frameworks Founder     - Joshua Bloch


Saturday, 23 April 2016

What is yeoman, bower and grunt & How it works with angularjs ??

*** Yeoman is a collection of three tools - called Yo, Grunt, and Bower - that allow developers to concentrate on building the functionality of an application, rather than working to build its infrastructure.

*** Yo handles scaffolding of the application, while Grunt takes care of build processes and Bower manages the application's dependencies.

During development, these tools will do things like create the development environment, automatically reload the browser when changes are saved, handle notification for Angular apps, and make sure packages are up-to-date. When it comes time to deploy, they'll minify all of the app's code, optimize images, compile CoffeeScript and Compass files, and package the app for distribution.

Yeoman is a tool that provides a great starting point for building apps in all kinds of different frameworks. Because it includes so many frameworks each community maintains their respective generator and the generator will follow those sets of best practices. The one for Angular uses Bower for dependencies and grunt for tasks. It will also include Karma etc.

Yeoman can also run your unit tests, minimize and concatenate your code, optimize images etc.

Yeoman can fire up a preview web server and watch your files for edits in order to live reload changes and compile your Sass.

*** Bower is a package manager for front-end modules that are usually comprised of JavaScript and/or CSS.

Bower assumes for easily search for, install, update, or remove these front-end dependencies.

The advantage to using Bower is that you do not have to bundle external dependencies with your project when you distribute it. Bower will take care of the third-party code when you run bower install and get those dependencies to the right locations. It also makes the final project package smaller for distribution.

Bower is a package manager for the web.

*** Grunt is used to build, preview, and test your project.

Grunt is a great tool for automating many things in our applications. From minifying files, processing LESS, linting our JS files, and so much more.

it is just easier to have Grunt start and watch our Node server for changes, process those changes/run tasks, and keep our restart our server for us.

We don’t have to run separate Grunt and node (or nodemon) commands and having just telling people to run grunt is simple enough.


How to install these all terms, which i discussed above through terminal
---------------------------------------------------------------------------------------

npm install -g yo grunt-cli bower    (-g gor globally installation)

npm install -g generator-angular

yo angular

bower install

npm install - for fetching all dependencies from bower.json and all

npm start  -- for starting grunt server.

grunt serve

======================================================
Write these command before any installation to take an updated version and all

sudo apt-get update
sudo apt-get update-all
sudo apt-get upgrade
sudo apt-get upgrade-all

Basic Description on angularjs controller, directive and services.

Controllers
========

So what is a Controller in angularjs ?

A Controller is an object that’s responsible for managing other objects. What that means is, the Controller doesn’t actually know the specifics about an object, like a Book for example.

The Controller doesn’t know how many pages a Book has, who its author is or what its called, but it knows how to get a Book, how to ask it for its name or how to pass it to a View so it can be read.

If you’re just getting started with AngularJS and Model-View-Controller architecture in general just remember that if your application has an object like a Book, chances are it will have a BooksController.

So for this simple application I want to ultimately display some weather for a specific city. So right away I know I am going to need to create a WeatherController to manage the Weather we request! Let’s do that now.

Go ahead and add another file to your application. Name this file app.js and update the markup in the html file you created earlier to include it:

<html>
    <head>
        <title>My First Angular App!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body>
    </body>
</html>

I also added a script tag that includes the angularjs file directly from a Google CDN. Why download it? If you save this file and load it in a browser, you won’t see anything.
but you should be able to open up the developer console and type angular. This will return an object and you shouldn’t see any errors.

----------------------  angular                            write this on console, you got error.

Before we make our Controller, we are going to have to make a top level module for it to live in. AngularJS projects are built around modules, so we will make one next. Open app.js and add the following code:

angular.module('weatherApp', []);

Save and refresh your html page. Take a look at the developer console. You shouldn’t have any errors and you should be able to retrieve your angular app by typing the following:

----------------------  angular.module('weatherApp')       write this on console, you got no error.


Did you see the subtle difference there in Syntax? When you create a module, you add the square brackets [ ] but when you retrieve one, you don’t. This can trip you up when you’re getting started with AngularJS. So be careful. What are the brackets for? For including other modules!


Ok, so now we are going to add our Controller (finally!). I’m going to just add it to app.js. In a production application you would likely use the return value from this module statement and have other files that had the code for your controllers, services, and directives, but I’m gonna keep it simple for now.

Here’s how you go ahead and add your first AngularJS Controller!


angular.module('weatherApp', [])
  .controller("weatherController", function() {
    console.log('weather controller created!');
  });

There’s another small thing to notice here – I took the semicolon off the first line and chained the controller declaration after the module declaration. I added a simple console.log statement to let us know that the controller has been loaded on the page. So let’s check that now.

Save and refresh your page. Nothing. That’s because we haven’t actually included that weatherApp module we created onto the page, to do that we need a directive!


Directives
========

Directives are simply custom html attributes that AngularJS knows what to do with. The browser will ignore them and Angular will use them. They are that simple. I know they are SO much more, but we are learning, and for the sake of getting started with Angular. That’s all you need to know for now. So let’s tell Angular to load our app. We do that by using a built-in directive named ng-app. Its common to put that on the HTML tag at the top of you page. Let’s do that now:


<html ng-app="weatherApp">
    <head>
        <title>My First Angular App!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body>
    </body>
</html>


So again, if you save and refresh your page. Nothing. Ok, here’s the deal. We have told Angular about our app and Angular has in fact loaded it. If you don’t believe me go ahead and change the ng-app declaration from: ng-app=”weatherApp” to ng-app=”weatherApp1″. When you save and refresh the page you will see a horrible error message (get used to it – that’s one of the things that drives me nuts about Angular is the horrible error messages). Change the ng-app back and make sure you aren’t getting any errors. Now you believe me that the app was loaded, but where was that console statement? Well, we didn’t create the controller. Let’s go ahead and do that now. With another built-in directive named ng-controller!

Add ng-controller to the body tag:


<html ng-app="weatherApp">
    <head>
        <title>My First Angular App!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body ng-controller="weatherController">
    </body>
</html>

Now if you save and refresh the page… you see the console message! Now that we have a controller there is a ton of cool stuff we can do. The first is to start using the scope and binding data to our html elements.


Data binding and scope
=================

If you’ve done any jQuery before, you’ve probably written something like this:

$("p.description").text("Here is some text!");

This is simply finding a p tag with a class of description and binding the text Here is some text! inside it. It works, and its served us well. However, what can happen is this kind of code can be nested deep in a very large javascript application and the p tag, well it just has a class of description. We don’t know that this code is going to drive by and throw a value in it. It can be hard to trace back why some elements behave the way they do on a page. Imagine if this p tag didn’t even have a class of description. It was just a p tag! This is where declarative programming and data binding comes in.

In Angular we actually declare what we are binding to an element, it makes it much easier to understand what markup is going to be affected by our code and what the intention of the original developer was. So let’s go ahead and add a p tag to our webpage and write out a brief description of our app using Angular declarative programming:


<html ng-app="weatherApp">
    <head>
        <title>My First Angular App!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body ng-controller="weatherController">
        <p ng-bind="description"></p>
    </body>
</html>

You know the drill. Save and refresh. Nothing. Don’t hate me. The reason is because Angular looked in the current scope of the directive (in this case the ng-controller named weatherController) and found nothing. So, you got nothing. Let’s go into our controller and add the description variable to the scope now:

angular.module('weatherApp', [])
  .controller("weatherController", function($scope) {
    $scope.description = "a simple weather app";
  });

There are two changes to notice here. First, we added a parameter to the constructor function of our controller named $scope. Second, we used that parameter as an object and added our description variable onto it. We gave it a simple value of: a simple weather app. What was that $scope parameter we passed to our constructor function? Well it was basically a service that gave us access to the current scope. What’s a scope? Well for right now, a scope is basically anything inside the element our directive is declared on. So, we declared our controller on the body tag. That means whatever we put inside the body tag is in the current scope when we are working inside our weatherController. Don’t believe me? Try this: add a div tag inside the body. Move the ng-controller declaration onto that div tag. Finally, move the p tag with our description outside the div, like this:



<html ng-app="weatherApp">
    <head>
        <title>My First Angular App!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body>
        <p ng-bind="description"></p>
        <div ng-controller="weatherController"></div>
    </body>
</html>

Here we go again… save and refresh. Nothing. That’s because our p tag is outside the scope of the controller now. I hope that’s becoming more clear. Basically if you want to bind something to the page then it needs to be on the $scope object. The $scope object is relevant to everything inside the element that you declared the directive on. In case you are wondering if you can have nested scopes. Yes. You can. So now that we have used a couple built-in directives, lets create our own. A custom directive!

Custom Directives
=============

Why would we want to build our own Directive? Well, suppose we have a lot more functionality inside our weatherController. Suppose it has a few Controllers and a Service or two. We might find it useful to re-use that weather on multiple pages. We don’t want to markup all the necessary elements every time on every page, so we use a directive. Adding a directive let’s us use templates so we can define the markup we need for weather once in its own file. Adding a directive also allows us to make changes to our code in one place and everywhere the directive is used is updated with the new functionality. Directives are really powerful and one of the best parts of Angular.

Adding a Directive to our app.js is very similar to adding a Controller. Here’s what app.js looks like now:

angular.module('weatherApp', [])
  .controller("weatherController", function($scope) {
    $scope.description = "a simple weather app";
  })
  .directive("weather", function() {
    return {
      restrict: "A",
      templateUrl: "weather.html"
    }
  });

This one is a little bit different than the controller in that it returns an object. That object has a bunch of parameters necessary for the directive to function. I’ve kept it simple and only added the bare minimum. First, I set the restrict property to “A”. This means the directive will function as an attribute of an element. This means I will put it on HTML elements just like ng-app or ng-controller. Second, I set templateUrl to a file named weather.html. This is the file that will hold the markup we used to have sitting in our body tag. Lets create that file next. Add the following code to weather.html:

<div ng-controller="weatherController">
 <p ng-bind="description"></p>
</div>

I’ve created a div tag here to declare the controller on. You could also have added the controller property to our directive and omitted this all together. Other than that, this file is pretty simple. Finally, let’s update our original HTML file to use our new directive:


<html ng-app="weatherApp">
    <head>
        <title>My First Angular App!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body>
        <div weather></div>
    </body>
</html>

I love how simple that is! Basically anywhere I want to add my weather app, I just add that directive now.

Now before you run this, let me tell you what sucks. If you try to refresh this in Chrome you will get a huge ugly Cross Origin error in your console, like this:


cross-origin-error
=============

Unfortunately, Chrome won’t let you reference local files. You can go ahead and work from Safari or you can run the following command inside your terminal window to open Chrome with this security disabled:

open -a Google\ Chrome --args --disable-web-security -–allow-file-access-from-files

Once you open you app again in Safari, or using the above command, you should see the same message as before, but now using your own custom directive! The last thing we need to do is add a Service.


Services
======


So we created a controller to manage our application and give us access to the scope. We placed all that functionality inside a Directive to allow us to re-use it and template out our markup. Where do we make a call to get our actual Weather? If you are thinking you would simply add a function to our controller and place the result on the scope… you’re not being very Angular! What I mean is that would work. You could simply call a web service right inside your controller and get your weather data, but Angular gives us Services to extract the functionality of getting our objects, calling web services etc. Its the preferred place to put that sort of logic.

Why else should you use a service? First, Reuse! You will likely create a service that is helpful to not only this controller, but to other controllers in your application. Or even a Directive (yes directives can be passed services). Second, maintenance. This controller example is trivial, but your actual projects will create very large controllers without cluttering them with service calls and the logic required to get and set objects.

So how do we add a Service? Well, again its very similar to the other pieces we’ve added to our application:


angular.module('weatherApp', [])
  .service("weatherService", function() {
    this.getWeather = function(cityName) {
      return "30";
    };
  })
  .controller("weatherController", function($scope, weatherService) {
    $scope.description = "a simple weather app";
    $scope.temp = weatherService.getWeather("Vancouver");
  })
  .directive("weather", function() {
    return {
      restrict: "A",
      templateUrl: "weather.html"
    }
  });

There’s a few items to take note of here. One, our service declares its function on this. Because of the way constructor functions work, you need to declare your functions on this if you want them to be accessible. If you didn’t declare it on this you wouldn’t be able to call it in the Controller. Second, we added our service to the list of parameters in our controllers’ constructor function. Finally, we created a scope variable named temp and placed the value returned from our Service call. Now I know I didn’t actually make a Service call. That’s the subject for another blog post, or a challenge for the reader.

The final piece is to update our template file with the new scope variable we created:

<div ng-controller="weatherController">
  <p ng-bind="description"></p>
  <p ng-bind="temp"></p>
</div>

If you save and refresh you will see your simple description and you’re hard-coded temperature. This was a simple and not very functional example, but the point was to help you understand the building blocks of an AngularJS application. With Controllers, Services and Directives and a basic understanding of scopes and declarative programming, you are should now be able to start to put together your first real AngularJS application!

How to configure Java and Eclipse for your ubuntu operating system ??


Following process to configure java in ubuntu
=================================

1) Download your jdk with your required version from

 http://www.oracle.com/technetwork/java/javase/downloads/index.html

2) After download, you found "jdk-8u73-linux-x64.tar.gz" in your download directoy.

3) Open your teminal, for installing JDK under "/usr/local/java" (or Ubuntu's default JDK directory /usr/lib/jvm).

   First, create a directory "java" under "/usr/local".

   Second, Extract the downloaded package (Check your downloaded filename!)

Write the Following commands for above 2 operations:

 cd /usr/local
 sudo mkdir java
 cd /usr/local/java
 sudo tar xzvf ~/Downloads/jdk-8u73-linux-x64.tar.gz
 
where     // x: extract, z: for unzipping gz, v: verbose, f: filename

4) So Now JDK shall be extracted in a folder "/usr/local/java/jdk1.8.0_73".


5) Now Informing Ubuntu to use this JDK/JRE:

// Setup the location of java, javac and javaws

$ sudo update-alternatives --install "/usr/bin/java" "java" "/usr/local/java/jdk1.8.0_73/jre/bin/java" 1
$ sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/local/java/jdk1.8.0_73/bin/javac" 1
$ sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/local/java/jdk1.8.0_73/jre/bin/javaws" 1

// Use this Oracle JDK/JRE as the default

$ sudo update-alternatives --set java /usr/local/java/jdk1.8.0_73/jre/bin/java
$ sudo update-alternatives --set javac /usr/local/java/jdk1.8.0_73/bin/javac
$ sudo update-alternatives --set javaws /usr/local/java/jdk1.8.0_73/jre/bin/javaws


These are the steps for set up symlinks java, javac, javaws at /usr/bin (which is in the PATH), that link to /etc/alternatives
and then to JDK bin directory.

The "alternatives" system aims to resolve the situation where several programs fulfilling the same function (e.g., different version of JDKs).

It sets up symlinks thru /etc/alternatives to refer to the actual programs to be used.

 cd /usr/bin
 ls -ld java*

lrwxrwxrwx 1 root root 22 Mar 31 20:41 java -> /etc/alternatives/java
lrwxrwxrwx 1 root root 23 Mar 31 20:42 javac -> /etc/alternatives/javac
lrwxrwxrwx 1 root root 24 Mar 31 20:42 javaws -> /etc/alternatives/javaws

 cd /etc/alternatives
 ls -ld java*

lrwxrwxrwx 1 root root 40 Aug 29 18:18 java -> /usr/local/java/jdk1.8.0_20/jre/bin/java
lrwxrwxrwx 1 root root 37 Aug 29 18:18 javac -> /usr/local/java/jdk1.8.0_20/bin/javac
lrwxrwxrwx 1 root root 42 Aug 29 18:19 javaws -> /usr/local/java/jdk1.8.0_20/jre/bin/javaws


6) To verify the JDK installation, issue these commands:
--------------------------------------------------------------------

// Show the Java Compiler (javac) version
   javac -version
   
   javac 1.8.0_73

// Show the Java Runtime (java) version
   java -version

   java version "1.8.0_73"
   Java(TM) SE Runtime Environment (build 1.8.0_73-b26)
   Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)

// Show the location of javac and java

   which javac
   /usr/bin/javac

   which java
   /usr/bin/java


7) Add JDK's binary directory ("bin") to the "PATH" by editing "/etc/profile":

   cd /etc
   gksudo gedit profile   // OR "sudo nano profile" to use the console-based nano editor


   Add these lines at the end of the file "/etc/profile"

   export JAVA_HOME=/usr/local/java/jdk1.8.0_73
   export PATH=$JAVA_HOME/bin:$PATH

   Rerun the configuration file by:

    source /etc/profile

  // Check the new settings for JAVA_HOME and PATH

    echo $JAVA_HOME
   
    /usr/local/java/jdk1.8.0_73

    echo $PATH
    .....:/usr/local/java/jdk1.8.0_73/bin


8) Compile and Run a Hello-world Java Program

    Open "Folder" and create a new directory called "myProject" under your home directory to keep all your works.
    Open "Text Editor" (gedit). Enter the following source code and save as "Hello.java" under the "~/myProject" directory created earlier.

    public class Hello
    {  
       public static void main(String[] args)
       {
          System.out.println("Hello, world from Ubuntu!");
       }
    }

    To compile the Hello-world Java program, launch a Terminal and issue these commands:

    // Change directory to where the source code resides
     cd /home/myProject
   
    // List the contents of current directory. Check for "Hello.java"
    ls
    ...... Hello.java ....
   
    // Compile "Hello.java" into "Hello.class"
    javac Hello.java
   
    // Check for "Hello.class"
    ls
    ...... Hello.class ....

    Run the Hello-world Java program:

    // Run "Hello.class"
    java Hello
   

Hello, world from Ubuntu!



==========================================================
Download the Eclipse IDE and try to launch them on Desktop
==========================================================

1) Download the eclipse for linux i.e. downloaded in my download folder as "eclipse-inst-linux64.tar.gz"

2) Now for installing eclipse

Install:

// Unzip the tarball into /usr/local
$ cd /usr/local
$ sudo tar xzvf ~/Downloads/eclipse-inst-linux64.tar.gz
      // Extract the downloaded package
      // x: extract, z: for unzipping gz, v: verbose, f: filename
      // You can also unzip in "File Explorer" by double-clicking the tarball.

// Change ownership
$ cd /usr/local
$ sudo chown -R your-username:your-groupname eclipse
      // Change ownership to your chosen username and groupname
      // -R recursive

// Set up a symlink
$ cd /usr/bin

$ sudo ln -s /usr/local/eclipse/eclipse
      // Make a symlink in /usr/bin, which is in the PATH.

$ ls -ld eclipse
lrwxrwxrwx 1 root root 26 Aug 30 11:53 eclipse -> /usr/local/eclipse/eclipse

$ which eclipse
/usr/bin/eclipse

$ whereis eclipse
eclipse: /usr/bin/eclipse /usr/bin/X11/eclipse /usr/local/eclipse


then go to particular folder -  /home/eclipse/jee-mars/eclipse/
right there just right click on elipse launcher and click on create link and then copy those link shortcut to desktop.

In such manner, you can create the Desktop shortcut.

Thursday, 28 January 2016

How can you describe String Literal/Constant Pool ??

There are two ways to create a String object in Java:

Using the new operator. For example,
String str = new String("Hello");

Using a string literal or constant expression). For example,
String str="Hello"; (string literal) or
String str="Hel" + "lo"; (string constant expression).

What is difference between these String's creations? 

In Java, the equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares the content of two objects rather than two objects' references. The == operator with reference types (i.e., Objects) evaluates as true if the references are identical - point to the same object. With value types (i.e., primitives) it evaluates as true if the value is identical. The equals method is to return true if two objects have identical content - however, the equals method in the java.lang.Object class - the default equals method if a class does not override it - returns true only if both references point to the same object.

Let's use the following example to see what difference between these creations of string:

public class DemoStringCreation {

  public static void main (String args[]) {
    String str1 = "Hello";
    String str2 = "Hello";
    System.out.println("str1 and str2 are created by using string literal.");  
    System.out.println("    str1 == str2 is " + (str1 == str2));
    System.out.println("    str1.equals(str2) is " + str1.equals(str2));

   
    String str3 = new String("Hello");
    String str4 = new String("Hello");
    System.out.println("str3 and str4 are created by using new operator.");  
    System.out.println("    str3 == str4 is " + (str3 == str4));
    System.out.println("    str3.equals(str4) is " + str3.equals(str4));
   
    String str5 = "Hel"+ "lo";
    String str6 = "He" + "llo";
    System.out.println("str5 and str6 are created by using string
constant expression.");  
    System.out.println("    str5 == str6 is " + (str5 == str6));
    System.out.println("    str5.equals(str6) is " + str5.equals(str6));

    String s = "lo";
    String str7 = "Hel"+ s;
    String str8 = "He" + "llo";
    System.out.println("str7 is computed at runtime.");
    System.out.println("str8 is created by using string constant
expression.");  
    System.out.println("    str7 == str8 is " + (str7 == str8));
    System.out.println("    str7.equals(str8) is " + str7.equals(str8));
   
  }
}
The output result is:

str1 and str2 are created by using string literal.
    str1 == str2 is true
    str1.equals(str2) is true
str3 and str4 are created by using new operator.
    str3 == str4 is false
    str3.equals(str4) is true
str5 and str6 are created by using string constant expression.
    str5 == str6 is true
    str5.equals(str6) is true
str7 is computed at runtime.
str8 is created by using string constant expression.
    str7 == str8 is false
    str7.equals(str8) is true

The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources.



String Literal Pool

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";
       String str2 = "Hello";
       System.out.print(str1 == str2);
    }
}
The result is

true


Unfortunately, when you use
String a=new String("Hello");

A String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it!

For example

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";
       String str2 = new String("Hello");
       System.out.print(str1 == str2 + " ");
       System.out.print(str1.equals(str2));
    }
}
The result is

false true


A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added.
For example

public class Program
{
    public static void main(String[] args)
    {
        // Create three strings in three different ways.
        String s1 = "Hello";
        String s2 = new StringBuffer("He").append("llo").toString();
        String s3 = s2.intern();

        // Determine which strings are equivalent using the ==
        // operator
        System.out.println("s1 == s2? " + (s1 == s2));
        System.out.println("s1 == s3? " + (s1 == s3));
    }
}
The output is

s1 == s2? false
s1 == s3? true
There is a table always maintaining a single reference to each unique String object in the global string literal pool ever created by an instance of the runtime in order to optimize space. That means that they always have a reference to String objects in string literal pool, therefore, the string objects in the string literal pool not eligible for garbage collection.


Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions-are "interned" so as to share unique instances, using the method String.intern.

Thus, the test program consisting of the compilation unit:

package testPackage;
class Test {
        public static void main(String[] args) {
                String hello = "Hello", lo = "lo";
                System.out.print((hello == "Hello") + " ");
                System.out.print((Other.hello == hello) + " ");
                System.out.print((other.Other.hello == hello) + " ");
                System.out.print((hello == ("Hel"+"lo")) + " ");
                System.out.print((hello == ("Hel"+lo)) + " ");
                System.out.println(hello == ("Hel"+lo).intern());
        }
}
class Other { static String hello = "Hello"; }
and the compilation unit:

package other;
public class Other { static String hello = "Hello"; }
produces the output:

true true true true false true

This example illustrates 5 points:

a) Literal strings within the same class in the same package represent references to the same String object.
b) Literal strings within different classes in the same package represent references to the same String object.
c) Literal strings within different classes in different packages likewise represent references to the same String object.
d) Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
e) Strings computed by concatenation at run time are newly created and therefore distinct.

JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...