Java Variables and Types of Variables


Variable:

  • Variable is a named memory location used to store data temporarily.
  • During program execution we can modify that data

Limitation of Variable:

  •  It can only store single value at a time.
  • It means , always it returns latest modified value.

How can a variable be created?

  • A variable can be created by using data type.
  • As we have two types of data types  we can create two types of variables.
    1.Primitive Variable
    2.Referenced variable
  • The difference between primitive and referenced variable is "primitive variable stores data directly , where referenced variables stores reference/address of object, not direct values"

  1. package com.instanceofjava;
  2.  
  3. class Example
  4. {
  5.  
  6.  int x=10;
  7.  int y=20;
  8.  
  9. }


  1. package instanceofjava;
  2. class Test
  3. {
  4.  
  5. public int get(){
  6. return 10:
  7. }
  8.  
  9. public static void main(String [] args){
  10.  
  11. //primitive variables
  12. int s=50;
  13. int t=get(); 
  14.  
  15. //reference variables
  16. String str="a";
  17. String str1=new String("a");
  18. Example e= new Example();

  19. }
  20. }



What is an object?

  • Technically object means collection of all non static variables and methods memory locations.
  • Object is created using new keyword

Defining a variable:

  • Variable creation with value is called defining a variable
  • <Accessibility modifier><Modifier><Data type><Variable name>=<Value> ;

  1. package instanceofjava;
  2. public class Demo{
  3. public static void main(String[] args){
  4.   
  5. public static int x=10;
  6. public static Example e= new Example();

  7. }
  8. }

Declaring a variable:

  • Variable creation without value is called declaring a variable.
  • <Accessibility modifier><Modifier><Data type><Variable name>;


  1. package instanceofjava;
  2. public class Demo{
  3. public static void main(String[] args){
  4.   
  5. public static int a;
  6. public static Example e;

  7. }
  8. }


Initializing/Assigning a variable:

  • Storing a value in a variable at the time of its creation is called initializing a variable.
  • Storing a value in a variable after its creation is called assigning a value to a variable.
  • <Variable_Name>=<Value>;

  1. package instanceofjava;
  2. public class Demo{
  3. public static void main(String[] args){
  4.   
  5. //declaring a variable
  6.  int a;
  7.  int x;
  8.  
  9. //assigning a variable
  10.  a=20;
  11.  x=10;
  12.  
  13. // re initialization/ re assignment
  14.  a=30;
  15.  x=20;

  16. }
  17. }


Calling a variable:

  • Reading a value from a variable is called calling a variable.


  1. package instanceofjava;
  2. public class Demo{
  3. public static void main(String[] args){
  4.   
  5.  int x=10;
  6.   
  7.  //calling x variable for printing
  8. System.out.println(x);
  9.  
  10. // calling x variable for initializing y
  11.  int y=x;


  12. }
  13. }



Types of Variables:

  • Local
  • Static
  • Non static
  • Final
  • Transient
  • Volatile

1.Local Variables:

  • The variables created inside a method or block are called local variables.

Rules:

  • While working with local variables , we must follow below 3 rules.

Rule #1:

  •  Local variables can not be accessed from another method. Because its scope is restricted only within its method.
  • Also we can not guarantee that variable creation , because that method may or may not be called. It leads to compile time Exception : can not find symbol.
 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4.  
  5. public void show(){
  6.  System.out.println("a:"+a); Compile time error: can not find symbol a.
  7. }
  8.  
  9. public static void main(String [] args){
  10.  
  11.  int a=10;
  12.  System.out.println("a:"+a);
  13. }
  14. }


Rule #2:

  • Local variable should not be accessed without initialization.

 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4. public static void main(String [] args){
  5.  
  6.  int a=10;
  7.  int b;
  8.  System.out.println("a:"+a);
  9.  
  10.  System.out.println("b:"+b);//Error
  11.  // Above statement throws Compile time Error: variable b might not have been initialized
  12.  
  13.  b=20;
  14. System.out.println("b:"+b);
  15.  
  16. }
  17. }


Rule #3:

  • Local variable must be accessed only after its creation statement. because method execution is sequential execution from top to bottom. If we access before  its creation statement it leads compile time Error : Can not find symbol.


 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4.  
  5.  static void show(){
  6.  System.out.println("a:"+a);// Compile time Error
  7.  int a;
  8.  System.out.println("a:"+a); // Compile time Error
  9.   
  10.  a=10
  11.  
  12.  System.out.println("a:"+a);
  13.  
  14. }
  15. }

2. Static variables :

  • Static variables gets life when class is loaded.
  • It is destroyed either if class is unloaded from JVM or JVM is destroyed.
  • Its scope is throughout the class it means where class is available there static variable is available provided it is public.

 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4.  static int a=10;

  5. public static void show(){
  6.  System.out.println("a:"+a);
  7. }
  8.  
  9. public static void main(String [] args){
  10.  
  11.  System.out.println("a:"+a);
  12.  
  13. }
  14. }

3. Non Static variables:

  • Non static variable gets life when object is created. It is destroyed when object is destroyed.
  • Object is destroyed when it is unreferenced.
  • Its scope is the scope of the object, object is available only if its referenced variable is available

 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4.  
  5.  int a=10;

  6. public void show(){
  7.   test t= new test();
  8.  System.out.println("a:"+t.a);
  9. }
  10.  
  11. public static void main(String [] args){
  12.  
  13.   test t= new test();
  14.  System.out.println("a:"+t.a);
  15.  
  16. }
  17. }


4.Final variables:

  • The class level or local variable that has final keyword in its definition is called final variable.

Rule:

  •  Once it is initialized by developer its value can not be changed. If we try to change its value it leads to Compile tile error.


 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4.  static final int a=10;
  5. static final int b=20;

  6. public static void main(String [] args){
  7.  
  8.  a=20;//Error : variable might be already have been assigned
  9.  b=30; //Error : variable might be already have been assigned
  10.  
  11. }
  12. }


5. Transient variable:

  • The class level variable that has transient keyword in its definition is called transient variable.

Rule:

  • Local variable can not be declared as transient.
  • It leads to Compile time error: Illegal start expression


 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4.  static transient int a=10;
  5. static transient  int b=20;

  6. public static void main(String [] args){
  7.  
  8.  transient int x=10; // compile time error : illegal start expression
  9.  
  10. }
  11. }

  • We declare variable as transient to tell to JVM that we do not want to store variable value in a file in object serialization. Since local variable is not part of object , declaring it as transient is illegal.
  • Refer IOStreams for more details

6.Volatile Variable:

  • The class level variable that has volatile keyword in its definition. 

Rule:

  • Local variable can not be declared as transient.
  • It leads to Compile time error: Illegal start expression


 Example program:

  1. package com.instanceofjava;
  2. class test
  3. {
  4.  static volatile int a=10;
  5. volatile int b=20;

  6. public static void main(String [] args){
  7.  
  8.  volatile int x=10; // compile time error : illegal start expression
  9.  
  10. }
  11. }

  • We declare variable as volatile to tell to JVM that we do not want to modify variable value concurrently by multiple threads.
  • If we declare variable as volatile multiple threads are allowed to change its value in sequence one after another one.


You might like:

Top 15 Garbage Collection Interview Questions

Top 50 Java Questions everybody should know

Top 25 Programs asked in interviews

Top 25 Core Java Interview Questions

Top 20 Java Interview Questions on Constructors


1. Define Constructor?

  • Constructor is a special method given in OOP language for creating and initializing object.
  • In java , constructor role is only initializing object , and new keyword role is crating object.

2.What are the Rules in defining a constructor?

  •  Constructor name should be same as class name.
  • It should not contain return type.
  • It should not contain Non Access Modifiers: final ,static, abstract, synchronized
  • In it logic return statement with value is not allowed.
  • It can have all four accessibility modifiers: private , public, protected, default
  • It can have parameters
  • It can have throws clause: we can throw exception from constructor.
  • It can have logic, as part of logic it can have all java legal statement except return statement with value.
  • We can not place return in constructor.

 3. Can we define a method with same name of class?

  • Yes, it is allowed to define a method with same class name. No compile time error and no runtime error is raised, but it is not recommended as per coding standards.

4.If we place return type in constructor prototype will it leads to Error?

  • No, because compiler and JVM considers it as a method.

5. How compiler and JVM can differentiate constructor and method definitions of both have same class name?

  • By using return type , if there is a return type it is considered as a method else it is considered as constructor.

6. How compiler and JVM can differentiate constructor and method invocations of both have same class name?

  • By using new keyword, if new keyword is used in calling then constructor is executed else method is executed.

7.Why return type is not allowed for constructor?

  •  As there is a possibility to define a method with same class name , return type is not allowed to constructor to differentiate constructor block from method block.

8.Why constructor name is same as class name?

  •  Every class object is created using the same new keyword , so it must have information about the class to which it must create object .
  • For this reason constructor name should be same as class name.

9.Can we declare constructor as private?

  •  Yes we can declare constructor as private.
  • All four access modifiers are allowed to
  •  constructor.
  • We should declare constructor as private for not to allow user to create object from outside of our class.
  • Basically we will declare private constructor in Singleton design pattern.
  • Read more at

constructor interview questions in java

10.Is Constructor definition is mandatory in class?

  •  No, it is optional . If we do not define a constructor compiler will define a default constructor.

11. Why compiler given constructor is called as default constructor?

  • Because it obtain all its default properties from its class.
  • They are
    1.Its accessibility modifier is same as its class accessibility modifier
    2.Its name is same as class name.
    3.Its does not have parameters and logic.

12. what is default accessibility modifier of default constructor?

  •  It is assigned from its class.

13.When compiler provides default constructor?

  •  Only if there is no explicit constructor defined by developer.

14.When developer must provide constructor explicitly?

  • If we want do execute some logic at the time of object creation, that logic may be object initialization logic or some other useful logic.

15.If class has explicit constructor , will it has default constructor?

  • No. compiler places default constructor only if there is no explicit constructor.
16.Programming interview questions on constructors





19.Differences between default constructor and no argument constructor

20.What is the order of execution of constructor with Non static blocks 


  1. Print prime numbers? 
  2. Java Program Find Second highest number in an integer array 
  3. Java Interview Program to find smallest and second smallest number in an array 
  4. Java Coding Interview programming Questions : Java Test on HashMap  
  5. Constructor chaining in java with example programs 
  6. Swap two numbers without using third variable in java 
  7. Find sum of digits in java 
  8. How to create immutable class in java 
  9. AtomicInteger in java 
  10. Check Even or Odd without using modulus and division  
  11. String Reverse Without using String API 
  12. Find Biggest substring in between specified character
  13. Check string is palindrome or not?
  14. Reverse a number in java? 
For more java programs: Top 50 java interview programs

How Java Technology Change My Life

  • We can not promise you fame, fortune or even a job if you learn the Java Programming
  • Still , It is likely to make your programs better and requires less effort than other languages.
  • We believe that Java technology will help you do the following.

1. Get Started Quickly:

  • Although the java programming is powerful object oriented language, its easy to learn.

2.Write less code

  •  Comparisons of program metrics(class count , method count and so on.) suggest that a program written in java programming language can be four times smaller than the same program written in C++.

3.Write Better code:

  •  Java Programming language encourages good coding practices and automatic garbage collection helps you avoid memory leak.

4.Develop programs more quickly:

  • The Java programming language is simpler than C++  and as such , your development time could be up to twice as fast when writing in it.
  • Your programs also require fewer lines of code.

5.Avoid platform dependencies:

  • You can keep your program portable by avoiding the use of libraries written in other languages.

6.Write once run anywhere:

  • Because applications written in the java programming language are compiled into machine independent bytecode, they run consistently on any java platform.

 7.Distribute software more easily:

  • With Java web start software , users will be able to launch your application with a single click of the mouse .
  • An automatic version check at start up ensures that users are always up to date with the latest version of your software .
  • If an update is available , the java web start software will automatically update their installation.

 What can Java Technology Do?

  • The general purpose , high level java programming language is powerful software platform.
  • Every full implementation of the java platform gives you the following features.

Development Tools:

  • The development tools provide everything you will need for 
  • compiling , 
  • running ,
  • mongering,
  • debugging and documenting your application.  

Application Programming Interface(API):

  • The API provides the core functionality of the java programming language . It offers a wide array of useful classes ready for use in your own applications.

Deployment Technologies:

  • The JDK software provides standard mechanism such as the java web start software  and java plug in software for developing your applications to end users.

User Interface Tool-kits:

  •  The swing and Java 2D tool kits make it possible to create sophisticated Graphical User Interfaces(GUIs).

Integration Libraries:

  • Integration libraries such as Java IDL API, JDBC API, Java Naming and Directory Interface(JNDI)  API, Java RMI and Java remote method invocation over Internet inter -ORB protocol Technology(Java RMI-IIOP technology)  enable database access and manipulation of remote objects.

Static import In java

  • If we want to use any predefined class or user defined class or interface or enum which is present in a package we need to import those  entire packages or those classes so that we can use those classes present inside the package.

  • import packagename.ClassTest;
  • import packagename.*;
  • For example if we want to read some data from keyboard we can use scanner class present in util package.
  • import java.util.Scanner;
  • We can import everything inside a package by using .*
  • import java.util.*;
  • Without importing want to use that class then code seems to like this




  1. package com.instanceofjava;
  2. class A{
  3.   
  4. public static void main(String [] args){
  5.  
  6.    int number;
  7.   java.util.Scanner in = new java.util.Scanner(System.in);
  8.  
  9.     System.out.println("Enter a number to check even or odd");
  10.     number=in.nextInt();
  11.   
  12.  
  13. }
  14. }

  • if we use import no need to mention class name in declaration 


  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class A{
  6.   
  7. public static void main(String [] args){
  8.  
  9.    int number;
  10.   Scanner in = new Scanner(System.in);
  11.  
  12.     System.out.println("Enter a number to check even or odd");
  13.     number=in.nextInt();
  14.   
  15.  
  16. }
  17. }


Static import:

  • Normal imports will import the all the classes so that we can use them. similarly static imports will import all static data so that can use without class name.
  • Static imports introduced in Java 5.
  • Lets see one program without static import.

 Without Static Import:


  1. package com.instanceofjava;
  2.  
  3. class StaticImport{
  4.   
  5. public static void main(String [] args){
  6.  
  7.     System.out.println(Math.PI); //3.141592653589793
  8.     System.out.println(Integer.MAX_VALUE);//2147483647
  9.     System.out.println(Integer.parseInt("123"));//123
  10.  
  11. }
  12. }

Using Static import:

static import in java with example:
  1. package com.instanceofjava;
  2.  
  3.  import static java.lang.Integer.*;
  4.  import static java.lang.Math.*;
  5.  
  6. class StaticImport{
  7.   
  8. public static void main(String [] args){
  9.  
  10.     System.out.println(PI); //3.141592653589793
  11.     System.out.println(MAX_VALUE);//2147483647
  12.     System.out.println(parseInt("123"));//123
  13.  
  14. }
  15. }

static imports in java 1.5 examples:

Importing Math class:

 

  1. package com.instanceofjava;
  2.  
  3.  import static java.lang.Math.*;
  4.  
  5. class StaticImport{
  6.   
  7. public static void main(String [] args){
  8.  
  9.     System.out.println(PI); //3.141592653589793

  10.     double square;
  11.  
  12.     double d1 = 3.0;
  13.     double   d2 = 4.0;
  14.  
  15.     square = sqrt(pow(d1, 2) + pow(d2, 2));
  16.     System.out.println(square);
  17.  
  18. }
  19. }

Importing System class:

 

  1. package com.instanceofjava;
  2.  
  3.  import static java.lang.System.out;
  4.  
  5. class StaticImport{
  6.   
  7. public static void main(String [] args){
  8.  
  9.      out.println("Good morning, " + "java2s");
  10.      out.println("Have a day!");
  11.  
  12. }
  13. }

Importing User defined classes:



  1. package com.instanceofjava;

  2.  
  3. class Colors{
  4.  
  5.      public static int white = 1;
  6.      public static int black = 2;
  7.      public static int red = 3;
  8.      public static int blue = 4;
  9.      public static int orange = 5;
  10.      public static int grey = 6;
  11.      public static int green =7;
  12.  
  13. }


  1. package com.instanceofjava;

  2.  import static com.instanceofjava.Colors.*; 

  3. class StaticImportDemo{
  4.  
  5. public static void main(String [] args){
  6.  
  7.     System.out.println(white );//1
  8.     System.out.println(blue);//4
  9.  
  10. }
  11.  
  12. }


Arrays and Collections:





  1. package com.instanceofjava;

  2.  import static com.instanceofjava.Colors.*; 

  3. class StaticImportDemo{
  4.  
  5. public static void main(String [] args){
  6.  
  7.    int[] array = new int[] {5, 4, 6, 3, 2, 1};
  8.  
  9.         sort(array);
  10.  
  11.      for (int i = 0; i < array.length; i++) {
  12.             System.out.print(array[i]+" ");
  13.       }  
  14.  
  15.   ArrayList al= new ArrayList();
  16.        al.add(1);
  17.         al.add(12);
  18.         al.add(3);
  19.        al.add(2);
  20.  
  21.        sort(al); 

  22.          Iterator itr= al.iterator();
  23.          while(itr.hasNext()){
  24.              System.out.printl(itr.next()+" ");
  25.          }
  26.  
  27. }
  28.  
  29. }

OutPut:

  1. 1 2 3 4 5 6
  2. 1 2 3 12



Advantages and Disadvantages of Static imports in java:

  • One of the advantage of using static imports is reducing keystrokes and re usability.
  • System.out.println() ; we can write as out.println() .  But using eclipse short cut syso (ctrl+sapce)  gives System.out.println() faster than static imports usage. 
  • And there may be a chance of  complexity in readability.
  • If we use class name before method like Math.sqrt() then can understand easily that method belongs to particular class . with static imports reduces readability.
  • One more disadvantage is naming conflicts.
  • If we use Integer.Max_value we cannot use Float.Max_value


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

Top 20 Oops Concepts Interview Questions

1.What are the oops concepts in java?

basic oops concepts in java

 




2. What is encapsulation?

3.What is class ? 

 

  • A class is a specification or blue print or template of an object.
  • Class is a logical construct , an object has physical reality.
  • Class is a structure.
  • Class is a user defined data type in java
  • Class will acts as base for encapsulation.
  • Class contains variables and methods.


  1. package com.instanceofjava;
  2.  
  3. class Demo{
  4.  
  5. int a,b;
  6. void show(){
  7. }
  8.  
  9. }

4. What is an object?



  • Object is instance of class.
  • Object is dynamic memory allocation of class.
  • Object is an encapsulated form of all non static variables and non static methods of a particular class.
  • The process of creating objects out of class is known as instantiation.
  1. package com.instanceofjava;
  2.  
  3. class Test{
  4.  
  5. int a,b;
  6. void print(){
  7. System.out.println("a="+a);
  8. System.out.println("b="+b);
  9. }
  10.  
  11. public static void main(String [] args){
  12.    
  13.    Test obj= new Test();
  14.   obj.a=10;
  15.   obj.b=20;
  16.   obj.print();
  17. }
  18. }


Output:

  1. a=10
  2. b=20

5. What are the Object Characteristics?

  •  The three key characteristics of Object are
  • State
  • Behavior
  • Identity

State:

  • Instance variables value is called object state.
  • An object state will be changed if instance variables value is changed.

Behavior:

  • Behavior of an object is defined by instance methods.
  • Behavior of an object is depends on the messages passed to it.
  • So an object behavior depends on the instance methods.

Identity:

  • Identity is the hashcode of an object, it is a 32 bit integer number created randomly and assigned to an object by default by JVM.
  • Developer can also generate hashcode of an object based on the state of that object by overriding hashcode() method of java.lang.Object class.
  • Then if state is changed , automatically hashcode will be changed.

6.What is Inheritance?

  • As the name suggests , inheritance means to take something that already made.
  • One of the most important feature of Object oriented Programming. It is the concept that is used for re usability purpose.
  • Getting the properties from one class object to another class object.

7. How inheritance implemented in java?

  • Inheritance can be implemented in JAVA using below two keywords.
    1.extends
    2.implements
  • extends is used for developing inheritance between two classes or two interfaces, and implements keyword is used to develop inheritance between interface and class.


  1. package com.instanceofjava;
  2. class A{
  3.  
  4. }


  1. package com.instanceofjava;
  2. class B extends A{
  3.  
  4. }

8. What are the types of inheritances?

  • There are two types of inheritance
    1.Multilevel Inheritance
    2.Multiple Inheritance

Multilevel Inheritance:

  • Getting the properties from one class object to another class object level wise with some priority is known as multilevel inheritance.



  1. package com.instanceofjava;
  2.  
  3. class A{
  4.  
  5. }
  6.  
  7. class B extends A{
  8.   
  9. }
  10.   
  11. class C extends B{
  12.  
  13. }


Multiple Inheritance:


9. What is polymorphism?

  • Defining multiple methods with same name,
 Static polymorphism:
  • Defining multiple methods with same name with different parameters.
  • Is also known as method overloading.


  1. package com.instanceofjava;
  2. class Demo{
  3.   
  4. void add(){
  5. }
  6.   
  7. void add(int a, int b){
  8. }
  9.  
  10. void add(float a, float b){
  11.   
  12. }
  13. public static void main(String [] args){
  14.  Demo obj= new Demo();
  15.  
  16. obj.add();
  17. obj.add(1,2);
  18. obj.add(1.2f,1.4f);

  19. }

  20. }


 Dynamic Polymorphism:

  • Defining multiple methods with same signature in super class and sub class.
  • The sub most object method will be executed always.


 10. Similarities and differences between this and super keywords?

 this:
  • This is a keyword used to store current object reference.
  • It must be used explicitly if non -static variable and local variables name is same.
  • System.out.print(this); works fine
super:
  • Super is a keyword used to store super class non -static members reference in sub class object.
  • used to separate super class and sub class members if both have same name.
  • System.out.println(super); compilation Error

11.Top 10 interview Questions on Method overriding

12.Top 15 interview programming questions on abstract classes

13.Top 10 interview Question on interfaces

14.Java Quiz

15. Basic Method overloading interview questions in java 

16. Super keyword interview Questions in java

17.Top 10 java Interview questions on final keyword 

18. Top 10 basic interview questions and answers on this keyword

19. Top 20 java interview questions on constructors 

20. 19 Oops concepts explanation with example programs
  1. OOPS Introduction
  2. Encapsulation 
  3. Class and Object
  4. Four different ways to create objects in java 
  5. 5 different places to define object in java
  6. Polymorphism
  7. Method Overriding
  8. Inheritance
  9. Constructor
  10. Constructor Overloading 
  11. Constructor Chaining 
  12. Static constructor
  13. Static Keyword
  14. This Keyword
  15. Super Keyword
  16. Final Keyword
  17. Abstract class and interfaces 
  18. Abstract Class and abstract methods
  19. Interview questions on interfaces in java

  1. Print prime numbers? 
  2. Java Program Find Second highest number in an integer array 
  3. Java Interview Program to find smallest and second smallest number in an array 
  4. Java Coding Interview programming Questions : Java Test on HashMap 
  5. Constructor chaining in java with example programs 
  6. Swap two numbers without using third variable in java 
  7. Find sum of digits in java 
  8. How to create immutable class in java 
  9. AtomicInteger in java 
  10. Check Even or Odd without using modulus and division  
  11. String Reverse Without using String API 
  12. Find Biggest substring in between specified character
  13. Check string is palindrome or not?
  14. Reverse a number in java? 
For more interview programs : Top 60 Java Programs asked in interviews
Read Also:

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 

Top 15 Garbage Collection Interview Questions

1.What is Garbage Collection in Java?

  • Garbage Collection is an automatic memory management feature.
  • The process of destroying unreferenced objects is called Garbage Collection.
  • Once object is unreferenced it is considered as unused object, hence JVM automatically destroys that object.
  • In java developers responsibility is only to creating objects and unreferencing those objects after usage.

2.How JVM can destroy unreferenced object?

  • JVM internally uses a daemon thread called "garbage collector" to destroy all unreferenced objects.
  • A daemon thread is a service thread. Garbage Collector thread is called daemon thread because it provides services to JVM to destroy unreferenced objects.
  • This thread is low priority thread. Since it is a low priority thread we can not guarantee this execution.

 3.So can you guarantee objects destruction?

  •  No, we can not guarantee objects destruction even though it is unreferenced, because we can not guarantee garbage collector execution.
  • So, we can confirm whether object is eligible for garbage collection or not.

4.Can we force garbage collector?

  • No, we can not force garbage collector to destroy objects , but we can request it.

5.How can we request JVM to start garbage collection process?

  • We have a method called gc() in system class as static method and also in Runtime class as non static method to request JVM to start garbage collector execution.
  • System.gc();
  • Runtime.getRuntime().gc();

6.What is the algorithm JVM internally uses for destroying objects?

  • "mark and swap" is the algorithm JVM internally uses.

7.Which part of the memory is involved in Garbage Collection?

  • Heap.

8.What is responsibility of Garbage Collector?

  • Garbage Collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects.
  • It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run.

9. When does an object become eligible for garbage collection?

  • An object becomes eligible for garbage collection when no live thread can access it.

10. What are the different ways to make an object eligible for garbage collection when it is no longer needed?

  • Set all available object references to "null" once the purpose of creating object is served.


  1. package com.instanceofjava;
  2.   
  3. class GarbageCollectionTest1{
  4.   
  5. public static void main(String [] args){
  6.  
  7. String str="garbage collection interview questions";
  8. // String object referenced by variable str and is not eligible for GC yet.
  9.  
  10. str=null;
  11. //String object referenced by variable str is eligible for GC
  12. }
  13. }

  • Make the reference variable to refer to another object. Decouple the reference variable from the object and set it refer to another object, so the object which was referring to before reassigning is eligible for Garbage Collection

  1. package com.instanceofjava;
  2.   
  3. class GarbageCollectionTest2{
  4.   
  5. public static void main(String [] args){
  6.  
  7. String str1="garbage collection interview questions";
  8. String str2="Top 15 garbage collection interview questions";
  9. // String object referenced by variable str1 and str2 and is not eligible for GC yet.
  10.  
  11. str1=str2;
  12. //String object referenced by variable str1 is eligible for GC
  13.  
  14. }
  15. }


11.What is purpose of overriding finalize() method?

  • The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

12.How many times does the garbage collector calls the finalize() method for an object? 

  • Only once.

13.What happens if an uncaught exception is thrown from during the execution of finalize() method of  an object?

  •  The exception will be ignored and the garbage collection (finalization) of that object terminates

14.What are the different ways to call garbage collector?

  • System.gc();
  • Runtime.getRuntime().gc();

15. How to enable /disable call of finalize() method of exit of application?

  • Runtime.getRuntime().runFinalizersOnExit(boolean value). passing the boolean value  true and false will enable or disable the finalize() call.



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

    Jdbc Connction Steps with Examples


    Example to connect to oracle database:

    Connecting to java application to oracle database.you have to follow 5 steps :
    1.load the driver class,
    2.create the connection object,
    3.create the statement object
    4.execute query Connect
    5.Connection close

    oracle database connectivity steps:

    Driver class:The oracle database driver class is oracle.jdbc.driver.OracleDriver.

    Connection URl:The oracle database connection URL is jdbc:oracle:thin:@localhost:1521:xe.
    here jdbc is API,oracle is the database, thin is the driver,local host is server on which oracle is running,or we can use IP address,1521 is port number and
    and XE is the Oracle service name.

    User name:The oracle database default userName is system.

    Password:Password is given by the user at the time of installing the oracle database. In this example, we are going to use system123 as the password.

    import java.sql.*;
    class ConnecttoOracle{
    public static void main(String args[]){
    try{
    // load the driver class
    Class.forName("oracle.jdbc.driver.OracleDriver");

    //create  the connection object
    Connection con=DriverManager.getConnection(
    "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

    // create the statement object
    Statement stmt=con.createStatement();

    // execute query
    ResultSet rs=stmt.executeQuery("select * from emp");
    while(rs.next())
    System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));

    // close the connection object
    con.close();

    }
    catch(Exception e){
    System.out.println(e);}

    }
    }


    Example to connect to Mysql databaase:



    Connecting to java application to mysql database.you have to follow 5 steps :
    1.load the driver class,
    2.create the connection object,
    3.create the statement object
    4.execute queryConnect
    5.Connection close

    Mysql database connectivity steps:

    Driver class:The mysql database driver class is com.mysql.jdbc.Driver.

    Connection URl:The mysql database connection URL is jdbc:mysql://localhost:3306/test.
    here jdbc is API,mysql is database,local host is server on which mysql is running,or we can use IP address,3306 is port number and test is database name.
    we can use any database name here.

    Username:The mysql database default userName is root.

    Password:Password is given by the user at the time of installing the mysql database. In this example, we are going to use root123 as the password.

    import java.sql.*;
    class ConnecttoMysql{
    public static void main(String args[]){
    try{
    class.forName("com.mysql.jdbc.Driver");

    Connection con=DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/database name","root","root123");

    //here root is username and root123 is password

    Statement stmt=con.createStatement();

    ResultSet rs=stmt.executeQuery("select * from emp");

    while(rs.next())
    System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));

    con.close();

    }
    catch(Exception e){
    System.out.println(e);}

    }
    }
     
    Select Menu