Print 1 to 10 without using loop in java?

  •  Basically to display numbers from 1 to 10 or a series we will use for , while or do while loop
  • So here is the programs to do same thing without using loop.
  • This is possible in two ways
  • First one is to display by printing all those things using system.out.println.
  • second one is by using recursive method call lets see these two programs

Solution #1:


  1. package com.instanceofjavaTutorial;
  2.  
  3. class Demo{  
  4.  
  5. public static void main(String args[]) { 

  6.    System.out.println(1);
  7.    System.out.println(2);
  8.    System.out.println(3);
  9.    System.out.println(4);
  10.    System.out.println(5);
  11.    System.out.println(6);
  12.    System.out.println(7);
  13.    System.out.println(8);
  14.    System.out.println(9);
  15.    System.out.println(10);
  16.  
  17. }

  18. }

Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10



Solution #2


  1. package com.instanceofjavaTutorial; 
  2. public class Main {
  3.     public static void main(String[] args) {
  4.         printNumbers(1, 10);
  5.     }

  6.     public static void printNumbers(int start, int end) {
  7.         if (start > end) {
  8.             return;
  9.         }
  10.         System.out.println(start);
  11.         printNumbers(start + 1, end);
  12.     }
  13. }
  • This uses recursion to achieve the same result. In this example, the method printNumbers is called with the start and end numbers as arguments. Inside the method, it checks if the start number is greater than the end number and if so, it returns (ends the recursion). 
  • If not, it prints the current start number and then calls the printNumbers method again with the start number incremented by 1. 
  • This continues until the start number is greater than the end number and the recursion ends.
  1. package com.instanceofjavaTutorial; 
  2. class PrintDemo{
  3.  
  4. public static void recursivefun(int n) 
  5.  
  6.   if(n <= 10) {
  7.  
  8.        System.out.println(n); 
  9.          recursivefun(n+1);   }
  10. }
  11.  
  12. public static void main(String args[]) 
  13. {
  14.  
  15. recursivefun(1); 
  16.  
  17.  }
  18.  
  19. }




Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Programming Questions on Static

1. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StaticDemo{
  4.  
  5.  
  6.    static {
  7.           i=10;
  8.     }
  9.  
  10.     static   int i;  
  11.  
  12.       public static void main(String[] args) {
  13.  
  14.        System.out.println("i= "+i);
  15. }
  16. }





2. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StaticDemo{
  4.  
  5.    static {
  6.           i=10;
  7.     }
  8.  
  9.     static   int i;  
  10.  
  11.       public static void main(String[] args) {
  12.         StaticDemo obj= new StaticDemo();
  13.           obj.i=20;
  14.  
  15.        System.out.println("i= "+StaticDemo.i);
  16. }
  17. }






Type Casting in java?

Type Casting:

Type casting means to explicitly convert one type of data to another type of data. 

Type casting has 2 types:
  • Upcasting
  • Downcasting

Upcasting:

Converting lower type value to upper type value is known as Upcasting.
http://instanceofjavaforus.blogspot.in/

Program:

package com.instanceofjavaforus;
public class Upcastingtest {
public static void main(String[] args) {
int a=100;
long b=a;
float c=b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}

}

Output:

100
100
100.0

Downcasting:

Converting upper type value to lower type value is known as Downcasting.
http://instanceofjavaforus.blogspot.in/

Program:

package com.instanceofjavaforus;
public class Downcastingtest {
public static void main(String[] args) {
double a=10.4;
long b=(long)a;
int c=(int)b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}

}

Output:

10.4
10
10

Program :

package com.instanceofjavaforus;
class Simple{
public static void main(String args[]){

char ch = 'A';
long a = ch;
System.out.println(a);
}

}

Output:
65

Program:

package com.instanceofjavaforus;
class Simple{
public static void main(String args[]) {
double d = 10.5;
int i = (int) d;
System.out.println(i);
}
}

Output:
10

Programming Interview Questions on loops

Think Output:

Program #1:

  1. package com.instanceofjavaforus;
  2.  
  3. public class Loops {
  4.  
  5. public static void main(String args[]){
  6.  
  7.             int i=0;
  8.  
  9.             for( i=0;i<5;i++){               
  10.                 System.out.println(i);
  11.              }
  12.  
  13.              System.out.println("value of i after completion of loop: "+i);
  14. }
  15. }





Program #2:

 

  1. package com.instanceofjavaforus;
  2.  
  3. public class LoopsDemo2 {
  4.  
  5. public static void main(String args[]){
  6.  
  7.           int a=0,b=0;
  8.  
  9.             for(int i=0;i<5;i++){
  10.                 if(++a>2||++b>2){
  11.                    a++;
  12.                   }
  13.           }
  14.  
  15.           System.out.println("a= "+a+" b="+b);
  16.         
  17. }
  18. }









Program #3:

  1. package com.instanceofjavaforus;
  2.  
  3. public class LoopsDemo3 {
  4.  
  5. public static void main(String args[]){        
  6. int i=5;
  7. System.out.println(i++);
  8. System.out.println(i--);
  9. }
  10. }




Convert Byte Array to String

  • To convert byte array to string we have a constructor in String class which is taking byte array as an argument.
  • So just we need to pass byte array object to string as argument while creating String class object.

  1.  package com.instanceofjavaforus;
  2.  
  3. public class ByteArrayToString {
  4.    /*
  5.    * This method converts a byte array to a String object.
  6.      */
  7.  
  8.     public static void convertByteArrayToString() {
  9.  
  10.         byte[] byteArray = new byte[] {78,73, 67,69};
  11.         String value = new String(byteArray);
  12.        System.out.println(value);
  13.  
  14.     }
  15.  
  16.     public static void main(String[] args) {
  17.         ByteArrayToString.convertByteArrayToString();
  18.     }
  19.  
  20. }

Output:


  1. NICE

 

Convert String to Byte Array:

  1.  package com.instanceofjava;
  2. public class StringTOByteArray{
  3.    /*
  4.    * This example shows how to convert a String object to byte array.
  5.      */

  6.     public static void main(String[] args) {
  7.       
  8.     String data = "Instance of java";
  9.  
  10.     byte[] byteData = data.getBytes();
  11.  
  12.     System.out.println(byteData);
  13.  
  14.     }
  15.  
  16. }



Output:


  1. [B@3b26456a

Convert values of a Map to a List

Java How To Convert Map Values To List In Java Some Different Ways Below are some common methods for doing so:

1. How to use values() with ArrayList

You can convert the values of a Map to a List in Java using various approaches. 

below are a few common methods:

1. Using ArrayList andvalues()

import java.util.*;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        // Convert values to List
        List<String> list = new ArrayList<>(map.values());

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

2. Using Java 8 Stream API

import java.util.*;
import java.util.stream.Collectors;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = Map.of(1, "Apple", 2, "Banana", 3, "Cherry");

        // Convert values to List using Stream
        List<String> list = map.values().stream().collect(Collectors.toList());

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

3. Using forEach Loop

import java.util.*;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        List<String> list = new ArrayList<>();
        map.values().forEach(list::add);

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

💡 Choose the method based on your Java version:

  • Use ArrayList<>(map.values()) for simple cases.
  • Use Stream API (map.values().stream().collect(Collectors.toList())) in Java 8+ for a functional approach.
  • Use a forEach loop if modifying the list during iteration.


  1. package com.instanceofjavaforus;

  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6.  
  7. public class MapValueToList {
  8.  
  9.  Map<Integer, String> map;
  10.  
  11.  public MapKeyToList(Map<Integer, String> map) {
  12.       this.map = map;
  13.  }
  14.  public List<String> convertValuesToList() {
  15.     return new ArrayList(map.values());
  16.  }
  17.  
  18.  public static void main(String[] args) {           
  19.  Map<Integer, String> map = new HashMap<>();
  20.  
  21.     map.put(1, "one");
  22.     map.put(2, "two");
  23.     map.put(3, "three");
  24.     map.put(4, "Four");
  25.     map.put(5, "Five");
  26.     map.put(6, "Six");
  27.     map.put(7, "Seven");
  28.     map.put(8, "Eight");
  29.     map.put(9, "Nine");
  30.     map.put(10, "Ten");
  31.  
  32.      MapValueToList  conv = new MapValueToList (map);
  33.      List<String> keysList = conv.convertValuesToList();
  34.      System.out.println("Values:");
  35.     for (String val : keysList) {
  36.        System.out.println(val);
  37. }
  38.  
  39.  }
  40. }
  41. OutPut:
  42. Values:
  43. one
  44. two
  45. three
  46. Four
  47. Five
  48. Six
  49. Seven
  50. Eight
  51. Nine
  52. Ten

     


Map to list in java example

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6.  
  7. public class MapKeyToList {
  8.  
  9.  Map<Integer, String> map;
  10.  
  11.  public MapKeyToList(Map<Integer, String> map) {
  12.  this.map = map;
  13. }
  14.  
  15.  public List<Integer> convertKeysToList() {
  16.    return new ArrayList(map.keySet());   
  17. }   

  18. public static void main(String[] args) {
  19.  
  20.  Map<Integer, String> map = new HashMap<>();
  21.     map.put(1, "one");
  22.     map.put(2, "two");
  23.     map.put(3, "three");
  24.     map.put(4, "Four");
  25.     map.put(5, "Five");
  26.     map.put(6, "Six");
  27.     map.put(7, "Seven");
  28.     map.put(9, "Nine");
  29.     map.put(10, "Ten");
  30.  
  31.     MapKeyToList conv = new MapKeyToList(map);
  32.     List<Integer> keysList = conv.convertKeysToList();
  33.  
  34.      System.out.println("Keys:");
  35.  
  36.      for (Integer key : keysList) {
  37.         System.out.println(key);
  38.    }
  39.  
  40.  }
  41. }
  42. OutPut:
  43. Keys:
  44. 1
  45. 2
  46. 3
  47. 4
  48. 5
  49. 6
  50. 7
  51. 8
  52. 9
  53. 10

Marker Interfaces in java

Marker interface:

  • The interfaces using which we explicitly mention or mark certain properties to the object are known as marker interface.
  • An interface that is used to check / mark / tag the given object is of a specific type to perform a special operations on that object.
  • Marker interfaces will not have methods , they are empty interfaces.

 Need of marker interface: 

  • It i used to check , whether we can perform some special operations on the passed object
  • For ex: using serializable  interface we can explicitly mention that object of a class is transferable. else it can not.
  • If a class is deriving form java.lang.Cloneable interface then that object can be cloned, else it can not
  • In side those particular methods , that method developer will check that the passed object is of type the given interface or not by using "instanceof" operator.


Predefined marker interfaces:

  1. java.lang.Cloneable
  2. java.io.Serializable
  3. java.util.RandomAccess
  4. java.util.Eventlistener
  5. java.rmi.Remote
  6. java.servlet.SingleThreadModel




Object class in java

Java.lang.Object class:

  • Object is the root or super class of the class hierarchy. Which is present in java.lang package.
  • All predefined classes and user defined classes are sub classed from Object class

Why object class is super class for all java classes:

  1. Re-usability:
    • Every object has 11 common properties.
    • These properties must be implemented by every class developer.
    • So to reduce burden on developer SUN developed a class called Object by implementing all these 11 properties with 11 methods.
    • All these methods have generic logic common for all sub classes. if this logic is not satisfying subclass requirement then subclass can override it.
     
  2. Run time polymorphism:
    • To achieve run time polymorphism so that we can write single method to receive and send any type of class object as argument and as return type.

Why this class name is chosen as object?

  • As per coding standards , class name must convey the operations doing by that class.
  • So this class name is chosen as Object as it has all operations related to object.
  • These operations are chosen based on real world object's behavior.

Common functionalities of every class object: 

  1. Comparing two objects: 

    • public boolean equals(Object obj)
  2. Retrieving hashcode: 

    • public int hashcode()
  3. Retrieving the run time class object reference:

    • public final Class getClass()
  4. Retrieving object information in String format:

    • public String toString()
  5. Cloning object: 

    • protected Object clone()
                      throws CloneNotSupportedException
  6. Object clean-up code/ resources releasing code: 

    •  protected void finalize()
                       throws Throwable
  7. To wait current thread until another thread invokes the notify():

    • public final void wait()
                      throws InterruptedException
  8. To wait current thread until another thread invokes the notify() specified amount of time:

    • public final void wait(long timeout)
                      throws InterruptedException
  9.  To wait current thread until another thread invokes the notify() specified amount of time

    • public final void wait(long timeout,int nanos)
                      throws InterruptedException
  10. Notify about object lock availability to waiting thread: 

    • public final void notify()
  11. Notify about object lock availability to waiting threads: 

    • public final void notifyAll() 
  • All above operations are implemented with generic logic that is common for all objects, so that developer can avoid implementing these common operations in every class.
  • Also Oracle ensures that all these operations are overridden by developers with the same method prototype. This feature will provide run time polymorphism.

What are the methods we can override in sub class from Object class:

  1. equals()
  2. hashCode()
  3. toString()
  4. clone()
  5. finalize()

Example program on toString() method :

  1. package com.instanceofjavaforus;
  2.  
  3. public class ToStringDemo {
  4.     int id;
  5.    String name;
  6.  
  7. public String toString(){
  8.  return id+" "+name;
  9.  }
  10.  
  11.  public int getId() {
  12.    return id;
  13.  }
  14.  
  15. public void setId(int id) {
  16.   this.id = id;
  17.  }
  18.  
  19.  public String getName() {
  20.       return name;
  21.  }
  22.  
  23.  public void setName(String name) {
  24.     this.name = name;
  25.   }
  26.  
  27.   public static void main(String[] args) {
  28.  
  29.    ToStringDemo obj = new ToStringDemo();
  30.      obj.setId(1);
  31.      obj.setName("abc");
  32.     System.out.println(obj);
  33.  
  34.  }
  35. }

  36. OutPut:
  37. 1 abc


Example program on clone() method:

  1.  
  2. package com.instanceofjava;
  3.  
  4. public class CloneDemo  implements Cloneable  {
  5.   int a=0;
  6.    String name="";
  7.   CloneDemo (int a,String name){
  8.  this.a=a;
  9.  this.name=name;
  10.  }
  11.   public CloneDemo clone() throws CloneNotSupportedException{
  12.  return (CloneDemo ) super.clone();
  13. }
  14.  public static void main(String[] args) {
  15.  CloneDemo e=new CloneDemo (2,"abc");
  16.  System.out.println(e.name);
  17.     try {
  18.  CloneDemo b=e.clone();
  19.  System.out.println(b.name);
  20. } catch (CloneNotSupportedException e1) {
  21.  // TODO Auto-generated catch block
  22.   e1.printStackTrace();
  23. }
  24. }
  25.  
  26. }
  27.  
  28. OutPut:
  29. abc
  30. abc

Remove duplicates from an array java

Removing duplicate elements form an array using collections:

  1. package com.instanceofjavaTutorial;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7.  
  8. public class RemoveDupArray {
  9.  
  10.   public static void main(String[] args) {
  11.  
  12.   // A string array with duplicate values
  13.    String[] data = { "E", "C", "B", "E", "A", "B", "E", "D", "B", "A" };
  14.  
  15. System.out.println("Original array         : " + Arrays.toString(data));
  16.  
  17.  List<String> list = Arrays.asList(data);
  18.  Set<String> set = new HashSet<String>(list);
  19.  
  20.   System.out.print("After removing duplicates: ");
  21.   String[] resarray= new String[set.size()];
  22.    set.toArray(resarray);
  23.  
  24.  for (String ele: resarray) {
  25.  
  26.  System.out.print(ele + ", ");
  27.  
  28.  }
  29.  
  30. }
  31.  
  32. }



  1. OutPut:
  2. Original array         : [E, C, B, E, A, B, E, D, B, A]
  3. After removing duplicates: D, E, A, B, C




You Might Like:

1. Java Interview Programs On Core Java

2. Java Interview Programs On Collections 

3. What is The Output Of Following Programs Java Interview:

4. Java Concept and Example Program

VarArgs in java

  • The full form of var-arg is variable length arguments.
  • Till JDK 1.4 we must define overloaded methods to pass different list of arguments .
  • But using this feature we can define method to pass ZERO to 'n'  number of arguments.
  • Syntax: After data type we must place three dots.


  1.          void method(int... i){
  2.          }
  • Internally Var-arg is a single dimensional array. So we can also pass single dimensional array as argument.
  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int... args){
  4. for(int i=0;i<args.length;i++){
  5. System.out.println(args[i]);
  6. }
  7. System.out.println();
  8. }
  9. public static void main(String args[]){
  10.  Vdemo obj= new Vdemo();
  11. int x={1,2};
  12. obj.print(x);// works fine
  13. obj.print(1,2,3,4);// works fine
  14. obj.print();// works fine
  15. //int... var=new int[5]; compile time error: not a valid statement
  16.  
  17. Output:
  18. 1
  19. 2

  20. 1
  21. 2
  22. 3
  23. 4

It must be last argument:

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3. void print(int x){
  4.  System.out.println("int x");
  5. }
  6.  
  7. void print(int x, int y){
  8.  System.out.println("int x, int y");
  9.  void print(int x, int y,int... args){
  10. System.out.println("int x, int y,int... args");
  11. }
  12. void print(int... args){
  13. System.out.println("int x, int y");
  14. }
  15.  public static void main(String args[]){
  16.  Vdemo obj= new Vdemo();
  17. int x={1,2};
  18. obj.print(1);
  19. obj.print(x);// works fine
  20. obj.print(1,2,3,4);// works fine
  21. obj.print();// works fine
  22. //int... var=new int[5]; compile time error: not a valid statement

  23. Output:
  24. int x
  25. int x, int y
  26. int x, int y,int... args
  • if we declared  placed any type after var-arg in the arguments list of a method then it throws a compile time error.

  1. void print(int x, int y, int...args, int z){// compile time error
  2. // throws Compile time error:The variable argument type int of the method print must be the
  3.  // last parameter
  4.  System.out.println("int x, int y");
  5.  void print(int x, int y,int... args){  // valid
  6. System.out.println("int x, int y,int... args");
  7. }
Overloading method with normal and varargs types :

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int... args){
  4. System.out.println("var arg method");
  5. }
  6. void print(int args){
  7. System.out.println("normal method");
  8. }
  9.  
  10. public static void main(String args[]){
  11.  Vdemo obj= new Vdemo();
  12. obj.print(1);// works fine
  13.  }
  14. Output:
  15. normal method

Overloading method with normal and varargs types in super and sub classes:

var args Program 1:

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int... args){
  4. System.out.println("super class method");
  5. }

  1. package instanceofjavaforus;
  2. public class Test extends VDemo{ 
  3.  void print(int args){
  4. System.out.println("sub class method");
  5. }
  6. public static void main(String args[]){
  7.  VDemo vobj= new VDemo();
  8. vobj.print(10);
  9. Test tobj= new Test();
  10. tobj.print(10);
  11. }
  12. }
  13. OutPut:
  14. Super class method
  15. Sub class method

var args Program 2:

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int args){
  4. System.out.println("super class method");
  5. }
  6. }



  1. package instanceofjavaforus;
  2.  
  3. public class Test extends VDemo{ 
  4.  
  5.  void print(int... args){
  6. System.out.println("sub class method");
  7. }
  8. public static void main(String args[]){
  9.  
  10.  VDemo vobj= new VDemo();
  11. vobj.print(10);
  12. Test tobj= new Test();
  13. tobj.print(10);
  14.  
  15. }
  16. }
  17. OutPut:
  18. Super class method
  19. Super class method

How to Convert string to date in java


  • Whenever are having a requirement of converting string (date as string ) in to date we need to use SimpledateFormat class which is present in java.text package.
  • To convert string to date in java we need to follow two steps.
  • First we need to create SimpledateFormat class object by passing pattern of date which we want as a string.
  • Ex: SimpleDateFormat  formatter = new SimpleDateFormat("dd/MM/yyyy");
  • And next we need to call parse() method on the object of  SimpleDateFormat then it will returns Date object.
  • parse() method  throws ParseException so need to handle this exception.
  • By using format method of the object will get string format of given date
  • formatter.format(date).
  • How to convert java string to date object 
  • Java SimpleDateFormat String to Date conversion and parsing examples
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 2015; 15
Y Week year Year 2009; 09
M Month in year Month July; Jul;07
w Week in year Number 25
W Week in month Number 3
D Day in year Number 143
d Day in month Number 37
F Day of week in month Number 1
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 12
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 30
S Millisecond Number 778
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
(Ref: Oracle DOCS)

Example program on SimpleDateFormat :

1. Convert string to date in java in MMM dd, yyyy format

Input : Jan 1, 2015 (MMM dd, yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6. SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");
  7. String dateInString = "Jan 1, 2015"; 
  8.  
  9. try{
  10.  
  11. Date date = formatter.parse(dateInString);
  12. System.out.println(date);
  13. System.out.println(formatter.format(date));  
  14.  
  15. }catch(ParseException e){
  16. e.printStackTrace();
  17. }
  18. }

  19. Output: 
  20. Thu Jan 01 00:00:00 IST 2015
  21. Jan 01, 2015




2.How to convert string into date format in java day MMM dd, yyyy format example

 Input : Sat, Feb 14 2015 (E, MMM dd yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
  8. String dateInString = "Sat, February 14 2015"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. Output: 
  22. Sat Feb 14 00:00:00 IST 2015
  23. Sat, Feb 14 2015



3. Convert string to date in java in dd/MM/ yyyy format example program

Input : 01/01/2015 (dd/MM/yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy);
  8. String dateInString = "01/01/2015";
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date)); 
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 01/01/2015


4. Convert string to date in java in dd-MMM-yyyy format example program

Input : 1-Jan-2015 (dd-MMM-yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6. SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
  7. String dateInString = "1-Jan-2015"; 
  8.  
  9. try{
  10.  
  11. Date date = formatter.parse(dateInString);
  12. System.out.println(date);
  13. System.out.println(formatter.format(date));  
  14.  
  15. }catch(ParseException e){
  16. e.printStackTrace();
  17. }
  18. }

  19. Output: 
  20. Thu Jan 01 00:00:00 IST 2015
  21. 01-Jan-2015


  5. Convert string to date in java in yyyyMMdd format example program

Input : 20150101 (yyyyMMdd):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
  8. String dateInString = "20150101"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 20150101


6.Convert string to date in java in ddMMyyyy format example program

Input : 01012015 (ddMMyyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy");
  8. String dateInString = "01012015"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 01012015


7.Convert string to date in java in dd-MMM-yy format example program

Input : 01-January-15 (dd-MMM-yy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("dd-MMMM-yy");
  8. String dateInString = "01-January-2015"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 01012015


8.Convert string to date in java in dd-M-yyyy HH:mm:SS format example program

 
convert string to date in java

JVM Architecture

  • This topic clears your questions like Explain jvm architecture in java  , jvm architecture in java with diagram, how JVM works internally and areas of Java Virtual Machine.
  • Virtual machine : In general terms Virtual machine is a software that creates an environment between the computer and end user in which end user can operate programs.
  • As per functionality Virtual machine is creation of number of different identical execution environments on a single computer to execute programs is called Virtual machine.
  • Java Virtual machine: it is also Virtual machine that runs java bytecode  by creating five identical run time areas to execute class members.

Function of java virtual machine

  • The bytecode is generated by java compiler in a JVM understandable format.
  • As a programmer we develop a java application and when we compile a java program, the compiler will generate .class (dot class) file.
  • The .class file contains byte code (Special java instructions).
  • To execute a java program we take the help of JVM (java virtual machine) to the JVM we have to provide .class file as the input.

Types of JVMs:

  • The java 2 SDK , Standard Edition , contains two implementation of the java virtual machine 
  1. Java HotSpot Client VM
  2. Java Hotspot Server VM

Java HotSpot Client VM:

  • The Hotspot Client VM is the default virtual machine of the java 2 SDK and java 2 run time environment .
  • As its name implies, it is tuned for best performance when running applications in a client environment by reducing application start up time and memory footprint.  

Java HotSpot Server VM:

  • The java HotSpot server VM is designed for maximum program execution speed for applications running in a server environment.
  • The Java HotSpot Server VM is invoked by using the server command line option when an application , as in java server MyApp.
  • Some of the features java HotSpot technology , common to both VM implementations, are the following.

Adaptive compiler:

  • Applications are launched using a standard interpreter, but the code is then analyzed as it runes to detect performance bottlenecks, or "hot spots".
  • The Java HotSpot VMs compile those performance critical portions of the code for a boost in performance , while avoiding unnecessary compilation of seldom used code.
  • The Java HotSpot VMs also uses the adoptive compiler to decide on the fly , how best to optimize compiled code with techniques such as in lining.
  • The run time analysis performed by the compiler allows it to eliminate guesswork in determining which optimizations will yield the largest performance benefit.

Rapid memory allocation garbage collection:

  • Java HotSpot technology provides for rapid memory allocation for objects , and it has a fast, efficient, state-of-the-art  garbage collector. 

Thread Synchronization:

  • The Java programming language allows for use of multiple , concurrent paths of program execution (called threads).
  • Java HotSpot technology provides a thread- handling capability that is designed to scale readily for use in large , shared memory multiprocessor servers.

Jvm architecture in java with diagram





Class Loader Sub System:     

  • The class loader sub system will take a .class file as the input and performance the following operations. 
  • The class loader sub system is responsible for loading the .class file (Byte code) into the JVM.
  • Before loading the Byte code into the JVM it will verify where there the Byte code is valid      or   not. This verification will be done by Byte code verifier.
  • If the Byte code is valid then the memory for the Byte code will be allocated in different areas.
  • The different areas into which the Byte code is loaded are called as Run Time Data Areas. The various run time data areas are.


1.Method Area: 

  • Java Virtual Machine Method Area can be used for storing all the class code and method code.
  • All classes bytecode is loaded and stored in this run time area , and all static variables are created in this area.

2.Heap Memory:

  • JVM Heap Area can be used for storing all the objects that are created.
  • It is the main memory of JVM , all objects of classes :- non static variables memory are created in this run time area.
  • This runtime  area memory is finite memory.
  • This area can be configured at the time of setting up of runtime environment using non standard option like
  • java -xms <size> class-name.
  • This can be expandable by its own , depending on the object creation.
  • Method area and Heap area both are sharable memory areas.

3.Java Stack area:

  • JVM stack Area can be used for storing the information of the methods. That is under execution. The java stack can be considered as the combination of stack frames where every frame will contain the stat of a single method.
  • In this runtime area all Java methods are executed.
  • In this runtime JVM by default creates two threads. they are
  • 1.main method
  • 2.Garbage Collection Thread
  •  main thread responsible to execute java methods starts with main method.
  • Also responsible to create objects in heap area if its finds new keyword in any method logic.
  • Garbage collection thread is responsible to destroy all unused objects from heap area.

4.PC Register (program counter) area:

  • The PC Register i Java Virtual Machine will contain address of the next instruction that have to be executed.

5.Java Native Stack:   

  • Java native stack area is used for storing non-java coding available in the application. The non-java code is called as native code.

  

Execution Engine:

  • The Execution Engine of JVM is Responsible for executing the program and it contains two parts.
  1. Interpreter.
  2. JIT Compiler (just in time compiler).
  • The java code will be executed by both interpreter and JIT compiler simultaneously which will reduce the execution time and them by providing high performance. The code that is executed by JIT compiler is called as HOTSPOTS (company).
  



Java programming interview questions

  1. Java Program to 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

Inner classes in java

  • Class inside a class is known as nested class.
  • We will use nested classes to group classes and interfaces at one place for readability and maintainability.
  1. package com.instanceofjava;
  2. public class A{ 
  3.  class B{
  4. // inner class
  5. }
  6. }


  • Inner class is a part of nested class. Non-static nested classes are known as inner classes. 
  • Nested classes are two types
  • Non-static nested class(inner class)
    1. Member inner class
    2. Anonymous inner class
    3. Local inner class
  • Static nested class.

Member inner class:

  •  A class is defined within a class and outside of methods of that class known as member inner class.
  1. package instanceofjavaforus;
  2. public class A{ 
  3.  class B{
  4. public void show(){
  5. }
  6. }
  7. public static void main(String args[]){
  8. A a= new A();
  9. a.B b= a.new B();
  10. b.show();
  11. }
  12. }

 

Anonymous inner class:

  • Anonymous inner class is a inner class which does not have a name and whose instance is created at the time creating class itself.
  • Anonymous inner classes are somewhat different from normal classes in its creation.
  • There are two ways to create in two ways.
    1. Using class.
    2. Using interface.

Using class:

  1. package instanceofjavaforus;
  2. public class A{ 
  3. public void show(){
  4. }
  5. public static void main(String args[]){
  6. A a= new A(){
  7.  public void display(){
  8. System.out.println('anonymous class method');
  9. }
  10. };
  11. a.display();
  12. }
  13. }


  Using interface:

  1. package instanceofjavaforus;
  2. public interface A{ 
  3.  public void show();
  4. }

  1. package instanceofjavaforus;
  2. public class Demo{ 
  3. public static void main(String args[]){
  4. A a= new A(){
  5.  public void show(){
  6. System.out.println('anonymous class method');
  7. }
  8. };
  9. a.show();
  10. }
  11. }

 

Local inner class:

  • A class which is defined inside a method of another class known as local inner class
  1. package instanceofjavaforus;
  2. public class Demo{ 
  3. void create(){
  4. class A{
  5. void show(){
  6. System.out.println("local inner class method");
  7. }
  8. }
  9. A a= new A();
  10. a.show();
  11. }
  12. public static void main(String args[]){
  13. Demo obj= new Demo();
  14.  obj.create();
  15. }
  16. }

 

Static nested class:

  • A static nested class is a class which is defined inside a class as static.
  1. package instanceofjavaforus;
  2. public class Outer{ 
  3.   static class inner{
  4. public void show(){
  5. System.out.println("static inner class method");
  6. }
  7. }
  8. public static void main(String args[]){
  9. Outer.inner in= new Outer.innner();
  10. in.show();
  11. }
  12. }

Top 25 Core java interview questions for freshers

1. what is a transient variable?

  •  A transient variable is a variable that whose value is not going to be serialized

2. What is synchronization?

  • With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.
  •  Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

3. What’s new with the stop(), suspend() and resume() methods in JDK 1.2? 

  • The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

4. Is null a keyword?

  •  "null"  is not a keyword. .null is a literal.

5. What state does a thread enter when it terminates its processing?

  • When a thread terminates its processing, it enters the dead state.

6. What is the Collections API?

  • The Collections API is a set of classes and interfaces that support operations on collections of objects.

7. What is the List interface?

  • The List interface provides support for ordered collections of objects which allows duplicate elements also.

8. What is the Vector class?

  • The Vector class provides the capability to implement a growable array of objects

9.Can we instantiate Abstract class?

  • We can not create object for abstract class directly. but indirectly through sub class object we can achieve it.

10.What is the first keyword used in a java program?

  • Its "package" keyword.

11.When a class should be defined as final?

  • If we do not want allow subclasses.
  • If we do not want to extend the functionality.

12.Can we declare abstract method as static?

  • No, we are not allowed to declare abstract method as static.
  • It leads to compilation error: illegal combination of modifiers abstract and static.

13.Can we apply abstract keyword to interface?

  • Yes, it is optional.
  • abstract interface A{}

14.Can we write empty interface?

  • Yes it is possible it is marker interface.
  • interface A{}

15.Can we declare interface as final?

  • No, it leads to compile time error. Because it should allow sub class.

16.How to solve ClassCastException?

  • To solve  ClassCastException we should use instanceof operator.
  • obj instanceof class_name

17. Is “xyz” a primitive value? 

  • No, it is not primitive it is string literal.

18.When is an object subject to garbage collection? 

  • An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

19.What method must be implemented by all threads? 

  • The run() method, whether they are a subclass of Thread or implement the Runnable interface.


20.What happens if an exception is not caught?

  • An uncaught exception results in the uncaughtException() method of the thread’s ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

21.How are this() and super() used with constructors?

  • this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

22.Under what conditions is an object’s finalize() method invoked by the garbage collector?

  • The garbage collector invokes an object’s finalize() method when it detects that the object has become unreachable.

23.What restrictions are placed on method overloading? 

  • Methods should have same name  and defer in parameters.

24.When does the compiler supply a default constructor for a class? 

  • The compiler supplies a default constructor for a class if no other constructors are provided.

25.What modifiers can be used with a local inner class?

  • A local inner class may be final or abstract.

For More Questions Check below on your interest:

1. Concept and Interview Program

2. Concept and Interview Questions

3. 0-3 Years Core Java Interview Questions



1. Top 15 Garbage Collection Interview Questions

2. Top 10 Oops Concepts Interview Questions 

3. Top 15 Java Interview Questions on Constructors

4. Top 10 Inheritance Interview Questions

5. Interview Programs on Strings

6. 10 Interesting Core Java Interview Coding Questions and Answers

7. Top 20 Basic Java Interview Questions for Frehsers 

8. Top 10 interview Question on Static keyword. 

9.Top 20 Java interview Questions on Increment and Decrement operators

10.Top 10 Interview Questions on main() method

11. Top 12 Java Experienced interview Programming Questions on Strings

12.Pattern Programs in java Part-1

13.Pattern Programs in java Part-2

14.Pattern Programs in java Part-3 

15. Collection framework interview programming questions 

Select Menu