Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Saturday, October 24, 2015

Interview Questions


  • Face to Face Interview Questions
  • Core Java Interview Questions
  • JDBC Interview Questions
  • Servlets Interview Questions
  • JSP Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • AngularJS Interview Questions
  • Struts Interview Questions

Friday, October 23, 2015

Face to Face Java Interview Questions for Freshers and Experienced


In this post, we are going to see some of the interview question asked while attending face to face.

Note: Here Company-1, Company-2 ...... are Some company names.

Company - 1:

1. Write a java program to print the following pattern:
   *
   *    *
   *    *    *
   *    *    *    *
   *    *    *    *    *
   *    *    *    *    *    *
2. Write a Collection hierarchy.
3. Write a Exception hierarchy.
3. What are different types of exception?
4. If you are not handling runtime exceptions why we want to write try and catch block.
5.  It is possible with out execute finally block to exit that method.
try {

} 
catch() {

}
finally {

}   
6. What is the output of the following program.
try {
     return 10 + 20;
} 
catch() {

}
finally {
     return 10 - 20;
}
7. How to handle a exception handling in the following flow:
   View    -->    Controller -->   Service   --> DAO
8. Java supports multiple inheritance or not?
9. What is the output of the following program.
interface A {
     public final static int MAX = 100;
}   
   
interface B {
     public final static int MAX = 100;
}      

class C implements A, B {
   
}
10. What is the output of the following program.
interface A {
     public final static int MAX = 100;
}   
   
interface B {
     public final static int MAX = 100;
}      

class C implements A, B {
   public static void main(String args[]) {
    System.out.println(MAX);
   }
}
11. What is the output of the following program
public void test(byte b ) { Syso("byte value"); }
public void test(int i) { Syso("int value"); }
public void test(Integer i) { Syso("Integer value"); }  
public void test(int ..args) { Syso("var args value"); }    

What is the output of the following program:    
test(100);
test(10000);
12. What is the output of the following program
public void test(byte b ) { Syso("byte value"); }
public void test(Integer i) { Syso("Integer value"); }  
public void test(int i) { Syso("int value"); }
public void test(int ..args) { Syso("var args value"); }    

What is the output of the following program:    
test(100);
test(10000);
13. What is Generalization?
14. Assume we have tables Patient and Doctor.
Patient table:
pid  pname    did
-----------------
1      a      3
2      b      2
3      c      2
4      d      1
5      e      3
6      f      null
    
Doctor table:
did  dname  specialization
-------------------------
1     aa      neurology
2     bb      pathology
3     cc      gynecology
        
Display the output in the following format. 
did dname count(pid)
15. In hibernate how to achieve one to many relationship.
16. In hibernate how to achieve many to many relationship. How many classes is needed and how many tables is needed for implementing many to many relationship.
17. Explain Servlet Life Cycle.
18. How to create a singleton object with thread safe.
19. How to display both key and values while iteration. Write the logic.
20. What is difference between Comparator and Comparable.
21. Assume i have person class with the fields id, name, age etc.
How to sort person class object values with id or name or age.
22. It is possible to store the person object hashmap. If it possible how?


Company - 2:
1. Explain about Relationship, Aggregation and Composition. Can you explain above relationship using Library, Student and Book.
2. What are the different ways to create a bean in Spring.
3. What is bean preprocessor and postprocessor.
4. What is fail fast and fail safe iterators.
5. How to get value using hashmap.
6. Assume i have string contains huge data. What is the best approach to find duplicate characters.


Company - 3:
1. Explain Oops Concepts?
2. Explain Abstraction. Can you give one realtime example?
3. Why string is immutable.
4. How many objects is created for the below program.
String s1 = "ranga";
String s2 = s1 + "reddy";
String s3 = "hi" + s2;
5. How Hashmap works.
6. What is Synchronization. Who will lock the object.
7. What is Serialization. What is the use of Serialization.
8. Write a sample program using Externilzable interface.
9. What is difference between Filter, Interceptor?
10. Write a Singleton program using double checking? We should not clone the singleton object.
11. What is difference between Factory design pattern and abstract factory design pattern. Can you give one Java API example.
12. How to redirect a request from one servlet to another servlet.
13. How to avoid duplicate submit the form.
14. How to achieve inheritance through spring configuration file.
15. What are the Spring bean scopes.
16. What is a functional programming language?
17. What is Java 8 features?
18. Can you write a sample program using lambda expressions.
19. What is callable interface?
20. In hibernate, for @onetomany annotation what are the attributes we need to pass.
21. What is difference between Left Inner Join and Right outer join.
22. Can you explain ACID Properties.
23. What is difference between Git and Subversion.


Company - 4:
1. What are the spring scopes.
2. What are the technologies you learnt recently.
3. Why Cassandra.
4. What is the use of Cassandra.


Company - 5:
1. What is difference between Abstraction and Encapsulation.
2. What is difference between wait() and wait(long) method.
3. What is difference between wait() and sleep(). If you call notifyAll() what happens in wait() method and sleep().
4. What is difference between abstract class and interface.
5. Who will lock the thread.
6. What are the spring scopes.
7.
<bean id="aBean" class="A" scope="singleton">
    <bean id="bBean" ref="bBean">
</bean>
     
<bean id="bBean" class="B" scope="prototype">
</bean>
What happens if i call aBean 3 times. How many B bean objects is created.
8. Write a program @manytomany association using student and course.
9. What is difference get() method and load() method.
10. What is difference between jdbc and orm.
11. What is difference between jpa and hibernate.
12. Assume there is form. There we can enter employee id and submit.
There is a sql query like "delete from employee where employee_id = "+id;
Now enter the employee_id value will be 100 or 1 == 1 and submit the form.
What happened. How to avoid sql injection.
13. Explain Spring MVC flow.
14. What is difference between @Component, @Controller, @Service, @Repository
15. How to handle Security in Restful Web Services.
16. What is the way to avoid changing the Collection values.
17. What is difference between hashmap and linkedhashmap.
18. How to sort the Custom Class values.
19. Explain how hashmap works.
20. How to lock the thread.
21. What are the different levels of locking in hibernate.
22. What is a Spring Transaction. What are the propegastion and  isolation levels.
23. Assume there is a relation ship.
                           RBI

SBI   Indian  Canara
When i change any thing on the RBI class it needs to notify to all sub classes for this one which design pattern you will use.
24. What is Factory design pattern.
24. String is immutable class. What is the use of making String class is immutable.
25. Immutable class uses the which design pattern. Can you give few immutable classes.
26. What is difference between forward() and include() method.
27. What is difference between page, pageContext and applicationContext.
28. What is the difference between Comparable and Comparator.
29. If i have more updation and deletion which collection you will prefer.
30. Reverse the string with out using the any JAVA API.
31. What is DAO design pattern. What are the advantages while using DAO design pattern.
32. In order to interact with hibernate what are the steps we need to do.
33. What are the roles and responsibilities.
34. Tell me about your self.
35. How to handle performance.


Company - 6:
1. Tell me about your self.
2. What are design patterns you worked.
3. Write the Factory design pattern.
4. How to interact with multiple systems.
5. How to ensure one of the server is done but data needs to be consistent.
6. Do you know JMS. Can you explain architecture of JMS.
7. How many squares are there in chess board.



Company - 7:
1. Tell me about your self.
2. About the Project.
3. Why Collections.
4. Difference between array and array list.
5. Which collection you will prefer for avoiding duplicates.
6. Why angularjs.
7. Why Spring.
8. Can you explain how request and response we can get in Spring.


Company - 8:
1. What is serialization. If i make any variable as static what will happen. If i make any variable as volatile what will happen.
2. Who will do the serialization.
3. Can you tell what are all the methods available in Serilizable interface.
4. What is cloning. What are the different types of Cloning. Can you write the program.
5. Why web services. Can you explain what are the types of web services available.
6. Can we use Servlet as a WebService.
7. What is DAO pattern. Can you write one sample program. What are all the advantage of using DAO pattern.
8. Can you explain Singleton design pattern. What are all advantages of creating singleton object as lazy and eagar.
9. What is multi threading. When we can use Threads.
10.
class Test extends Thread {
    public void synchronized test() {
    // some logic
    }
}
        
class Main {
    public static void main() {
      Test t1 = new Test();
      Test t2 = new Test();
                
      t1.start();
      t2.start();           
      t1.test();
      t2.test();
    }
}   
Now while calling t1.test() and t1.test(); test() method will execute serially or not.
11. Difference between List and Set.
12. How hashmap works.
13. What is actions and directives in JSP.
14. How to deploy war in tomcat. What are the difference ways is available.
15. While deploying War file into tomcat, if you dont have permissions how to deploy.
16.
Emp_Id     Allowance_type  Salary
----------------------------------
 1            HRA           2000
 1            DA            1500         
 2            HRA           3000
 2            DA            2000
-----------
a) Write a query to find out the sum of salary of each employee.
b) Write a query to find out the sum of salary of each employee and salary greater then 3000.
17. What will be the output of the following program.
public int getValue() {     
     int x = 10;
     try {
        return x;
     } finally {
         x++;
     }  
}
18. What the difference between NoClassDefFoundError and ClassNotFoundException
19. Explain about project.
20. What are the different types of exceptions.
21. What are the different types of Statements in JDBC.
22. Where preparedstatement plan will be stored either java heap memory or database.
23. How to access java script variable value into java in jsp page.
24. What is AJAX.


Company - 9:
1. Java5 Features
2. What is enum.
3. How hashmap works.
4. What is IOC.
5. Can you explain Spring MVC flow.
5. Why cassandra is column - oriented database.
6. What is CAP theorem.
7. What is Round Robin Algorithm
8. Why AngularJss.
9. Architecture of AngularJs.
10. In angularjs how to manipulate DOM.
11. Can you different events in angularjs.


Company - 10:
1) In browser after hitting url how the request processing is doing.
2) How serialization works where serializable interface is a marker interface.
3) Write a customized Doubly linked list program using Java.
4) Explain about Autoboxing
5) Calling destroy method from service
6) Inheritance concept  for beans in spring.
7) Default access modifier
8) Default access modifier for interface.
9) Circular dependency
10) Volatile keyword
11) Multi threading
12) Write a Java program to print the numbers using following pattern.
1
2 3
4 5 6
7 8 9 10
13) Scriptlets
14) CRON expressions
15) Wrapper classes function overloading.


Company - 11:
1. What are the OOPs concepts in Java script.
2. How to share the data between two controllers.
3. Can you write one sample angularjs application.
4. What happen if i am not passing arguments to the function.
var myApp = angular.module('myApp',[]);

myApp.controller('TestController', ['$scope', function(scope) {
scope.name = 'Ranga Reddy';
}]);
5. How to achieve toggle using programmatically in angularjs.
6. Assume list of rows is there. If i click on any row it needs to open. If i click on other row what ever row previously opened needs to close. Newly selected row needs to open.
How to achieve in angularjs.
7. Can you tell what are the directives used in your application.


Company - 12:
1. Can you tell me about your self and what are the technologies you worked.
2. How to share the data between two controllers.
3. How to achieve multiple inheritance in java.
4. What is the difference between method overloading and overriding.
5. Have you worked on Collections. Suppose i have Employee class with the id, name, age, salary fields. I have array list of 10 employee objects. How to sort the employees object using salary.
6. Have you worked on JSPs.
7. How to create a Custom directive in angularjs.
8. How to achieve two way data-binding.
9. What are the different types of Scopes in angularjs.
10. Have you worked on Restful web services.
11. How to call web services in angularjs.



Happy Learning!

Monday, September 28, 2015

forEach() method in Iterable interface and Stream interface in Java 8

To iterate a collection, we have several ways:

  • Using Normal for loop
  • Using Enhanced for loop
  • Using Iterator (java.util.Iterator)
1. Using Normal for loop:
List<String> names = new ArrayList<>();
names.add("Ranga");
names.add("Reddy");
names.add("Raja");
names.add("Vasu");
        
System.out.println("Using normal for loop..");
for(int index = 0; index < names.size(); index++) {
    System.out.println(names.get(index));
}
2. Using Enhanced for loop:
System.out.println("\nUsing enhanced for loop..");
for(String name: names) {
    System.out.println(name);
}
3. Using Iterator (java.util.Iterator):
System.out.println("\nUsing Iteraotr..");
Iterator<String> namesIterator = names.iterator();
while(namesIterator.hasNext()) {
    System.out.println(namesIterator.next());
}

In java 8, a new method is introduced to iterate collection ie. forEach(). This forEach() is defined in two places namely, inside java.lang.Iterable interface and java.util.stream.Stream interface.
4. Using Iterable (java.lang.Iterable):
Collection classes that implements Iterable interface (List, Set) have a default method called a forEach(), it takes one argument i.e Consumer functional interface.
package java.lang;

public interface Iterable<T> {
    --------
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
   --------
}
System.out.println("\nUsing Consumer..");
Consumer<String> namesConsumer = (name) -> System.out.println(name);                 
names.forEach(namesConsumer);
5. Using Streams (java.util.Stream):
Same as Iterable interface forEach() stream interface also having one forEach() method it will take Consumer functional interface. Through streams, we can iterate collection (List, Set, Map) values serial and parallel.
package java.util.stream;
public interface Stream<T> extends BaseStream<T, Stream<T>> {
    --------
    void forEach(Consumer<? super T> action);
    --------
}
System.out.println("\nUsing Stream forEach..");                  
names.stream().forEach((name) -> System.out.println(name));
        
System.out.println("\nUsing Parallel Stream forEach..");                     
names.parallelStream().forEach((name) -> System.out.println(name));
If you we use parallelStream().forEach() method, there is no guarantee to which order elements will display. To make same order we need to use forEachOrdered() method.

Note: Instead of using Iterable forEach() method prefer to use Streams().forEach() because streams are lazy and not evaluated until a terminal operation is called.
package com.ranga.foreach;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Ranga Reddy
 * @version 1.0
 */
public class ForEachDemo {
    public static void main(String[] args) {
                
        List<String> names = new ArrayList<>();
        names.add("Ranga");
        names.add("Reddy");
        names.add("Raja");
        names.add("Vasu");
        
        System.out.println("\nPrinting the list values using forEach()..");              
        names.stream().forEach((name) -> System.out.println(name));
        
        
        System.out.println("\nPrinting the set values using forEach()..");
        Set<String> setNames = new HashSet<>(names);
        setNames.add("Ranga");
        setNames.forEach(System.out::println);
        
        Map<String, String> namesMap = new HashMap<>();
        namesMap.put("name1", "Ranga");
        namesMap.put("name2", "Reddy");
        namesMap.put("name3", "Vasu");
        namesMap.put("name4", "Raja");
        
        System.out.println("\nPrinting the hashmap values using forEach()..");
        namesMap.forEach((key, value) -> System.out.println("Key: "+key +", Value: "+value));
    }
}
Output:
Printing the list values using forEach()..
Ranga
Reddy
Raja
Vasu

Printing the set values using forEach()..
Raja
Reddy
Vasu
Ranga

Printing the hashmap values using forEach()..
Key: name4, Value: Raja
Key: name3, Value: Vasu
Key: name2, Value: Reddy
Key: name1, Value: Ranga

Sunday, September 27, 2015

Lambda Expressions in Java 8

Lambda Expressions:
  • Lambda expression is an anonymous function without any declarations. 
  • Lambda Expression are useful to write shorthand code and hence saves the effort of writing lengthy code. 
  • It promotes developer productivity, better readable and reliable code.
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final variables from the enclosing scope..
Syntax of Lambda expression:
(arguments) -> {body}

Example of Lambda expression:
public class LambdaExpressions
{
  public static void main(String[] args)
  {        
    // Old way
    Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("With out using Lambda Expressions .... ");
        }
    };
    
    Thread thread = new Thread(runnable);    
    thread.start();
    
    // Using Lambda Expressions
    Runnable runnable2 = () -> { System.out.println("With using Lambda Expressions .... ");};
    
    Thread thread2 = new Thread(runnable2);    
    thread2.start();    
  }
}
Output:
With out using Lambda Expressions .... 
With using Lambda Expressions .... 
Lambda expression arguments can contain zero or more arguments.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");

new Thread(() -> { System.out.println("Empty arguments.");}) {      // empty arguments          
}.run();;
        
names.forEach(name -> System.out.println(name));            // one argument with out specifying data type 
names.forEach((name) -> System.out.println(name));          // one argument with out specifying data type
names.forEach((String name) -> System.out.println(name));   // one argument with specifying data type
Note: We can omit the datatype of the parameters in a lambda expression. And also we can omit the parentheses if there is only one parameter.

Lambda expression body can contain any number of statements or with out statement also.
If body contains more than one statement then curly braces is mandatory otherwise it is optional.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");
        
names.forEach(((name) -> System.out.println(name))); // with out braces
        
names.forEach((name) -> {                            // with braces 
    System.out.println(name);
    System.out.println("Hello Mr. "+name);          
});

Sunday, September 20, 2015

Functional Interfaces (java.util.function) in Java 8



Functional Interfaces (java.util.function):

  • Functional interface is also called as Single Abstract Method interfaces.
  • A functional interface is an interface with a single abstract method
  • Note: A functional interface can redeclare the methods in the Object class.
  • The Java API has many one-method interfaces such as java.lang.Runnable, java.util.concurrent.Callable, java.util.Comparator, java.awt.event.ActionListener etc.
      • public interface Runnable { void run(); } 
      • public interface Callable<V> { V call() throws Exception; }
      • public interface ActionListener { void actionPerformed(ActionEvent e); } 
      • public interface Comparator<T> { int compare(T obj1, T obj2); boolean equals(Object obj); } 
  • Instances of functional interfaces can be created with lambda expressions, method references, or constructor references. For example,
                // Before Java8
Runnable runnable1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("runnable1");
}
});
runnable1.run();
// Java8
Runnable runnable2 = () -> System.out.println("runnable2");
runnable2.run();   
  • In java 8, to declare functional interfaces there is a new annotation is introduced called @FunctionalInterface. By using this annotation we will ensure that the functional interface will not have more than one abstract method. If we try to add one more abstract method it will raises the compile timer error. 
                Example 1: 
                @FunctionalInterface 
                interface Greeting {
              public void greeting(String message);
                }
                The above Greeting functional interface is valid interface because it contains only one abstract method. 

                Example 2: 
                @FunctionalInterface 
                interface Animal {
               public void speak();
               public default void name() {
            System.out.println("Hay I am animal");
               }
                }
                The above Animal functional interface is valid because in functional interface we can keep n number of default methods.

               Example 3:
                @FunctionalInterface 

                interface Test {
              public void doWork();
              public boolean equals(Object obj);
              public String toString();
                }
                The above Test functional interface is valid because in function interface we can declare the abstract methods from the java.lang.Object class.
               
                Example 4:
                @FunctionalInterface 

                interface EmptyInterface {
                      
                }
                The above EmptyInterface functional interface is not valid because it does not contain any abstract method.

                Example 5:
                @FunctionalInterface 

                interface MultipleMethodsInterface {
              public void doWork();
              public boolean equals();
                }
                The above MultipleMethodsInterface functional interface is not valid because it contains more than one abstract method.

                Example 6:
                @FunctionalInterface 

                interface Greeting {
              public void sayGreeting();
              public boolean equals();
                }


                interface AnotherGreeting extends Greeting {
              public boolean equals();
                }

                The above AnotherGreeting functional interface is valid because it is inheriting sayGreeting() method and this sayGreeting() method is abstract.

                Example 7:
                @FunctionalInterface 

                interface Greeting2 {
              public void sayGreeting();
              public boolean equals();
                }


                interface AnotherGreeting2 extends Greeting2 {
              public void sayAnotherGreeting();
              public boolean equals();
                }

                The above AnotherGreeting2 functional interface is not valid because it is inheriting sayGreeting() abstract method and also it contains one more abstract method say sayAnotherGreeting() method.
  • The major benefit of functional interface is that we can use lambda expressions to instantiate them and avoid using bulky anonymous class implementation.
  • The advantage of functional interface over normal interface is we can define method definition inside Interface using default modifier which helps to modify existing Interface with out breakage of application.
  • Java 8 Collections API has rewritten and new Stream API is provided that uses a lot of functional interfaces. Java 8 has defined a lot of functional interfaces in java.util.function package, some of the useful ones are Consumer, Supplier, Function and Predicate etc. You can find more here. How to use above functional interface we can see in Stream API examples.
Happy Learning..!

Saturday, September 19, 2015

Difference between ServletConfig and ServletContext

In this post, we are going to see the difference between ServletConfig and ServletContext.

Difference between ServletConfig and ServletContext:

ServletConfigServletContext(It should have been ApplicationContext)
One ServletConfig object is created per servlet One ServletContext object is created per Application
Can be used to pass deployment time information to the Servlet. Information is stored as parameters in the deployment descriptor(web.xml) Can be used to share Application level information across servlets and is this information is also stored in the web.xml as well as parameters (So it kind of acts as GlobalContext or Application Context)
Provides a set of methods to set and get the initialization configuration information Provides a set of methods to the servlet so that servlet can communicate with the Container
------------------------Servlet can access a ServletContext object only through ServletConfig object

Working with ServletConfig:

web.xml: 
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.ranga.LoginServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>ranga</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>ranga</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
LoginServlet.java    
package com.ranga;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Ranga Reddy
* @version 1.0
*/

public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = -2226127949360374211L;
protected String username = null, password = null;

public void init(ServletConfig servletConfig) throws ServletException {
this.username = servletConfig.getInitParameter("username");
this.password = servletConfig.getInitParameter("password");
}

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("<html><body> Username:" + this.username + ", Password: "+this.password+" </body></html>");
}
}
Getting init parameters inside the servlet
servletConfig.getInitParameter("username");

Working with ServletContext:

web.xml:
 <context-param>
<param-name>username</param-name>
<param-value>ranga</param-value>
</context-param>

<context-param>
<param-name>password</param-name>
<param-value>ranga</param-value>
</context-param>

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.ranga.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
LoginServlet.java
package com.ranga;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Ranga Reddy
* @version 1.0
*/

public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = -2226127949360374211L;
protected String username = null, password = null;

public void init(ServletConfig servletConfig) throws ServletException {

ServletContext servletContext = servletConfig.getServletContext();
this.username = servletContext.getInitParameter("username");
this.password = servletContext.getInitParameter("password");
}

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("<html><body> Username:" + this.username + ", Password: "+this.password+" </body></html>");
}
}
Accessing context params in Servlet
servletConfig.getServletContext().getInitParameter("username");
Accessing context params in JSP
<% getServletContext().getInitParameter("username"); %>