Reverse number program in java

  1. package com.instaceofjavaforus;
    public class Reversenum {
    public static void main(String[] args) {

    int rev=0;
    int num=1234;
    while(num>0){
    int rem=num%10;
    rev=rem+(rev*10);
    num=num/10;

    }
    }
    }


Check whether string is palindrome or not


1.Palindrome program in java using for loop

 

  1. package com.instaceofjava;
  2.  
  3. public class PalindromeDemo{  
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String str="MADAM";
  8. String revstring="";
  9.  
  10. for(int i=str.length()-1;i>=0;--i){
  11. revstring +=str.charAt(i);
  12. }
  13.  
  14. System.out.println(revstring);
  15.  
  16. if(revstring.equalsIgnoreCase(str)){
  17. System.out.println("The string is Palindrome");
  18. }
  19. else{
  20. System.out.println("Not Palindrome");
  21. }
  22.  
  23. }
  24. }


  Output:

  1. The string is Palindrome

 

2.palindrome program in java using stringbuffer

 

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class Palindrome {
  5.  
  6. public static void main(String[] args)
  7. {
  8.  
  9.  Scanner in = new Scanner(System.in);
  10.  System.out.println("Enter a string");
  11.  String str=in.nextLine();
  12.  
  13.  StringBuffer strone=new StringBuffer(str);
  14.  StringBuffer strtwo=new StringBuffer(strone);
  15.  
  16.   strone.reverse();
  17.  
  18.   System.out.println("Orginal String ="+strtwo);
  19.   System.out.println("After Reverse ="+strone);
  20.  
  21.  if(String.valueOf(strone).compareTo(String.valueOf(strtwo))==0)
  22.    System.out.println("Result:Palindrome");
  23.     else
  24.     System.out.println("Result:Not Palindrome");
  25.  
  26.     }
  27. }

 Output:

  1. Enter a string
  2. MOOM
  3. Orginal String =MOOM
  4. After Reverse =MOOM
  5. Result:Palindrome

Simple palindrome program in java:

3.Program to Check given number is palindrome or not

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class Palindrome {
  5.  
  6. public static void main(String[] args)
  7. {
  8.  
  9.  System.out.println("Please Enter a number : ");
  10.  
  11.         int givennumber = new Scanner(System.in).nextInt();
  12.  
  13.         int number=givennumber;
  14.         int reverse=0;
  15.  
  16.         while (number != 0) {
  17.  
  18.             int remainder = number % 10;
  19.             reverse = reverse * 10 + remainder;
  20.             number = number / 10;
  21.         }            
  22.  
  23.  if(givennumber == reverse)
  24.    System.out.println("Result:Palindrome");
  25.     else
  26.     System.out.println("Result:Not Palindrome");
  27.  
  28.     }
  29. }

 Output:

  1. Please Enter a number : 
  2. 535
  3. Result:Palindrome


Java programming interview questions
  1. Print prime numbers? 
  2. Dynamic polymorphism in Java 
  3. Find missing numbers in an array
  4. Collection vs Collections
  5. Custom iterator in java 
  6. Unreachable Blocks in java
  7. Enum in java  
  8. toString() method in java with example program
  9. Explain Hibernate Configuration file
  10. What happens if we place return statement in try catch blocks 
  11. Write a java program to convert binary to decimal 
  12. Java interview questions on exception handling 
  13. Java Program to convert Decimal to Binary
  14. Java program to restrict a class from creating not more than three objects
  15. Java basic interview programs on this keyword 
  16. Interfaces allows constructors? 
  17. Can we create static constructor in java 
  18. Super keyword interview questions java 
  19. Java interview questions on final keyword
  20. Can we create private constructor in java
  21. Java Program Find Second highest number in an integer array 
  22. Java interview programming questions on interfaces 
  23. Top 15 abstract class interview questions  
  24. Java interview Questions on main() method  
  25. Top 20 collection framework interview Questions
  26. Java Interview Program to find smallest and second smallest number in an array 
  27. Java Coding Interview programming Questions : Java Test on HashMap  
  28. Explain java data types with example programs 
  29. Constructor chaining in java with example programs 
  30. Swap two numbers without using third variable in java 
  31. Find sum of digits in java 
  32. How to create immutable class in java 
  33. AtomicInteger in java 
  34. Check Even or Odd without using modulus and division  
  35. String Reverse Without using String API 
  36. Find Biggest substring in between specified character
  37. Check string is palindrome or not?
  38. Reverse a number in java?
  39. Fibonacci series with Recursive?
  40. Fibonacci series without using Recursive?
  41. Sort the String using string API?
  42. Sort the String without using String API?
  43. what is the difference between method overloading and method overriding?
  44. How to find largest element in an array with index and value ?
  45. Sort integer array using bubble sort in java?
  46. Object Cloning in java example?
  47. Method Overriding in java?
  48. Program for create Singleton class?
  49. Print numbers in pyramid shape?
  50. Check armstrong number or not?
  51. Producer Consumer Problem?
  52. Remove duplicate elements from an array
  53. Convert Byte Array to String
  54. Print 1 to 10 without using loops
  55. Add 2 Matrices
  56. Multiply 2 Matrices
  57. How to Add elements to hash map and Display
  58. Sort ArrayList in descending order
  59. Sort Object Using Comparator
  60. Count Number of Occurrences of character in a String
  61. Can we Overload static methods in java
  62. Can we Override static methods in java 
  63. Can we call super class static methods from sub class 
  64. Explain return type in java 
  65. Can we call Sub class methods using super class object? 
  66. Can we Override private methods ? 
  67. Basic Programming Questions to Practice : Test your Skill
  68. Java programming interview questions on collections

Reverse a string without using string function in java


  1. How to reverse a string in java without using reverse function
  2. Reverse a string in java
  3. Write a program to reverse string without using any function java
  • First of all "there is no direct built in function or method in string class to reverse a string" but still it is frequently asked question in java interviews.
  • It's not possible to reverse a string without using string methods. (length(),chgarAt())



public static String reverseString(String s) {
    char[] chars = s.toCharArray();
    int left = 0;
    int right = chars.length - 1;
    while (left < right) {
        char temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
        left++;
        right--;
    }
    return new String(chars);
}

This method converts the input string to a character array using the toCharArray() method. Then, it initializes two pointers, left and right, to the first and last positions in the array, respectively.

Then, it enters a while loop that continues as long as the left pointer is less than the right pointer. In each iteration of the loop, the characters at the positions indicated by the left and right pointers are swapped using a temporary variable. Then, the left and right pointers are incremented and decremented, respectively.

Finally, the reversed character array is converted back to a string and returned.

This method is more efficient than using string functions because strings are immutable in Java and any operation that modifies the string creates a new object, whereas a character array can be modified in place.



reverse string without using string function


  • Lets discuss on how to reverse a string in java with using any built in string functions or methods.
  1. Using charAt() function/method

1:Using charAt():

  • Take a for loop and iterate string by checking length of the string from n to 1.
  • Use charAt() method of string and take each  character and append to another string.
  • By the end of the loop you will get all characters in reverse order.
  • Like this we can reverse a string in java with using string method.

#1: Reverse a string in java with using inbuilt function

  1. package com.instaceofjava;
  2.  
  3. public class ReverseString {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String str="Hello world";
  8. String revstring="";
  9.  
  10. for(int i=str.length()-1;i>=0;--i){
  11. revstring +=str.charAt(i);
  12. }
  13.  
  14. System.out.println(revstring);
  15. }
  16. }


OutPut:


  1. dlrow olleH


  • This program reads a string from the user, and then uses a loop to iterate over the characters in the string in reverse order. It appends each character to a new string called reversed, and then prints out the reversed string after the loop has finished.
  • Note that this program does not modify the original string, but creates a new reversed string instead. If you want to reverse the original string in place, you can use an array of characters instead of a string, and swap the elements at opposite ends of the array until you reach the middle.
Here is a simple Java program that reverses a string without using any string functions:


  • This program works by first converting the input string to a character array using the toCharArray method. 
  • It then uses two pointers, i and j, to traverse the array from opposite ends. On each iteration, it swaps the characters at indices i and j, and increments i and decrements j until they meet in the middle. 
  • Finally, it converts the reversed character array back to a string using the String constructor.
2: Using StringBuffer Object:

Another way to reverse a string in Java without using any built-in string functions is to use a StringBuilder or StringBuffer object.

Here is an example using a StringBuilder:

public static String reverseString(String s) {
    StringBuilder sb = new StringBuilder(s);
    return sb.reverse().toString();
}

Here, the input string is passed to the constructor of the StringBuilder object. Then, the reverse() method is called on the object, which reverses the order of the characters in the string. Finally, the toString() method is called on the StringBuilder object to convert it back to a string and return it.

StringBuffer is similar to StringBuilder, it is thread safe, whereas StringBuilder is not.

public static String reverseString(String s) {
    StringBuffer sb = new StringBuffer(s);
    return sb.reverse().toString();
}

The above approach is more efficient than the previous one that used a character array because it avoids the need to create a temporary array and copy the characters to it.

In both cases, the method takes a single string parameter and returns the reversed version of it.

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

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"%>




Select Menu