Program to print prime numbers in java


  1. package com.instaceofjava;
  2. public class primenumbers {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. int num=50;
  7. int count=0;
  8.  
  9. for(int i=2;i<=num;i++){
  10.  
  11. count=0;
  12.  
  13. for(int j=2;j<=i/2;j++){
  14.  
  15. if(i%j==0){
  16. count++;
  17. break;
  18. }
  19.  
  20. }
  21.  
  22. if(count==0){
  23.  
  24. System.out.println(i);
  25.  
  26. }
  27.  
  28. }
  29.  
  30. }
  31.  
  32. }




Output:
  1. 2
  2. 3
  3. 5
  4. 7
  5. 11
  6. 13
  7. 17
  8. 19
  9. 23
  10. 29
  11. 31
  12. 37
  13. 41
  14. 43
  15. 47

Java programming interview questions
  1. Print prime numbers? 
  2. What happens if we place return statement in try catch blocks 
  3. Write a java program to convert binary to decimal 
  4. Java Program to convert Decimal to Binary
  5. Java program to restrict a class from creating not more than three objects
  6. Java basic interview programs on this keyword 
  7. Interfaces allows constructors? 
  8. Can we create static constructor in java 
  9. Super keyword interview questions java 
  10. Java interview questions on final keyword
  11. Can we create private constructor in java
  12. Java Program Find Second highest number in an integer array 
  13. Java interview programming questions on interfaces 
  14. Top 15 abstract class interview questions  
  15. Java interview Questions on main() method  
  16. Top 20 collection framework interview Questions
  17. Java Interview Program to find smallest and second smallest number in an array 
  18. Java Coding Interview programming Questions : Java Test on HashMap  
  19. Explain java data types with example programs 
  20. Constructor chaining in java with example programs 
  21. Swap two numbers without using third variable in java 
  22. Find sum of digits in java 
  23. How to create immutable class in java 
  24. AtomicInteger in java 
  25. Check Even or Odd without using modulus and division  
  26. String Reverse Without using String API 
  27. Find Biggest substring in between specified character
  28. Check string is palindrome or not?
  29. Reverse a number in java?
  30. Fibonacci series with Recursive?
  31. Fibonacci series without using Recursive?
  32. Sort the String using string API?
  33. Sort the String without using String API?
  34. what is the difference between method overloading and method overriding?
  35. How to find largest element in an array with index and value ?
  36. Sort integer array using bubble sort in java?
  37. Object Cloning in java example?
  38. Method Overriding in java?
  39. Program for create Singleton class?
  40. Print numbers in pyramid shape?


  41. Check armstrong number or not?
  42. Producer Consumer Problem?
  43. Remove duplicate elements from an array
  44. Convert Byte Array to String
  45. Print 1 to 10 without using loops
  46. Add 2 Matrices
  47. Multiply 2 Matrices
  48. How to Add elements to hash map and Display
  49. Sort ArrayList in descending order
  50. Sort Object Using Comparator
  51. Count Number of Occurrences of character in a String
  52. Can we Overload static methods in java
  53. Can we Override static methods in java 
  54. Can we call super class static methods from sub class 
  55. Explain return type in java 
  56. Can we call Sub class methods using super class object? 
  57. Can we Override private methods ? 
  58. Basic Programming Questions to Practice : Test your Skill
  59. Java programming interview questions on collections

Filters in java


  • Filters are used to pre process the request and post process the response.
  • This concept has introduced in servlet 2.3 version.
  • Preprocessing involves authentication , logging ,authorization , change request information.
  • Post processing involves encrypting response compressing response.
Filters in java



Application areas of Filter:

  • To implement logging mechanism.
  • To perform authentication.
  • To perform authorization.
  • To alter request information.
  • To alter response information.
  • Encrypting response.
  • Compressing response.

Interfaces present in Filter API: 

  • Javax.servlet.Filter
  • Javax.servlet.FilterConfig
  • Javax.servlet.FilterChain

 Filter:

  • Every filter class should implement filter interface either directly or indirectly.
  • Filter interface defines the most common which can be applicable for any Filter object.
  • Filter interface defines following methods
    1. init()
    2. doFilter()
    3. destroy()

  • public abstract void init(FilterConfig config) Throws ServletException:
    This method is used to perform initialization activities.
    This method will be executed just after filter object is created.
  • public abstract void doFiletr(ServletRequest req, ServletResponse res, FilterChain ch) throws
    IOException, ServletException
    .
    This method will be executed for every request to perform filter activities.
    In this method only we have to implement entire Filter logic
    This method takes filterChain object as argument and by using that we can forward the request
    to the nest level. Next level can be again filter or servlet.
  • public abstract void destrroy();
    this method will be executed only once to perform cleanup activities just before taking filter from out of service .





Jsp Directive Elements

  • A jsp directive is a translation time instruction to the jsp engine.
  • we have three kinds of directives.
  1. Page directive
  2. Include directive
  3. Taglib directive


Page Directive:

  • Page directive is one of the three translation time instructions to the jsp engine.
  • Page directive has 13 attributes.
  • Mostly page directive used to import java packages in to jsps
    <% @ page import="java.sql.*, java.util,*"%>

Jsp Page directive attributes:

  1. import
  2. session
  3. isErrorPage
  4. errorPage
  5. ContentType
  6. isThreadSafe
  7. extends
  8. info
  9. language
  10. autoflush
  11. buffer

import:

This attribute defines the list of packages,each separated by comma.

Syntax:

import="package.class"

Example:

<%@page import="java.util.*,java.io.*"%>

Session:

The session attribute indicates that  whether or not the JSP page uses HTTP sessions. If it is tree means that the JSP page has access to a
existing session object and it is false means that the JSP page cannot access the built-in session object.

Syntax:

session="true|false"

Example:

<%@ page session="true"%>

isErrorPage:

In JSp Page IsErrorPage indicates that whether or not the current page can act as a error page or not.If it is true it is Supposed to handle the Errors..

Syntax:

isErrorPage="true|false"

Example:

<%@ page isErrorPage="false"%>

errorPage:

The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs.
The value of the errorPage attribute is a relative URL.
The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown

Syntax:

errorPage="url"

Example:

<%@ page errorPage="error.jsp"%>

contentType :

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.

Syntax:

contentType="MIME-Type"

Example:

<%@ page contentType="text/html; charset=ISO-8859-1"%>

isThreadSafe:

isThreadSafe option tells that a page as being thread-safe. By default, all JSPs are considered thread-safe.
If you set the isThreadSafe is false, the JSP engine makes sure that only one thread at a time is executing your JSP.

Syntax:

isThreadSafe="true|false"

Example:

<%@ page isThreadSafe="true"%>

extends:

Indicates the superclass of servlet when jsp translated in servlet.

Syntax:

extends="package.class"

Example:

<%@ page extends="com.Connect"%>

info:

This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo() method of Servlet interface.

Syntax:

info="message"

Example:

<%@ page info="created by instanceofjava" %>

language:

language tells the server about the language to be used in the JSP file.
Presently the only valid value for this attribute is java.

Syntax:

language="java"

Example:

<%@ page language="java"%>

autoflush:

autoflush attribute true indicates that the buffer should be flushed when it is full and false indicates that an exception should be thrown
when the buffer overflows.

Syntax:

autoflush="true|false"

Example:

<%@ page autoFlush="true"%>

Buffer:

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The default size of the buffer is 8Kb.

Syntax:

buffer="sizekb|none"

Example:

<%@ page buffer="8kb"%>

include Directive:

The include directive is used to include the contents of any resource it may be jsp file, html file or text file.
It allows a JSP developer to include source code of a file inside jsp file at the specified place at a translation time.

Advantage of Include directive:

Code Reusability

Syntax:

<%@ include file="sourceName"%>

Example:

<%@ include file="/foldername/fileName"%>

taglib Directive:

The taglib directive makes custom actions available in current page through the use of tag library.
TLD (Tag Library Descriptor) is used for file to define the tags.

Syntax:

<%@ taglib uri="path" prefix="prefix"%>

Example:


<%@ taglib uri="http://www.instanceofjava/tags" prefix="mytag"%>




Collections List


List Interface:
  • List allows Duplicate Elements.
  • List having index.
  • List allows n number of null values.
  • List will display Insertion order with index.
  • List having classes like :
  • Vector
  • ArrayList
  • LinkedList


Introduction to the Java List Interface

The List interface in Java forms part of the core of the Java Collections Framework. It offers access to an ordered list of objects. In contrast with sets, lists allow duplicates as well as maintain insertion order. This makes lists perfect for sequences. When sequence matters, the List interface in Java is useful for modeling things like user input, products returned from a database query, or steps in a workflow.

In this guide, you'll find the List interface and its implementing classes: ArrayList, LinkedList, Vector, and Stack. We will examine their performance characteristics, use cases, and best practices to help you select the right one for any given project.

Key Characteristics of the List Interface

  • Accepted Elements: Elements maintain their order of insertion.
  • Index-based access: Retrieve, add, or remove elements by position.
  • Duplicates allowed: Lists can contain the same item more than once.
  • Null-Safe: Most implementations of List allow null values.

Classes that Implement the List Interface

1. ArrayList

  • What It Is: A resizable array implementation.
  • When to Use: Ideal for read-heavy, random access operations.
  • Performance:
    • Access: O(1) (fast for get() and set()).
    • Insert/Delete: O(n) (because shifting items is required).

Example:

List<String> fruits = new ArrayList<>();
fruits.add("Apple");  
fruits.add("Banana");  
System.out.println(fruits.get(0)); // Output: Apple  

2. LinkedList

  • What It Is: A doubly-linked list implementation.
  • When to Use: Ideal for frequent insertions and deletions.
  • Performance:
    • Access: O(n) (poor for random access).
    • Insert/Delete: O(1) (when modifying head or tail).

Example:

List<Integer> numbers = new LinkedList<>();
numbers.add(10);  
numbers.addFirst(5); // Add at head  

3. Vector

  • What It Is: An array-based list that is thread-safe.
  • When to Use: In multi-threading environments (although ArrayList with explicit synchronization is preferred).
  • Disadvantage: Being synchronized makes it slower than ArrayList.

Example:

List<String> colors = new Vector<>();
colors.add("Red");  
colors.add("Blue");  

4. Stack

  • What It Is: A Vector subclass that implements LIFO (Last-In-First-Out).
  • Methods:push(), pop(), peek().
  • When to Use: For undo/redo operations, parsing expressions, and backtracking algorithms.

Example:

Stack<String> stack = new Stack<>();
stack.push("Task1");  
stack.push("Task2");  
System.out.println(stack.pop()); // Output: Task2  

ArrayList Vs. LinkedList Vs. Vector Vs. Stack

Class Underlying Data Thread-Safe? Use Cases
ArrayList Dynamic array No Read-heavy operations
LinkedList Doubly linked list No Frequent insertions/deletions
Vector Array Yes Legacy applications
Stack Array (Vector) Yes LIFO-based operations

Best Practices When Using Java Lists

  1. Choose the Right Implementation:
    • Default to ArrayList for most use cases.
    • Use LinkedList for queue-like behavior (addFirst(),removeLast()).
  2. Avoid Synchronized Classes: Use Collections.synchronizedList() with ArrayList instead of Vector.
  3. Preallocate Capacity: Initialize larger ArrayLists with a capacity to reduce resizing overhead.
  4. Leverage Java 8+ Features: Use streams and lambda functions for filtering, mapping, and sorting.

Frequently Asked Questions on Java Lists

Question 1: When should I use ArrayList as opposed to LinkedList?

  • ArrayList: Best for random access and read-heavy operations.
  • LinkedList: Best for frequent insertions/deletions.

Question 2: Is Vector still relevant in modern-day Java?

  • Vector is largely outdated. Use CopyOnWriteArrayList or java.util.concurrent classes for thread safety.

Question 3: How do I convert a List to an array?

  • Use String[] array = list.toArray(new String[0]);

4: How do I sort a List?

  • Use Collections.sort(list) or list.sort(Comparator).


By mastering the Java List interface and its implementations, you can write efficient, scalable code. Whether you are building high-performance applications with ArrayLists, managing complex workflows with LinkedLists, or using Vectors for legacy applications, understanding their strengths and weaknesses is key.

Found this guide helpful? Share with a friend!

Stay tuned for more tutorials on Java Collections, Spring Boot, and System Design.

Keywords: Java List interface, ArrayList vs LinkedList, Vector and Stack in Java, Java Collections tutorial, List implementations in Java.


Jsp life cycle


     
  • jsp engine controls the life cycle of jsp
  • Jsp life cycle is described by three life cycle methods and six life cycle phases

Jsp life cycle methods :

  • jspInit()
  • _jspService()
  • jspDestroy()
Jsp Life Cycle

  • Jspinit() method is invoked when JSP page is initialized.
  • The _jspService() method corresponds to the body of the jsp page.
  • This method is defined automatically by the JSp container and should never be defined y the JSP page author.

Jsp Life cycle Phases: 

  • Translation phase
  • Compilation phase
  • Instantiation phase
  • initialization phase
  • Servicing phase
  • Destruction phase

Jsp Life Cycle methods




  • Jsp engine calls jspInit() method only once during the initialization phase of a jsp.
  • similarly during destruction phase jsp engine calls jspDestory() method only once
  • For each client request Jsp container calls _jspService() method once.

Jsp Translation phase:

  • When client request comes for a jsp for the first time , jsp engine makes a full read of the jsp verifies the syntactical corectness of the jsp elements and converts code into a servlet source code .
  • The process of JSP engine translating jsp into servlet nothing but translation phase of JSP.
  • Therefore , we say that Jsp development is another style of development  asking container to develop the servlet is nothing but JSP developement
  • Container generated servlet class is also known as page implementation class.

Jsp Compilation phase:

  • The process of jsp engine compiling the page implementation class is nothing but compilation phase of jsp.
  • Jsp engine uses JASPER compiler to compile the container generated servlet class source code.
  • In the life of the Jsp Translation and compilation happens only once unless jsp source code modified.

Jsp Instantiation phase:

  • Container creating the instance of generated servelt class is nothing but instantialtion phase of jsp
  • actually now we have a servelt object.
  • Servlet engine loads user user defined servlet class file from secondary memory into
    primary memory dynamically

    class c= class.forName("name");
    c.newInstance();
  • Servlet engine creates the instance of loaded servlet class.
  • Servlet engine uses the following piece of code to load the servlet clas  dynamically to instantiate it.
    Class c= class.forName("Servlet class name");
    c.newInstance();


Initialization:

  • Servlet engine creates servletConfig object
  • Servlet engine calls the init() method on the servlet instance by supplying servletconfig object
    as argument.
  • Once init method completely executed servlet is ready to serve the client request.

Servicing : 

  • Servlet engine creates servlet request and servlet response object based on the web server
    provided client information.
  • Servlet engine calls service method on the servlet instance by supplying two object reference as arguments
  • Once service method is completely executed , client request is served and request-response cycle is complete.
  • Within the service method request object is used to capture the user input
  • Response object is used to build the dynamic page and hand over the same to the web server

Destruction:

  • Destruction phase of servlet represents servlet being removed from use by container

Jsp scripting elements

  • Jsp scripting elements are used to embed jva code in to the jsp.
  • Jsp scripting elements are three types
    1. Declaration
    2. Expression
    3. Scriplet

Jsp Declaration:

  • Jsp declaration is one of the three scripting elements.
  • it is used to embed java code into the jsp
  • A Jsp declration starts with "<%!" and ends with "%>".
  • <%! int a%>.
  • Instance variables, instance methods, static methods can be declared and defined in ajsp declaration.
  • During translation time of jsp they became members of container generated servlate/page implementation class.

Jsp Expression:

  • Jsp Expression is one of the three scripting elements.
  • it is used to embed java code into the js.
  • A jsp expression starts with "<%=" and ends with "%>".
  • <%=a+b%>
  • within a Jsp expression only one java expression that too without semicolon is placed.
  • When Jsp expression is evaluated two thing will happen in the backend
    1. Java expression is evaluated
    2. The result is sent to the browser stream.
  •  we can have any number of jsp expressions in ajsp.
  • During translation phase each java expression of a jsp expression is placed in into _jspService()
    method of page implemented class


Jsp Scriplet:

  • Jsp scriplet is one of the three scripting elements.
  • it is used to embed java code into the js.
  • A jsp scriplet starts with "<%" and ends with "%>".
  • <% java code%>
  • To serve the client request what ever java code required that is placed in servlet.
  • In servlet programming whatever code we write in the service() method of user defined servlet all that code can be placed in a jsp scriplet.
  • During the translation phase java code placed in the scriplet is written in to _jspService() method of page implementation class.
  • in jsp we can have any number of scriplets.

Select Menu