Sunday, December 15, 2013

Java and Junit Interview Questions and Answers

Most Frequently Asked JUnit Interview Questions

How To Wirte a Simple JUnit Test Class?
import org.junit.*;

public class HelloTest {
@Test
 public void testHello() {
String message = "Hello World!";
Assert.assertEquals(12, message.length());
}
}

What is JUnit?
It is a software testing framework to for unit testing.
It is written in Java and designed to test Java applications.
It is an Open Source Software maintained by the JUnit.org community.

Answer from the JUnit FAQ:

JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. JUnit features include:

Assertions for testing expected results
Test fixtures for sharing common test data
Test runners for running tests

JUnit was originally written by Erich Gamma and Kent Beck.

Why Do You Use JUnit to Test Your Code?
I believe that writing more tests will make me more productive, not less productive.
I believe that tests should be done as soon as possible at the code unit level.
I believe that using JUnit makes unit testing easier and faster.

Who Should Use JUnit, Developers or Testers?
JUnit is mostly used by developers. JUnit is designed for unit testing, which is really a coding process, not a testing process.

But many testers or QA engineers, are also required to use JUnit for unit testing. For example, I found this job title on the Internet: Lead QA Engineer - Java / J2EE / whitebox / SAP / Junit

When Should Unit Tests Should Be Written In Development Cycle?
If you are a TDD (Test-Driven Development) believer, you should write unit test before writing the code. Test-first programming is practiced by only writing new code when an automated test is failing.

Good tests tell you how to best design the system for its intended use. They effectively communicate in an executable format how to use the software. They also prevent tendencies to over-build the system based on speculation. When all the tests pass, you know you're done!

Whenever a customer test fails or a bug is reported, first write the necessary unit test(s) to expose the bug(s), then fix them. This makes it almost impossible for that particular bug to resurface later.

Test-driven development is a lot more fun than writing tests after the code seems to be working. Give it a try!

How Do You Test a Method That Does not Return Anything?

You need to follow the logic below to answer this question:

* If a method is not returning anything through the "return" statement (void method), it may return data through its arguments. In this case, you can test the data returned in any argument.
* Else if a method is not returning any data through its arguments, it may change values of its instance variables. In this case, you can test changes of any instance variables.
* Else if a method is not changing any instance variable, it may change values of its class variables. In this case, you can test changes of any class variables.
* Else if a method is not changing any class variable, it may change external resources. In this case, you can test changes of any external resources.
* Else if a method is not changing any external resources, it may just doing nothing but holding the thread in a waiting status. In this case, you can test this waiting condition.
* Else if a method is not holding the thread in waiting status, then this method is really doing nothing. In this case, there is no need to test this method. :-)

When Objects Are Garbage Collected After a Test Is Executed?
My guess would be that all objects used in a test will be ready for Java garbage collector to release them immediately after the test has been executed.

By design, the tree of Test instances is built in one pass, then the tests are executed in a second pass. The test runner holds strong references to all Test instances for the duration of the test execution. This means that for a very long test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run.

Therefore, if you allocate external or limited resources in a test, you are responsible for freeing those resources. Explicitly setting an object to null in the tearDown() method, for example, allows it to be garbage collected before the end of the entire test run.

If this is true, the JUnit runner should be improved to stop building all test instances before executing any tests. Instead, the JUnit runner should just take one test at a time, build an instance of this test, execute the test, and release the test when the execution is done.

Do You Have To Write a Test for Everything?
No, just test everything that could reasonably break.

Be practical and maximize your testing investment. Remember that investments in testing are equal investments in design. If defects aren't being reported and your design responds well to change, then you're probably testing enough. If you're spending a lot of time fixing defects and your design is difficult to grow, you should write more tests.

If something is difficult to test, it's usually an opportunity for a design improvement. Look to improve the design so that it's easier to test, and by doing so a better design will usually emerge.


Dear readers, these JUnit Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of JUnit. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:
Q: What is testing?
A: Testing is the process of checking the functionality of the application whether it is working as per requirements.
Q: What is unit testing?
A: Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.
Q: What is Manual testing?
A: Executing the test cases manually without any tool support is known as manual testing.
Q: What is Automated testing?
A: Taking tool support and executing the test cases by using automation tool is known as automation testing.
Q: Out of Manual and Automated testing which one is better and why?
A: Manual Testing is:
1.      Time consuming and tedious.
2.      Huge investment in human resources.
3.      Less reliable.
4.      Non-programmable.
Automated testing is
1.      Fast
2.      Less investment in human resources
3.      More reliable
4.      Programmable
Q: What is JUnit?
A: JUnit is a unit testing framework for the Java Programming Language. It is written in Java and is an Open Source Software maintained by the JUnit.org community.
Q: What are important features of JUnit?
A: Import features of JUnit are:
1.      It is an open source framework.
2.      Provides Annotation to identify the test methods.
3.      Provides Assertions for testing expected results.
4.      Provides Test runners for running tests.
5.      JUnit tests can be run automatically and they check their own results and provide immediate feedback.
6.      JUnit tests can be organized into test suites containing test cases and even other test suites.
7.      JUnit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
Q: What is a Unit Test Case?
A: A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected. A formal written unit test case is characterized by a known input and by an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post condition.
Q: When are Unit Tests written in Development Cycle?
A: Tests are written before the code during development in order to help coders write the best code.
Q: Why not just use System.out.println() for testing?
A: Debugging the code using system.out.println() will lead to manual scanning of the whole output every time the program is run to ensure the code is doing the expected operations. Moreover, in the long run, it takes lesser time to code JUnit methods and test them on class files.
Q: How to install JUnit?
A: Follow the steps below:
1.      Download the latest version of JUnit, referred to below as junit.zip.
2.      Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
3.      Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
4.      Test the installation by running the sample tests distributed with JUnit (sample tests are located in the installation directory directly, not the junit.jar file). Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an "OK" message. If the tests don't pass, verify that junit.jar is in the CLASSPATH.
Q: Why does JUnit only report the first failure in a single test?
A: Reporting multiple failures in a single test is generally a sign that the test does too much and it is too big a unit test. JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test.
Q: In Java, assert is a keyword. Won't this conflict with JUnit's assert() method?
A: JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works exactly the same way. JUnit 4 is compatible with the assert keyword. If you run with the -ea JVM switch, assertions that fail will be reported by JUnit.
Q: How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?
A: Refactoring J2EE components to delegate functionality to other objects that don't have to be run in a J2EE container will improve the design and testability of the software. Cactus is an open source JUnit extension that can be used for unit testing server-side java code.
Q: What are JUnit classes? List some of them.
A: JUnit classes are important classes which are used in writing and testing JUnits. Some of the important classes are:
1.      Assert - A set of assert methods.
2.      TestCase - It defines the fixture to run multiple tests.
3.      TestResult - It collects the results of executing a test case.
4.      TestSuite - It is a Composite of Tests.
Q: What are annotations and how are they useful in JUnit?
A: Annotations are like meta-tags that you can add to you code and apply them to methods or in class.
The annotation in JUnit gives us information about test methods, which methods are going to run before & after test methods, which methods run before & after all the methods, which methods or class will be ignore during execution.
Q: How will you run JUnit from command window?
A: Follow the steps below:
1.      Set the CLASSPATH
2.      Invoke the runner:
3.  java org.junit.runner.JUnitCore.
 
Q: What is JUnitCore class?
A: JUnitCore is an inbuilt class in JUnit package. It is based on Facade design pattern. This class is used to run only specified test classes.
Q: What is Test suite?
A: Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
Q: What is @Ignore annotation and how is this useful?
A: Sometimes it happens that our code is not ready and test case written to test that method/code will fail if run. The @Ignore annotation helps in this regards. Following are some of the usefulness of @Ignore annotation:
1.      You can easily identify all @Ignore annotations in the source code, while unannotated or commented out tests are not so simple to find.
2.      There are cases when you can't fix a code that is failing, but you still want to method to be around, precisely so that it does not get forgotten. In such cases @Ignore makes sense.
Q: What are Parameterized tests?
A: Parameterized tests allow developer to run the same test over and over again using different values.
Q: How do you use test fixtures?
A: Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. It includes:
1.      setUp() method which runs before every test invocation.
2.      tearDown() method which runs after every test method.
Q: How to compile a JUnit Test Class?
A: Compiling a JUnit test class is like compiling any other Java classes. The only thing you need watch out is that the JUnit JAR file must be included in the classpath.
Q: What happens if a JUnit Test Method is Declared as "private"?
A: If a JUnit test method is declared as "private", it compiles successfully. But the execution will fail. This is because JUnit requires that all test methods must be declared as "public".
Q: How do you test a "protected" method?
A: When a method is declared as "protected", it can only be accessed within the same package where the class is defined. Hence to test a "protected" method of a target class, define your test class in the same package as the target class.
Q: How do you test a "private" method?
A: When a method is declared as "private", it can only be accessed within the same class. So there is no way to test a "private" method of a target class from any test class. Hence you need to perform unit testing manually. Or you have to change your method from "private" to "protected".
Q: What happens if a JUnit test method is declared to return "String"?
A: If a JUnit test method is declared to return "String", the compilation will pass ok. But the execution will fail. This is because JUnit requires that all test methods must be declared to return "void".
Q: How can you use JUnit to test that the code throws desired exception?
A: JUnit provides a option of tracing the Exception handling of code. You can test if a code throws desired exception or not. The expected parameter is used along with @Test annotation as follows: @Test(expected)
Q: What are Parameterized tests in JUnit?
A: Parameterized tests allow developer to run the same test over and over again using different values.
Q: How to create Parameterized tests?
A: There are five steps, which you need to follow to create Parameterized tests:
1.      Annotate test class with @RunWith(Parameterized.class).
2.      Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.
3.      Create a public constructor that takes in what is equivalent to one "row" of test data.
4.      Create an instance variable for each "column" of test data.
5.      Create your tests case(s) using the instance variables as the source of the test data.
The test case will be invoked once per each row of data.
Q: Can you use a main() Method for Unit Testing?
A: Yes you can test using main() method. One obvious advantage seems to be that you can whitebox test the class. That is, you can test the internals of it (private methods for example). You can't do that with unit-tests. But primarily the test framework tests the interface and the behavior from the user's perspective.
Q: Do you need to write a test class for every class that needs to be tested?
A: No. We need not write an independent test class for every class that needs to be tested. If there is a small group of tests sharing a common test fixture, you may move those tests to a new test class.
Q: When are tests garbage collected?
A: The test runner holds strong references to all Test instances for the duration of the test execution. This means that for a very long test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run. Explicitly setting an object to null in the tearDown() method, for example, allows it to be garbage collected before the end of the entire test run.

What is Next ?

Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)

Q: How can we test a method that do not return anything?
  • A method may change value of instance variables, if it does not return anything. In this case we can check value of instance variables.
  • A method may not return any thing but it may modify the objects that are referenced by the object references which are passed in arguments. In this case we can test the state of these referenced objects.
  • If method does not change any of above, It may change value of static members. In this case we may check change in value of static variables.
  • Otherwise if a method is not changing any variable, it may be changing external resources. In this case, you can test changes of any external resources. These external resources may be a file.
  • Otherwise if a method is not changing any external resources, it may just doing nothing but holding the thread in a waiting status. In this case, you can test this waiting condition.
Most of the times a method may be doing one or more of above things which can be tested. more

Q: Can we declare JUnit test methods private?
Junit test methods cannot be declared as private. If we do so, the test case will compile successfully however execution of the test will fail. This is because JUnit requires that all the test methods must be declared as “public”.

Q: What is a test suite?
A TestSuite is group of tests. It runs a collection of test cases. This is a convenient way to group related test cases. ex.

void testSu() {
TestSuite testSuite=new TestSuite("Some test suite");
testSuite.add(test1.class);
testSuite.add(test2.class);
}

Q: When are test garbage collected ?
The Test instances tree is built in one pass and then the tests are executed in a second pass. The test runner holds references to all Test instances for the duration of the test execution. This means that for a long test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run.
Therefore, if you allocate external or limited resources in a test, tester is responsible for freeing those resources. Explicitly setting an object to null in the tearDown() method, allows it to be garbage collected before the end of the entire test run and is also recommended.

Q: Can we pass command-line arguments to a test execution?
Yes, we can do so by using
-D JVM command-line options
like: -DnameOfParameter=parameterValue

Q: What Happens If we Run JUnit Tests with Java Assertion Enabled?
As of JUnit 3.8, The JUnit runner works well with Java assertions. If Java assertion is enabled and a Java “assert” statement fails, the JUnit runner will flag this in same way as the calling test fails.

JUnit (Java Unit Testing) interview questions and answers
by Chaitanya Singh
Hello Guys, The below Junit interview questions and answers are for both freshers as well as for experienced folks. The reason behind this is that generally interviewers start with the basic questions (fresher level) and go for questions related to advanced topics ( experienced level) later. The whole FAQs are divided in two sections. This is the first part.
Must read Q&A second part here: JUnit interview questions
Question: What is unit testing?
Answer: A complete application can be build up by  integrating small-2 functional parts, such parts are called as units.  It is always better to test such individual units before testing the entire application. The process of testing the functionality and working of these individual unit is known as unit testing. Unit testing can be done manually and the process can also be automated.
Question: Explain Manual testing vs Automated testing?
Answer: Manual testing: Test cases are executed by humans, it’s time consuming and costly. Automated Testing: No human involvement, test  cases are executed by automated tools and programs, It’s fast and less costly compared to manual testing.
Question: What is a Unit Test Case?
Answer: Unit test case is nothing but a combination of input data and expected output, which is defined to test the proper functionality of a individual test unit. It’s is just to test the behavior of the unit for a particular input data.
Question: Why does JUnit only report the first failure in a single test?
Answer: There is no particular answer for this question, the main reason it does it like this to make the testing process simple and easy. Even though the failures are more than one it only reports the first failure, resolving which may implicitly resolve other unreported failures too.
Question: What is @Test and where it’s used?
@Test annotation is used to mark a method as test method, result of which is then compared with expected output to check whether the test is successful or not.
Question: What is @Before and @BeforeClass and it’s usage?
@Before annotation:
syntax:
@Before
public void myMethod()
This method should execute before each test. Such methods are generally used for initialization before performing a actual test in test environment.
@BeforeClass annotation:
syntax:
@BeforeClass
public static void myMethod()
This method should execute before all the tests. It executes only once. Method should be declared static. Mostly used for database connectivity tasks before execution of any of the test.
Question: What is @After and @AfterClass and it’s usage?
@After annotation:
syntax:
@After
public void myMethod()
This method should execute after each test and used for cleaning up the test and temporary data to avoid memory issues.
@AfterClass annotation:
syntax:
@AfterClass
public static void myMethod()
This method should execute at the end, once all the tests are finished. Method should be declared static and executes only a single time. Mostly used for closing the database connection.
Question: What is @Ignore and when it’s used?
@Ignore is used to ignore a test method. It’s really useful when we have all the tests in advance but the code is yet to be tested for the particular test, in such scenarios such test methods should be marked with @Ignore annotation.
Question: How will you run JUnit from command window?
Answer:
1) First set the ClassPath as follows:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar
2) Invoke JunitCore
java org.junit.runner.JUnitCore
Question: What is JUnitCore class?
Answer: This class is mainly responsible for executing tests. The org.junit.runner.JUnitCore class has a runClasses() method, which allows us to run one or more test classes. As a output we get a Result (org.junit.runner.Result) object, which we use to filter out the test information.
Question: What is Parameterized test in JUnit and what all annotations used for this?
Answer: Parameterized tests are possible in JUnit and they provides us the liberty of passing parameters into the test classes.
@RunWith(Parameterized.class) – For making a class parametrized.
@Parameters - Parameterized class must have a static method for generating and returning a collection of array, this method should be marked with @Parameters annotation.
Question: What’s the use of @Rule annotation?
Answer: @Rule annotation is used for creating objects, which later can be used in test methods.
Question: When you should run JUnit test, Is there any particular time interval between each run?
Answer: No there is no time constraint. A JUnit test needs to run whenever there is a change in the source code. This ensures that the new change passes through all the tests.
Question: Can we change return type of JUnit test method from void to some other type?
Answer: Ideally you should not do this. All the JUnit test methods should have a void return type. If you change the return type then the test method would not be considered as a test method and would be ignored during execution of tests.
Question: Is it possible to pass command-line arguments to a test execution?
Answer: Yes, It’s possible to pass command line arguments to a test execution -
You should use this command:
-D JVM command-line options
Question: How @Test annotation is used for testing exceptions?
Answer: @Test (expected = Exception.class)
Limitation: It is used for testing only a single exception.
This is Part 2 of Q&A. Read first part here - JUnit (Java Unit Testing) interview questions and answers – Part1.
Question1: What is Junit?
Answer: Java + unit testing = Junit
  1. Junit is open source testing framework developed for unit testing java code and is now the default framework for testing Java development.
  2. It has been developed by Erich Gamma and Kent Beck.
  3. It is an application programming interface for developing test cases in java which is part of the XUnit Family.
  4. It helps the developer to write and execute repeatable automated tests.
  5. Eclipse IDE comes with both Junit and it’s plug-in for working with Junit.
  6. Junit also has been ported to various other languages like PHP, Python, C++ etc.
Question2:  Who should use Junit, developers or testers?
Answer: Used by developers to implement unit tests in Java.  Junit is designed for unit testing, which is really a coding process, not a testing process. But many testers or QA engineers are also required to use Junit for unit testing.
Question3:  Why do you use Junit to test your code?
Answer: Junit provides a framework to achieve all the following-:
  1. Test early and often automated testing.
  2. Junit tests can be integrated with the build so regression testing can be done at unit level.
  3. Test Code reusage.
  4. Also when there is a transfer Junit tests act as a document for the unit tests.
Question4:  How do you install Junit?
Answer: Let’s see the installation of Junit on windows platform:
1. Download the latest version of Junit from http://download.sourceforge.net/junit/
2. Uncompress the zip to a directory of your choice.
3. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar
4. Test the installation by running the sample tests that come along with Junit located in the installation directory. Therefore, make sure that the JUnit installation directory is on your CLASSPATH. Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an “OK” message. If the tests don’t pass, verify that junit.jar is in the CLASSPATH.
Question5: What are unit tests?
Answer: A unit test is nothing more than the code wrapper around the application code that can be executed to view pass – fail results.
Question6:  When are Unit Tests written in Development Cycle?
Answer: Tests are written before the code during development in order to help coders write the best code. Test-driven development is the ideal way to create a bug free code. When all tests pass, you know you are done! Whenever a test fails or a bug is reported, we must  first write the necessary unit test(s) to expose the bug(s), and then fix them. This makes it almost impossible for that particular bug to resurface later. 
Question7:  How to write a simple Junit test class?
Answer: To write a test case, follow these steps:
  1. Define a subclass of TestCase.
  2. Override the setUp() method to initialize object(s) under test.
  3. Optionally override the tearDown() method to release object(s) under test.
Define one or more public testXYZ() methods that exercise the object(s) under test and assert expected results.
Question8:  What Is Junit TestCase?
Answer: JUnit TestCase is the base class, junit.framework.TestCase, that allows you to create a test case. (Although, TestCase class is no longer supported in JUnit 4.4.)
A test case defines the fixture to run multiple tests. To define a test case
-Implement a subclass of TestCase
-Define instance variables that store the state of the fixture
-Initialize the fixture state by overriding setUp
-Clean-up after a test by overriding tearDown
Each test runs in its own fixture so there can be no side effects among test runs.
Question9: What Is Junit TestSuite?
Answer: JUnit TestSuite is a container class under package junit.framework.TestSuite. It allows us to group multiple test cases into a collection and run them together. (JUnit 4.4 does not support TestSuite class now).
Question10: What is Junit Test Fixture?
Answer: A test fixture is a fixed state of a set of objects used as a baseline for running tests. Their purpose is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. Examples of fixtures:
  • Loading a database with a specific, known set of data
  • Copying a specific known set of files
  • Preparation of input data and setup/creation of fake or mock objects
If a group of tests shares the same fixtures, you should write a separate setup code to create the common test fixture. If a group of tests requires different test fixtures, you can write code inside the test method to create its own test fixture.
Question11:  What happens if a Junit test method is declared as “private”?
Answer: If a Junit test method is declared as “private”, the compilation will pass ok. But the execution will fail. This is because Junit requires that all test methods must be declared as “public”.
Question12:  What happens If a Junit test method Is declared to return “String”?
Answer: If a Junit test method is declared to return “String”, the compilation will pass ok. But the execution will fail. This is because Junit requires that all test methods must be declared to return “void”.
Question13:  Why not just use system.out.println () for Unit Testing?
Answer: Debugging the code using system.out.println() will lead to manual scanning of the whole output every time the program is run to ensure the code is doing the expected operations. Moreover, in the long run, it takes lesser time to code Junit methods and test them on our files.
Question14:  The methods Get () and Set () should be tested for which conditions?
Answer: Unit tests performed on java code should be designed to target areas that might break. Since the set() and get() methods on simple data types are unlikely to break, there is no need to test them explicitly. On the other hand, set() and get() methods on complex data types are vulnerable to break. So they should be tested.
Question15: For which conditions, the methods Get () and Set () can be left out for testing?
Answer: You should do this test to check if a property has already been set (in the constructor) at the point you wish to call getX(). In this case you must test the constructor, and not the getX() method. This kind of test is especially useful if you have multiple constructors.
Question16: Do you need to write a test class for every class that needs to be tested?
Answer: No. We need not write an independent test class for every class that needs to be tested. If there is a small group of tests sharing a common test fixture, you may move those tests to a new test class. If you have two groups of tests that you think you’d like to execute separately from one another, it is wise to place them in separate test classes.
Question17: How do you test a “protected” method?
Answer: A protected method can only be accessed within the same package where the class is defined. So, testing a protected method of a target class means we need to define your test class in the same package as the target class.
Question18: How do you test a “private” method?
Answer: A private method only be accessed within the same class. So there is no way to test a “private” method of a target class from any test class. A way out is that you can perform unit testing manually or can change your method from “private” to “protected”.
Question19: Do you need to write a main () method compulsorily in a Junit test case class?
Answer: No. But still developers write the main() method in a JUnit test case class to call a JUnit test runner to run all tests defined in this class like:
public static void main(String[] args) {
   junit.textui.TestRunner.run(Calculator.class);
}
Since you can call a JUnit runner to run a test case class as a system command, explicit main() for a Junit test case is not recommended. junit.textui.TestRunner.run() method takes the test class name as its argument. This method automatically finds all class methods whose name starts with test. Thus it will result in below mentioned findings:
  1. testCreateLogFile()
  2. testExists()
  3. testGetChildList()
It will execute each of the 3 methods in unpredictable sequence (hence test case methods should be independent of each other) and give the result in console.
Question20:  What happens if a test method throws an exception?
Answer: If you write a test method that throws an exception by itself or by the method being tested, the JUnit runner will declare that test as fail.
The example test below is designed to let the test fail by throwing the uncaught IndexOutOfBoundsException exception:
import org.junit.*;
import java.util.*;
public class UnexpectedExceptionTest2 {
// throw any unexpected exception
@Test public void testGet() throws Exception {
      ArrayList emptyList = new ArrayList();
      Exception anyException = null; // don't catch any exception
      Object o = emptyList.get(1); }
}
If you run this test, it will fail:
OUTPUT:
There was 1 failure:
 testGet(UnexpectedExceptionTest2)
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
 at java.util.ArrayList.RangeCheck(ArrayList.java:547)
 at java.util.ArrayList.get(ArrayList.java:322)
 at UnexpectedExceptionTest2.testGet(UnexpectedExceptionTest2.ja
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAcce
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMe
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.junit.internal.runners.TestMethod.invoke(TestMethod.java
 at org.junit.internal.runners.MethodRoadie.runTestMethod(Method
 at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.j
 at org.junit.internal.runners.MethodRoadie.runBeforesThenTestTh
 at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie
 at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.jav
 at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMetho
 at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUni
 at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4Cla
 at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassR
 at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoa
 at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4Class
 at org.junit.internal.runners.CompositeRunner.runChildren(Compo
 at org.junit.internal.runners.CompositeRunner.run(CompositeRunn
 at org.junit.runner.JUnitCore.run(JUnitCore.java:130)
 at org.junit.runner.JUnitCore.run(JUnitCore.java:109)
 at org.junit.runner.JUnitCore.run(JUnitCore.java:100)
 at org.junit.runner.JUnitCore.runMain(JUnitCore.java:81)
 at org.junit.runner.JUnitCore.main(JUnitCore.java:44)
FAILURES!!!
Tests run: 1,  Failures: 1
Question21:  When objects are garbage collected after a test is executed?
Answer: By design, the tree of Test instances is built in one pass. Then the tests are executed in a second pass. The test runner holds strong references to all Test instances for the duration of the test execution. This means that for a very long test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run. Therefore, if you allocate external or limited resources in a test, you are responsible for freeing those resources. Explicitly setting an object to null in the tearDown() method, for example, allows it to be garbage collected before the end of the entire test run.
Question22: What is Java “assert” statement?
Answer: Java assertions allow the developer to put “assert” statements in Java source code to help unit testing and debugging.
An “assert” statement has the following format:
assert boolean_expression : string_expression;
When this statement is executed:
  • If boolean_expression evaluates to true, the statement will pass normally.
  • If boolean_expression evaluates to false, the statement will fail with an “AssertionError” exception.
Helper methods which help to determine if the methods being tested are performing correctly or not
  • assertEquals([String message], expected, actual) –any kind of object can be used for testing equality –native types and objects, also specify tolerance when checking for equality in case of floating point numbers.
  • assertNull([String message], java.lang.Objectobject) –asserts that a given object is null
  • assertNotNull([String message], java.lang.Objectobject) –asserts that a given object isnotnull
  • assertTrue([String message], Boolean condition) –Asserts that the given Boolean condition is true
  • assertFalse([String message], Boolean condition) –Asserts that the given Boolean condition is false
  • fail([String message]) –Fails the test immediately with the optional message 
Example-:
 public void testSum() {
   int num1 = 15;
   int num2 = 50;
   int total = 35;
   int sum = 0;
   sum = num1 + num2;
   assertEquals(sum, total);
 }

100+ Core Java Interview Questions

by Chaitanya Singh

Java – OOPs Interview questions

Q) Three Principles of OOPS language?
Inheritance
Polymorphism
Data Encapsulation
Q) Java vs. C ++?
Simple
Multi-threaded
Distributed Application
Robust
Security
Complexities are removed (Pointers, Operator overloading, Multiple inheritance).
Q) What is javac ?
It produces the java byte code when *.java is given as input and it is the intermediate representation of your source code that contains instructions that the java interpreter will execute.
Q) What all terms are related to OOPs?
Class
Object
Methods
Inheritance
Polymorphism
Overriding
Abstraction
Encapsulation
Interface
Q) What is class?
Class is nothing but a template, which describes the various properties and functions.
Q) What is an object?
Object has its own properties and functionality; also it’s an instance of the class.
Q) How many times does the garbage collector calls the finalize() method for an object?
The garbage collector calls the finalize() method Only once for an object.

Q) What are two different ways to call garbage collector?
System.gc() OR Runtime.getRuntime().gc().

Q) Can the Garbage Collection be forced by any means?
No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.

Q) Abstract class?
A class for which object can’t be instantiated/created, such class are called as Abstract class. Also a class, which is, generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
Q) Multiple Inheritances?
Inheriting more than one parent class. Java doesn’t supports multiple inheritances whereas c++  supports.
Q) What is the method overriding?
In inheritance, when a child class writes a method with the same name as method in super-class is called method overriding.  Method call on the child class will execute the child class method not the super class method.
There can be no object of an abstract class.
Constructors or static methods cannot be declared as abstract.
Q) Can this keyword be assigned null value?
No, this keyword cannot have null values assigned to it.

Q) What is a WeakHashMap?
a) A hash table map with duplictate keys.
b) A general purpose hash table-based implementation to better store.
c) A hash table-based Map implementation with weak keys.
d) A list with weak references to objects.

Ans is option (c).
WeakHashMap is a hash table-based Map implementation with weak keys.

Q) Which of the following lines allow main method to be executed by ClassLoader?
a) public static String main(String a[]);
b) protected static void main(String a[]);
c) final public static void main(String a[]);
d) public static void main();
e) private static void main(String a[]);
f) public void main(String a[]);

Ans is (c). In order for the ClassLoader to execute the main() method, it has to be declared atleast as public, static & void.
Q) Which modifiers a method of local inner class can have?
Only abstract or final keyword is allowed.

Q) Do we need to implement any method of Serializable interface to make an object serializable?
No.In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.

Q) What is a transient variable?
transient variables are not included in the process of serialization.
They are not the part of the object’s serialized state.
Variables which we don’t want to include in serialization are declared as transient.

Q) Does a static nested class have access to the enclosing class’ non-static methods or instance variables?
No. A static nested class doesn’t have access to the enclosing class’ non-static methods or instance variables.

Q) Which modifiers can be applied to the inner class?
public ,private , abstract, final, protected.

Q) Polymorphism?
In a class, 2 methods with same name having different number of arguments is called polymorphism. Is also called as function overloading.
Q) Does Java support operator overloading?
Operator overloading is not supported in Java.
Q) Encapsulation?
Group of Data & functions are said to be an Encapsulation with single entity. Objects should not be allowed to access the properties of class instead could have separate methods thru which the property can be accessed.
Q) Interface?
Interfaces are a collection of method prototypes, the implementation of which has to be done by a class that inherits it. When it is declared as public, any class can use the interface. Once an interface3 has been defined, any classes can implements that interface.
Interfaces are java’s substitute for multiple inheritances.
Interfaces can be extended.
One interface can inherit another by use of keyword extends.
When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface chain.

Core Java – Interview Questions

Q) Different Data types in Java.
Byte  – 8   bit     (are esp. useful when working with a stream of data from a network or a file).
Short  – 16 bit
Char   – 16 bit Unicode
Int       – 32 bit (whole number)
Float    – 32 bit (real number)
Long    – 64 bit (Single precision)
Double  -  64 bit  (double precision)
Note: Any time you have an integer expression involving bytes, shorts, ints and literal numbers, the entire expression is promoted to int before the calculation is done.
Q) What is Unicode?
Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.
Q) What is Literals?
A literal is a value that may be assigned to a primitive or string variable or passed as an argument to a method.
Q) Dynamic Initialization?
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
Q) What is Type casting in Java?
To create a conversion between two incompatible types, you must use a cast. There are automatic casting and explicit casting.
Q) Arrays?
An array is to store the group of like-typed variables that are referred to by a common name.
Q) Explain about BREAK stmt in java?
In Java, the break stmt has 3 uses.
First, it terminates a statement sequence in a switch statement.
Second, it can be used to exit a loop
Third, it can be used as “go to” keyword
Q) What are Constructors?
Constructors are special methods belonging to a class. These methods are basically used to do initialization of instance variables. They are automatically called whenever an instance of a class is created.
Q)THIS keyword?
The THIS keyword is a reference to the current object which is automatically created.
Q) Garbage collection in java?
Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no references to an object exist for a long time is called garbage collection.
Q) Use of finalize() method in java?
FINALIZE () method is used to free the allocated resource.
Q) Explain ways to pass the arguments in Java?
In java, arguments can be passed in 2 ways,
Pass by value – Changes made to the parameter of the subroutines have no effect on the argument used to call it.
Pass by reference – Changes made to the parameter will affect the argument used to call the subroutine.
Q) Explain SUPER in Java?
First calls the superclass constructor.
Second, is used to access a method of the superclass that has been hidden by a member of a subclass.
A subclass can call a constructor method defined by its super class by using super (parameter-list). Super must always be the first statement.
Q) What is a Object class?
This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods
objectClone () – to creates a new object that is same as the object being cloned.
boolean – determines whether one object is equal to another.
finalize – called before an unused object is recycled.
toString () – returns a string that describes the object.
Q) What are Packages? 
Package is group of multiple classes under one name space.
Q)What is the difference between import java.utilDate and java.util.* ?
The star form may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-time performance.
Q) Why can’t I do myArray.length () ? Arrays are just objects, right?
Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as toString () and hashCode () on an array. However, length is a data item of an array and not a method. So you have to use myArray.length.
Q) How can I put all my classes and resources into one file and run it?
Use a JAR file. Put all the files in a JAR, then run the app like this:
Java -jar [-options] jarfile [args...]
Q) Can I declare a data type inside loop in java?
Any Data type declaration should not be inside the loop.
Q) Advantage over jdk 1.0 vs. jdk 1.1 ?
Jdk1.1 release consists of Java Unicode character to support the multiple language fonts, along with Event Handling, Java security, Java Beans, RMI, SQL are the major feature provided.
Q) java.lang.* get imported by default. For using String and Exception classes, you don’t need explicitly to import this package. The major classes inside this package are
Object class
Data type wrapper classes
Math class
String class
System and Runtime classes
Thread classes
Exception classes
Process classes
Class classes
Q) Arrays can be defined in different ways. All ways are right.
1
2
3
4
5
6
7
int arr[] = null;

int arr[][] = new int arr[][];

int [][] arr = new arr [][];

int [] arr [] = new arr[][];
Q) What is static method means?
When a member is declared as Static, it can be accessed before any objects of its class are created, and without references to any object.
It allocates the memory once and uses the same until the end of the class.
Note: It is illegal to refer to any instance variable inside of a static method.
Q) Use of final keyword in Java?
Final methods – mean methods cannot be override by any other method.
Final variable – means constant, the value of the variable can’t be changed, its fixed.
Final class – Means can’t be inherited to other class. This type of classes will be used when application required security or someone don’t want that particular class.

Exception handling in Java – Interview Questions

Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?
Java.lang.Exception
This package contains definitions for Exceptions.

Q) What is throw keyword in exception handling?
throw keyword is used to throw the exception manually. While creating user defined exception you would be needing to use throw keyword.

Q) Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception(Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.

Q) throw & throws statement?
Throwing an exception, in its most basic form is simple. You need to do two things. First, you create an instance of an object that is a subclass of java.lang.Throwable. Next you use the throw keyword to actually throw the exception.
If you write a method that might throw an exception (and this includes un-handled exceptions that are generated by other methods called from your method), then you must declare the possibility using a throws statement.
Q) Different Exception types?
Checked exceptions – describes problems that can arise in a correct program, typically difficulties with the environment such as user mistakes or I/O problems. These exceptions are not a programming error, rather more likely with the Environment behavior. Java.lang.Exception is the class used.
Unchecked exception – Exception, which occurs at the runtime, is called Unchecked exception. Java.lang.RuntimeException class is used. Runtime exception describes the program bugs. Such exceptions arise from things like out-of-bounds a correctly coded program would avoid array access, Database connection, MalformedURLException, EOFException, NullPointerException, IllegalState Exception etc and normally this.
Q) Interview questions about exception class –  
The Exceptions classes are derived from Throwable class. The structure is given below.
Java.lang.Throwable class
Java.lang.Exception (Checked Exception)
Java.lang.RuntimeExceptions (Unchecked Exception).
Java.lang.Error
ArrayBoundOutOfException – Whenever an array is referenced outside its boundary.
NumberFormatException – When we try Illegal operation with any data types. For e.g., performing arithmetic on String variable.
NullPointerException  – When the Dynamic Variable carries value as “null” during the condition will result in null pointer exception.
ClassCastException – Attempting to use a reference as if it referred to an object of some class – but it doesn’t
EmptyStackException – Tried to pop or peek from an empty stack
IllegalStateException – A method was activated when the object was in a state that violates the method’s precondition.
NegativeArraysizeException – Allocating an array with a negative number of components
IOException – An input or output error
Q) finally block?
Irrespective of success or failure of try/catch block, the finally block gets execute. Finally block will best utilized to close your open database connections, open files etc.

Java I/O Interview Questions

Q) Write a Small program to read an input from command prompt ?
1
2
3
4
5
6
7
8
9
10
11
12
13
Public class ClassName{
    public static void main(String a[])
    try{
        char ch = (char) system.in.read();
        if (Character.isJavaIdentifiedPart(ch);
           System.out.println(“ is a Identifier”);
        if (Character.isJavaIdentifiedStart(ch);
           System.out.println(“can be start of Identifier”);
        }catch(Exception e){
           System.out.println(e);
         }
     }
}
Points to remember: Math is a final class. Cannot be override. It can imported from java.lang.*. All the methods( ceil(), floor(), rint(), round(), random() ) in this class are static and they can be invoked automatically.
An only double data type is the input for math methods.
Q) List of classes under java.util. *?
This package contains the basic classes, which form as a java’s data structure. Since java doesn’t support Structures, Unions, and Pointers as in c++, hence this package is used.
Vector – is for growable array. It allows storing different objects of any type.
StringTokenizer – Generating tokens for a given string based on delimiter.
Stack – LIFO, FIFO
Date -   is depreciated in jdk 1.1, 1.2, use Calendar in-spite
Calender – System data and calendar
Enumeration – hasMoreElements(); nextElement()
Hashtable – Key value pair.
Q) Wrapper Classes?
Vector and Stack classes allow operation only for object not for data types. Hence some of the data types are wrapped to convert them into object to put into vector. Such data type wrapper classes are
Integer, Double, Float, Character etc.
For e.g.
1
2
3
4
Vector v = new Vector();
int I = 5; //this can’t be added to vector hence need to wrap
Integer ii = new Integer(I);
v.addElement(ii);
Q) Different methods can operates on Vector are
1
2
3
4
v.elementAt(int);
v.insertElementAt(object, int);
removeElementAt(int);
removeAllElements();
Q) Hashtable ?
Hashtable are used to store key and value pair. User need not to worry about whether the variable is stored rather we just need to know the key retrieve the corresponding “value”.
Hashtable h1 – new Hashtable();
Methods are :
1
2
3
4
5
6
7
8
9
10
11
12
h1.put(“key”,”value”);
h1.get(“key”);

Sample program to find out the list of all keys from hastable.

1
Enumeration e = h1.keys();
While (e.hasMoreElements())
{
   object obj = e.nextElement();
   h1.get(obj);
}
Go through all the
Basic Arithmetic operators like (+, -, *, /, %, ++, --, += ).
Boolean logical operators like (&, |, ^, ||, && )
The ? Operator (ternary operator).
Shift operators (>>, <<, >>>). Very important.
Q) How do I resize an array?
You can't resize an array. Once an array is created, you will not be able to change the length of it. You can allocate a new array, copy the elements into the new array, and set the reference to the original array to point to the new array -
1
2
3
4
5
ABC[] arr = new ABC[];
// Below I'm creating a new array with larger size
XYZ[] newarr = new XYZ[5];
System.arraycopy(arr, 0, newarr, 0, arr.length);
arr = newarr;
Q) What is a Java Bean?
A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.

Applet Interview Questions

Q) How do you do file I/O from an applet?
Unsigned applets are simply not allowed to read or write files on the local file system .
Unsigned applets can, however, read (but not write) non-class files bundled with your applet on the server, called resource files
Q) What is container ?
A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog

Learning)
  1. Flow Layout is default for panel.
  2. Border Layout is default for Frames.
Q) On Windows, generally frames are invisible, how to make it visible. ? 
1
2
3
Frame f = new Frame();
f.setSize(300,200);  //ht and width
f.setVisible(true) ;  // Frames appears
Q) JFC –  Java Foundation Class
Swing
AWT
Java2D
Drag and Drop
Accessibility

Learning) Listeners and Methods?
ActionListerner -   actionPerformed();
ItemListerner -  itemStateChanged();
TextListener -  textValueChanged();
FocusListener -  focusLost(); & FocusGained();
WindowListener -   windowActified(); windowDEactified(); windowIconified(); windowDeiconified(); windowClosed(); windowClosing(); windowOpened();
MouseMotionListener - mouseDragged(); & mouseMoved();
MouseListener -  mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClicked();
Learnings)
parseInt – to convert string to int.
getBytes – string to byte array
Q) Applet Life cycle?
Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy().
Q) showStatus() ?–
To display the message at the bottom of the browser when applet is started.
Q) What is the Event handling?
Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event Handling.
Q) What is Adapter class?
Adapter class is an abstract class.
Advantage of adapter: To perform any window listener, we need to include all the methods used by the window listener whether we use those methods are not in our class like Interfaces whereas with adapter class, its sufficient to include only the methods required to override. Straight opposite to Interface.
Q) Diaglog can be modal, non-modal dialog.
Dialog d = new Dialog(this,”Title”,true)  - 3rd parameter indicated whether dialog frame is modal or non-modal.
Q) Handling keyboard events?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.awt.*, java.awt.event.*, java.applet.*;
public class CN extend Applet implements KeyListener {
   String msg = “”:
   int X= 10, Y =20;
   public void init(){
     addKeyListener(this);
     requestFocus();
}

public void keyPressed(KeyEvent ke){
   showStatus(“Key Down”);
}

public void keyReleased(KeyEvent ke){
   showStatus(“Key UP”);
}

public void keyTyped(KeyEvent ke){
   msg += ke.getKeyChar();
   repaint();
}

public void paint(Graphics g){
   g.drawString(msg,X,Y);
}
}

Java Multithreading Interview Questions

Q) Thread?
In concurrent programs, several independent activities happen at the same time. Java models this through an interface, Runnable that embodies generic activities and a class, Thread that is responsible for the independent execution of Runnable.
Thread Life cycle: Starts with init(), start(), run(), stop() and destroy().
Learning) Other Thread methods
  1. stop() kills the thread. (Different from Applet.stop().)
  2. sleep(ms): non-busy wait for ms milliseconds, then throws InterruptedExceptions.
  3. setPriority(int pr): lowest = 1, highest = 10 , normal =5
  4. yield(): signals its willingness to give up CPU. Control transferred only when there is a ready thread of the same or higher priority.
  5. wait() vs. notify()
  6. suspend() vs. resume()
Q) Java Threads
  1. interface Runnable
  2. abstract class Thread
Two different ways to implement threads
Extends Thread class
  1. create a subclass of Thread class
  2. implement void run() method, which will be the main body of the thread.
  3. initiated by start(), and terminates when run() ends.
Implements Runnable interface
  1. create a class implementing Runnable interface.
  2. create a Thread instance inside the class (with this as an argument).
  3. invoke start() method.
  4. initiated by creating the class instance, terminates when run() ends.
Q) Synchronization?
I have good news and bad news for you. The bad news is that you can run into big problems when two or more threads share parameters. Recall that the threads run independently and re likely to interfere during complex operations.
One has to enforce proper synchronization between threads. In Java, synchronized is a keyword applied to methods:
public synchronized void someMethod()
Each Java object has a lock. To execute synchronized code on an object, a thread must own the object's lock. When two threads execute code synchronized on the same object, only one of them acquires the lock and proceeds. The other is paused until the first one releases the lock. Thanks to synchronization each thread has a chance to use the object with no meddling from the other thread.
Learning)  A thread that waits on an object is automatically woken up by other threads calling notifyAll() on the same object. wait() is efficient and consumes no CPU cycles. notify() is faster than notifyAll() but it can be dangerous when several threads wait on the same object. In practice, it is seldom used and I suggest you stick to the safer notifyAll().
If no result is available getResult() waits:
1
2
3
4
5
6
7
public synchronized Object getResult()
throws InterruptedException
{
  while (result == null)
    wait();
  return result;
}

Interview Questions related to Java Strings?

Q) StringBuffer class ?
An instance of this class represents a string that can be dynamically modified. A String buffer has a capacity, which is the maximum-length string it can represent without needing to allocate more memory. A string buffer can grow beyond this as necessary, so usually do not have worry about capacity.
Different methods are
1
2
3
StringBuffer sb = new StringBuffer(“Planetasia”);
sb.insert(3,”xyz”); // plaxyznetasia
sb.append(“abc”);   // plaxyznetasiaabc
Q) Different methods operated on String?
String s1 = “Planetasia”;
String s2 = “bangalore”;
int i = 3;
s1.charAt(i); - will find the character at that position.
s1.indexOf(“t”); - will return the position of “t” in the string “s1”.
s1.lastIndexOf(“a”); - will return the position of “a” starting the index at the end.
s1.equals(s2) – String s1 and s2 content will be compared, return true if they are equal.
s1 == s2           - The reference of both the string will be compared.
s1.compareTo(s2) – will compare 2 strings and result three possible value
0          – if both the strings are equal.
> 1       - if s1 is greater than s2
< 1       - if s2 is greater than s1.
s1.endsWith, s1.startsWith, s1.equalsIgnoreCase.
Q) trim (). ?
Is a method used to remove the unwanted space in the beginning and end of the variable?
Q) A small program on StringTokenizer -
1
2
3
4
5
6
7
8
9
10
11
12
13
public class CN
{
    public static void main(String a[]){
      String s = "Java in two days" ;
      StringTokenizer st = new StringTokenizer(s,” “);
      int I = st.countToken();
      while(st.hasMoreTokens(I))
      {
         String y = st.nextToken();
         System.out.println(y);
      }
    }
}
Q) What is the difference between String s = “abc”; and String s = new String(“abc”); ?
As such no big difference, but second statement will take extra memory allocation.

JDBC(Java to Database Connectvity) Interview Questions

Q) JDBC package contains a set of classes and methods for issuing SQL stmt, table update and calls to stored procedure.
Java Application ---jdbc api---------à JDBC driver Manager ----uses JDBC driver Api to load---à  JDBC Driver protocol à DB
Q) Java Soft has defined 4 types of drivers to connect with db thru DB driver?
Type 1 – JDBC-OBDCBridge
Type 2 -  Native-API-Partly-Java driver
Type 3 -  JDBC-Net-All-Java driver
Type 4 -  Native Protocol-All-Java driver
Q) 3 classes for sending sql stmts to DB thru connection object.
Statement – created by method createStatement(). A statement object is used to sending simple sql’s.
PreparedStatement – method prepareStatement() uses. It has potential & efficient than a statement object becoz it has been pre-compiled and stored it for future use.
CallableStatement -  are used to execute the SQL stored procedures.
Q) The statement interface provides 3 different methods for executing SQL stmts, what are those?
executeQuery() –  Queries like select.
executeUpdate() – Queries like insert, update, delete and also for DDL
execute()   - it returns boolean. If true means all select query is operated, if it false DML queries have taken place.
Q) What is Connection in JDBC?
A connection object represents a connection with a database. A connection session includes SQL stmts that are executed and the results are returned over that connection. A single application can have more connection with a single DB.
Opening a connection is established with a db to call method DriverManager.getConnection().
Template to create connection on to database located at URL : “jdbc:odbc:wombat”
1
2
String Url = "jdbc:odbc:wombat";
Connection con = DriverManager.getConnection(Url,"username","password");

Test your skills - Guess the answers of Java programs - for Written tests as well as to sharpen the Java Knowledge

Question - What is o/p of following program?
1
2
3
4
5
6
7
8
9
10
11
12
public class Test
{
    public static void main(String args[])
    {
       int num = 132;
       List ls = new ArrayList();
       ls.add(new Object());
       ls.add("Welcome");
       ls.add(num);
       System.out.println(ls.get(1));
    }
}
a) Welcome
b) It will give a Compilation Error!!
c) Runtime Error will occur
d) 132

Ans is (a)
‘Welcome’ gets printed since it is the 2nd object(String object) in the list and ArrayList index starts from 0.

Question - What is o/p of following program?
1
2
3
4
5
6
public class FClass {
   private int final FNUM;
   public static void main(String args[]){
      System.out.println(new FClass().FNUM);
   }
}
a) 1
b) 0
c) RunTimeException
d) Compile time error.

Ans is (d). private final variable FNUM needs to be initialized (should have some value assigned) since its declared final.
Question - Select methods that correctly overload the following method
1
byte sampMethod(short i) throws Exception {...}
a) int sampMethod(int i) throws IOException{...}
b) protected int sampMethod(short shr) throws FileNotFoundException{...}
c) private String sampMethod(byte byt,short shr) throws Exception{...}
d) char sampMethod(String str) throws RuntimeException{...}
e) int sampMethod(short shr){...}
Ans is (a),(c)& (d)

Question -
1
2
3
4
5
6
7
8
public class MyClass
{
   public static void main(String[] args)
   {
       int[] myArr = new int[]{0,1,2,3,4,5};
       System.out.println(myArr[0]+ myArr[5]+myArr[2]);
   }
}
a) 032
b) It will throw a Compilation Error!!
c) 7
d) 172

Ans is (c).
Hint: Array(myArr) index starts from 0.

Question - Will this code compile fine?
1
2
3
4
5
6
7
8
public class final HMap {
  private static final Map m = new HMap();
  public static void main(String[] args) {
     m.put("p1","v1"); //line num:3
     m.put("p2","v2");
     m = new HMap(); //line num:5
  }
}
a) Yes
b) No, Compilation Error at line 3
c) No, Runtime Error
d) No, Compilation Error at line 5

Ans is (d). Once declared the final variable cannot be initialized again.
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.io.*;
class Demo
{
     Demo() throws IOException
     {
        throw new IOException();
     }
}

class test1 extends Demo
{
    public static void main(String a[]) throws Exception
    {
        try
        {
            test1 aObj = new test1();
         }
         catch(Exception io)
         {
            System.out.println("Catch2");
         }
    }

    test1() throws Exception,ClassCastException
    {
         try{
             System.out.println("constructor");
         }
         catch(Exception io)
         {
            System.out.println("Catch1");
         }
    }
}
What is output?
1. Catch1
2. Catch2
3. Compilation Fail.
4. Runtime Exception
5. Code runs fine with No output
Ans is (2).
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Demo
{
    int inum = 10;
}
class Sample extends Demo
{
   int inum = 15;
   public static void main(String[] args)
   {
    Sample obj1 = new Sample();
    Demo obj2 = new Sample();
    System.out.println(obj1.inum);
    System.out.println(obj2.inum);
    System.out.println(((Demo)obj1).inum );
   }
}
1. 15 10 15
2. 15 15 15
3. 10 10 10
4. 15 10 10
5. 10 15 104
6. Compilation Fails.
7. Runtime Exception.

Ans: (4).
Question -
1
2
3
4
5
6
7
8
9
class Test
{
    public static void main(String[] args)
    {
     byte byt1 = -128;
     byte byt2 =  128;
     System.out.println(byt1+byt2);
    }
}
1. 0
2. 1
3. -1
4. Compilation Fails.
5. Runtime Exception

Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
public class A
{
     public static void main(String a[])
     {
     byte byt1 = 1 ,  byt2 =2,  res;
     res = byt1 + byt2--;
     System.out.println("Ans :"+res);
     }
}
1. 0
2. 1
3. 2
4. 3
5. Compilation Fails.
6. Runtime Exception

Ans: (5)
1
2
3
4
5
6
7
8
9
public class A
{
    public static void main(String a[])
    {
    short shr = 2;
    int num = shr++ - shr++;
    System.out.println(""+num++  +  shr);
    }
}
1. 0
2. 1
3. -14
4. -13
5. 3
6. 4

Ans: (3)
Question -
1
2
3
4
5
6
7
8
9
public class A
{
    public static void main(String a[])
    {
    int i = 1;
    for(;;){}
    System.out.println("Hello world");
    }
}
Ans: Compilation error. For(;;) forms an Infinite loop
Question - Which of the following are not valid ?
1. String String;
2. Integer Integer;
3. Double Object;
4. int main;
5. int unsigned;

Ans: Nothing is INVALID
Question -
1
2
3
4
5
6
7
8
9
public class Sample
{
    int inum = 1;
    public static void main(String a[])
    {
    int inum = 12;
        System.out.print( this.inum );
     }
}
Ans: inum is a non-static variable, this cannot be referenced from a static context
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
public class A extends A1,A2   //Line no: 1
{
     public static void main(String a[])
     {
    System.out.println("Hi");
     }
}

interface I extends I1,I2 {}   //Line no: 2
interface I1{}
interface I2{}
class A1{}
class A2{}
1. Runs Fine
2. Compilation Error at Line no: 1
3. Compilation Error at Line no: 2
4. Compilation Error at Line 1 and Line 2.
5. Runtime Exception

Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Demo
{
   static String myMethod(int i)
   {
       return "int";
   }
   static String myMethod(float i)
   {
       return "float";
   }
   public static void main (String[] args)
   {
      long num1 = 1;
      double num2 = 2;
      System.out.print(myMethod(num1)+","+ myMethod(num2));
   }
}
What is the Result ?
1. Prints: float,double
2. Prints: float,float
3. Prints: double,float
4. Compile-time error
5. None of the above

Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
10
11
class XYZ
{
      {
         System.out.println("initializer");
      }
      public static void main(String a[])
      {
             System.out.println("hello");
             XYZ obj=new XYZ();
       }
}
What is the Result ?
1.prints hello and initializer
2.prints initializer and hello
3.compile time error
4.runtime error
5.None of the above

Ans: (1)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
class bike { }
class Demo extends bike
{
    public static void main(String[] args)
    {
    Demo[] a1=new Demo[2];
    bike[] a2;
    a2=a1;                 //Line no:3
    Test[] a3;
    a3=a1;                //Line no:5
    }
}
What is the Result ?
1. compile time error at line 3
2. compile time error at line 5
3. Runtime exception
4. The code runs fine
5. None of the above

Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
class Test
{
     static interface I     //Line no:1
     {
     static class Test2{}            //Line no:2
      }
      public static void main(String a[])
      {
     Test.I.Test2 ob1=new Test.I.Test2();   //Line no:3
     System.out.println("object created");
      }
}
What is the Result ?
1. Print object created.
2. Compilation Error at line 1.
3. Compilation Error at line 2.
4. Compilation Error at line 3.
5. Runtime Exception
6. None of the above

Ans: (1)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void parse(String str)
{
  try
  {
     float f = Float.parseFloat(str);
  }
  catch (NumberFormatException nfe)
  {
     f = 0;
  }
  finally
  {
     System.out.println(f);
  }
}

public static void main(String[] args)
{
   parse("invalid");
}
What is the result?
1. 0.0
2. 0
3. Compilation fails.
4. NumberFormatException is thrown at runtime.
5. ParseException is thrown at runtime.

Ans: (3)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MyThreadClass implements Runnable
{
   public void run()
   {
      System.out.print("thread is running");
   }
   public static void main(String[] args)
   {
       Thread th = new Thread(new MyThreadClass());
       th.run();
       th.run();
       th.start();
   }
}
What is the result?
1. Compilation fails.
2. An exception is thrown at runtime.
3. The code executes and prints "thread is running".
4. The code executes and prints "thread is runningthread is running".
5 The code executes and prints "thread is runningthread is runningthread is running".

Ans: (5)
Question -
Which modifiers would be valid in the declaration of a main() method so that the class can be run from command line?
Can select multiple options.

1.native
2.protected
3.public
4.final
5.abstract

Ans: (3), (4)
Question -
Which of the following class can not be extended ?
1. Object
2. Thread
3. Error
4. Exception
5. Throwable.
6. String

Ans: (6)

What is Inheritance in Java Programming?

by Chaitanya Singh
Inheritance in java is one of the essential feature of Object-Oriented Programming (OOP). Inheritance allows a class to use the properties and methods of another class. In other words, the derived class inherits the states and behaviors from the base class. The derived class is also called subclass and the base class is also called superclass. The derived class can add its own additional variables and methods. These additional variable and methods differentiates the derived class from the base class.
Inheritance is a compile-time mechanism. A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritance.
I have covered Inheritance in detail at one of my Post: OOPs Concepts in Java.
The superclass and subclass have “is a” relationship between them. Let’s have a look at the example below.

Inheritance in java programming

Let’s consider a superclass ‘Vehicle’. Different vehicles have different attributes but there are a few attributes which are common to all. Speed, color, fuel used, size are some of them. Hence we can create a class ‘Vehicle’ with states and actions that are common to all vehicles. The subclass of this superclass can be any type of vehicle. Example, Car. A Car has all the features of a vehicle. But it has its own attributes which makes it different from other subclasses. By using inheritance we need not rewrite the code that we’ve already used with the ‘Vehicle’. The subclass can also be extended. We can make a class ‘Sports Car’ which extends ‘Car’. It inherits the features of both ‘Vehicle’ and ‘Car’.
The keyword used for inheritance is extends. The syntax is as given below.
1
2
3
public class extends {
 // derived class methods extend and possibly override
 }
Here is a simple example to illustrate the use of inheritance in Java.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// A class to display the attributes of the vehicle
class vehicle {
String color;
int speed;
int size;
void attributes() {
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}

// A subclass which extends for vehicle
class car extends vehicle {
int CC;
int gears;
void attributescar() {
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("CC of Car : " + CC);
System.out.println("No of gears of Car : " + gears);
}
}
public class Test {
public static void main(String args[]) {
car b1 = new car();
b1.color = "Blue";
b1.speed = 200 ;
b1.size = 22;
b1.CC = 1000;
b1.gears = 5;
b1.attributescar();
}
}
The output is
Color of Car : Blue
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5

Note:
The derived class inherits all the members and methods that are declared as public or protected. If declared as private it can not be inherited by the derived classes. The private members can be accessed only in its own class. The private members can be accessed through assessor methods as shown in the example below. The derived class cannot inherit a member of the base class if the derived class declares another member with the same name.
PFB inheritance in java with example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// A class to display the attributes of the vehicle
class vehicle {
String color;
private int speed;
private int size;
public int getSize() {
return size;
}
public int getSpeed() {
return speed;
}
public void setSize(int i) {
size = i;
}
public void setSpeed(int i) {
speed = i;
}
}

// A subclass which extends for vehicle
class car extends vehicle {
int CC;
int gears;
int color;
void attributescar() {
// System.out.println("Speed of Car : " + speed); // Error due to access violation
// System.out.println("Size of Car : " + size); // Error due to access violation

}
}
public class Test {
public static void main(String args[]) {
car b1 = new car();
b1.color = 500; // the subclass can inherit 'color' member of the superclass
b1.setSpeed(200) ;
b1.setSize(22);
b1.CC = 1000;
b1.gears = 5;

// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + b1.color);
System.out.println("Speed of Car : " + b1.getSpeed());
System.out.println("Size of Car : " + b1.getSize());
System.out.println("CC of Car : " + b1.CC);
System.out.println("No of gears of Car : " + b1.gears);

}
}
The output is
Color of Car : 500
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5

Types of inheritance in Java

Read my below post to understand Simple, Multiple, Multilevel and hybrid inheritance. You would also be able to know why java doesn’t support Multiple inheritance.
Read more at: Types of inheritance in Java

Constructors and Inheritance in Java

The constructor in the superclass is responsible for building the object of the superclass and the constructor of the subclass builds the subclass part. When a constructor of the subclass is defined, the default superclass constructor will be called implicitly. Hence, under inheritance the objects are constructed top-down. The superclass constructor can be called explicitly using the keyword super, but it should be first statement in a constructor. The keyword super always refers to the superclass immediately above the calling class in the hierarchy. The use of multiple supers to access an ancestor class other than the direct parent is illegal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class shape {
private int length;
private int breadth;
public int getBreadth() {
return breadth;
}

public int getLength() {
return length;
}
public void setBreadth(int i) {
breadth = i;
}
public void setLength(int i) {
length = i;
}

// default Constructor
shape() {
length = 0;
breadth = 0;
System.out.println("Inside default constructor of Shape ");
}

// Parameterized Constructor
shape(int len, int bdth) {
length = len;
breadth = bdth;
System.out.println("Inside constructor of Shape ");
System.out.println("length : " + length);
System.out.println("breadth : " + breadth);
}
}

// A subclass which extends for shape
class rectangle extends shape {
private String type;

// default Constructor
rectangle() {
super();
type = null;
System.out.println("Inside default constructor of rectangle ");
}

// Parameterized Constructor
rectangle(String ty, int len, int bdth) {
super (len, bdth);
System.out.println("Inside constructor of rectangle ");
System.out.println("length : " + len);
System.out.println("breadth : " + bdth);
System.out.println("type : " + type);
}

public String getType() {
return type;
}

public void setType(String string) {
type = string;
}
}

// A subclass which extends for rectangle
class coloredRectangle extends rectangle {
private String color;
/* default Constructor*/
coloredRectangle() {
super();
color = null;
System.out.println("Inside default constructor of coloredRectangle ");
}

// Parameterized Constructor
coloredRectangle(String c, String ty, int len, int bdth) {
super (ty, len, bdth);
System.out.println("Inside constructor of coloredRectangle ");
System.out.println("length : " + len);
System.out.println("breadth : " + bdth);
System.out.println("type : " + ty);
}
public String getColor() {
return color;
}
public void setColor(String string) {
color = string;
}
}

public class Test {
public static void main(String args[]) {
coloredRectangle CR = new coloredRectangle();
coloredRectangle CR2 = new coloredRectangle("Red","Big", 5, 2 );
}
}
The output is:
Inside default constructor of Shape
Inside default constructor of rectangle
Inside default constructor of coloredRectangle
Inside constructor of Shape
length : 5
breadth : 2
Inside constructor of rectangle
length : 5
breadth : 2
type : null
Inside constructor of coloredRectangle
length : 5
breadth : 2
type : Big

Method Overriding

A method from the superclass can be redefined in the subclass. The new method in the subclass will have the same return type, method name and number and type of parameters. This is called method overloading. This new method will have a different definition in the derived class. If it has different number and type of parameters then it is called method overloading.
The access specifier can allow more access in the overriding method. But it can not reduce the access. Example, a protected method can be made public in the subclass but cannot be made private.
By using super we can access the overridden method in the super class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class shape {
private int length;
private int breadth;
// default Constructor
shape() {
length = 0;
breadth = 0;
}
// Parameterized Constructor
shape(int len, int bdth) {
length = len;
breadth = bdth;
}
void showattributes() {
System.out.println("length : " + length);
System.out.println("breadth : " + breadth);
}
}

// A subclass which extends for shape
class rectangle extends shape {
private String type;
/* default Constructor
*/
rectangle() {
type = null;
}
// Parameterized Constructor
rectangle(String ty, int len, int bdth) {
super(len,bdth);
type = ty;
}
void showattributes() {
super.showattributes(); // showattributes() in shape is called
System.out.println("type : " + type);
}
}

public class Test {
public static void main(String args[]) {
rectangle rect = new rectangle("Blue",5,7);
rect.showattributes(); // showattributes() in rectangle is called
}
}
The output is :
length : 5
breadth : 7
type : Blue

Method overriding is the basis of dynamic method dispatch which is one of Java’s most powerful concepts. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at the run time and not at compile time. This is how run-time polymorphism implemented in Java. When an overridden method is called, the type of object being referred to decide which version of the method will be executed. This is done at the run-time. Overridden methods are another way of implementing “one interface, multiple methods” aspect of polymorphism in java.

Abstract Classes

The superclasses are more general than their subclasses. Usually, the superclasses are made abstract so that the objects of its prototype cannot be made. So the objects of only the subclasses can be used. To make a class abstract, the keyword abstract is used in the class definition.
Abstract methods are methods which do not have method statements. The subclasse provides the method statements. The methods provided by the superclass needs to be overridden by the subclass. The class that has at least one abstract method should be made abstract. The abstract class can not be instantiated because it does not define a complete implementation.
1
2
3
public abstract class {
 ….
 }
Using Final with methods
We can prevent a method from being overridden by using the keyword final at the start of its declaration.
Final methods can not be overridden.

The syntax is as given below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public abstract void methodname();

class shape {

final void showattributes() {
 System.out.println("Inside class shape ");

 }
 }

 // A subclass which extends for shape
 class rectangle extends shape {

void showattributes() { // Cannot override the final method
 System.out.println("Inside class rectangle");
 }
 }
The method showattributes() cannot be overridden in the class rectangle because it is declared as final in class shape. It shows an error when we try to override it.
Using Final with class
We can also prevent inheritance by making a class final. When a class is declared as final, its methods also become final. An abstract class cannot be declared as final because an abstract class is incomplete and its subclasses need to provide the implementation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
final class shape {

void showattributes() {
 System.out.println("Inside class shape ");

}
 }

 /* A subclass which extends for shape
 */
 class rectangle extends shape { // The type rectangle cannot subclass the final class shape

void showattributes() {
 System.out.println("Inside class rectangle");
 }
 }
The class shape cannot be inherited because it is declared as final. It will show an error when we try to inherit it.

Using Final with data members

A variable can be made constant by making the variable name final. The value of the final variable cannot be changed throughout the lifetime of the program, but it can be given an initial value. These variables can be accessed via an object of the class in which they are declared. Also, they can be inherited by subclasses and accessed inside those subclasses.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class employee {
 final int empcode1 = 0;
 final int empcode2 = 1;
 final int empcode3 = 2;
 final int empcode4 = 3;
 String empname [] = {
 "ABC",
 "DEF",
 "GHI",
 "JKL"
 };
 String getempname(int i) {
 if (i >= 0 & i < empname.length)
 return empname[i];
 else
 return "Invalid Employee Number";
 }
 }
 public class Test {
 public static void main(String args[]) {
 employee emp = new employee();
 System.out.println(emp.getempname(emp.empcode1));
 System.out.println(emp.getempname(emp.empcode2));
 System.out.println(emp.getempname(emp.empcode3));
 System.out.println(emp.getempname(emp.empcode4));
 }
 }
Out put is:
ABC
DEF
GHI
JKL

Target Keywords: Inheritance in OOPS, Inheritance in Java, java inheritance example
Reference
Java 2: the complete reference: fifth Edition
http://java.sun.com

Polymorphism in Java – Method Overloading and Overriding

by Chaitanya Singh
In the last tutorial I shared about Java Inheritance and in this tutorial I will discuss about Polymorphism in java. Java is an Object Oriented Programming (OOPs) language. Polymorphism is one of the key point in OOPs concepts.

What is polymorphism in programming

Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations.
  • It is a  feature that allows one interface to be used for a general class of  actions.
  • An operation may exhibit different behavior in different instances.
  • The behavior depends on the types of data used in the operation.
  • It plays an important role in allowing objects having different internal structures to share the same external interface.
  • Polymorphism is extensively used in implementing inheritance.
In Java, the concept of polymorphism is achieved through:
1) Method Overloading
2) Method Overriding

Method Definition:
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name.
1)
Method Overloading:
In Java, it is possible to define two or more methods in a class, with the same name and the arguments or parameters should be different. This is known as Method Overloading.

I have covered method overloading and Overriding below. To know more about polymorphism types refer my post Types of polymorphism in java: Static, Dynamic, Runtime and Compile time Polymorphism.

1) Polymorphism in Java: Method Overloading

  1. To call an overloaded method in Java, it is must to use the type and/or number of arguments to determine which version of the overloaded method to actually call.
  2. Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method. .
  3. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
  4. It allows the user to achieve compile time polymorphism.
  5. An overloaded method can throw different exceptions.
  6. It can have different access modifiers.
java polymorphism tutorial example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Overload
{
  void demo (int a)
  {
     System.out.println ("a: " + a);
  }
  void demo (int a, int b)
  {
     System.out.println ("a and b: " + a + "," + b);
  }
  double demo(double a) {
     System.out.println("double a: " + a);
     return a*a;
  }
}
class MethodOverloading
{
  public static void main (String args [])
  {
     Overload Obj = new Overload();
     double result;
     Obj .demo(10);
     Obj .demo(10, 20);
     result = Obj .demo(5.5);
     System.out.println("O/P : " + result);
  }
}
Here the method demo() is overloaded 3 times with 1 integer parameter, 2 integer parameter and a double. The methods are invoked or called with the same type and number of parameters used.
Output:
a: 10
a and b: 10, 20
double a: 5.5
O/P : 30.25

Rules for Method Overloading

  1. Overloading can take place in the same or in its sub-class.
  2. Constructor in Java can be overloaded
  3. Overloaded methods must have a different argument list.
  4. Overloaded method should always be in part of the same class, with same name but different parameters.
  5. The parameters may differ in their type or number, or in both.
  6. They may have the same or different return types.
  7. It is also known as compile time polymorphism.

2) Polymorphism in Java: Method Overriding

The derived class which is extended from the base class has a method which is exactly similar to the one present in the base class. This is called as overriding a method.
Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class BaseClass
{
    Public void methodToOverride() //Base class method
    {
       System.out.println ("I'm the method of BaseClass");
    }
}

public class DerivedClass extends BaseClass
{
    Public void methodToOverride() //Derived Class method
    {
       System.out.println ("I'm the method of DerivedClass");
    }
}

public class TestMethod
{
    Public static void main (String args []) {
       BaseClass obj1 = new BaseClass(); // BaseClass reference and object
       BaseClass obj2 = new DerivedClass(); // BaseClass reference but DerivedClass object
       obj1.methodToOverride(); // Calls the method from BaseClass class
       obj2.methodToOverride(); //Calls the method from DerivedClass class
    }
}
Output:
I’m the method of BaseClass
I’m the method of DerivedClass

Rules for Method Overriding:

  1. applies only to inherited methods
  2. object type (NOT reference variable type) determines which overridden method will be used at runtime
  3. Overriding methods must have the same return type
  4. Overriding method must not have more restrictive access modifier
  5. Abstract methods must be overridden
  6. Static and final methods cannot be overridden
  7. Constructors cannot be overridden
  8. It is also known as Runtime polymorphism.

Using the super keyword:

When invoking a superclass version of an overridden method the super keyword is used.
Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Vehicle {

    Public void move () {
      System.out.println ("Vehicles are used for moving from one place to another ");
    }
 }

 class Car extends Vehicle {
    Public void move () {
       Super. Move (); // invokes the super class method
       System.out.println ("Car is a good medium of transport ");
    }
}

public class Test Car {
  Public static void main (String args []){
     Vehicle b = new Car (); // Vehicle reference but Car object
     b.move (); //Calls the method in Car class
  }
}
Output:
Vehicles are used for moving from one place to another
Car is a good medium of transport

Encapsulation in Java

by Chaitanya Singh
I have already discussed about encapsulation in brief in my article OOPs concepts. Also, I covered Java polymorphism and Java inheritance in separate articles. Here I will cover Java encapsulation in detail.

What is encapsulation?

Encapsulation means the localization of the information or knowledge within an object. In other words you can say that Using this technique data can be hidden. but how?? If a data member is private which means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. This way data can be accessed by public methods of the same class and would not be accessed outside the class. That’s the reason encapsulation is known as data hiding.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class EncapsDemo{
   private int ssn;
   private String empName;
   private int empAge;

   public int getEmpSSN(){
      return ssn;
   }

   public String getEmpName(){
      return name;
   }

   public int getEmpAge(){
      return age;
   }

   public void setEmpAge( int newValue){
      empAge = newValue;
   }

   public void setEmpName(String newValue){
      empName = newValue;
   }

   public void setEmpSSN( String newValue){
      ssn = newValue;
   }
}
public class EncapsTest{
   public static void main(String args[]){
      EncapsDemo obj = new EncapsDemo();
      obj.setEmpName("Mario");
      obj.setEmpAge(32);
      obj.setEmpSSN("1111222233");
      System.out.print("Employee Name: " + obj.getEmpName());
      System.out.print("Employee SSN: " + obj.getEmpSSN());
      System.out.print("Employee Age: " + obj.getEmpAge());
} }
Output:
Employee Name: Mario
Employee SSN: 1111222233
Employee Age: 32

you can see in above example that all the three data members are private which gets accessed using private methods of local class. These variables will not be accessible in any other class. Employee name, SSN and Age will become hidden data members using encapsulation technique of OOPs.
Encapsulation is also called as “Information Hiding”.
  1. Objects encapsulate data and implementation details. To the outside world, an object is a black box that exhibits a certain behavior.
  2. The behavior of this object is what which is useful for the external world or other objects.
  3. An object exposes its behavior by means of methods or functions.
  4. The set of functions an object exposes to other objects or external world acts as the interface of the object.

Does Java support Multiple inheritance?

by Chaitanya Singh
In this post we will learn why java doesn’t support multiple inheritance. We would also see how to achieve this using interfaces in Java.

Why Java doesn’t support multiple inheritance?

C++ , Common lisp and few other languages supports multiple inheritance while java doesn’t support it. It is just to remove ambiguity, because multiple inheritance can cause ambiguity in few scenarios. One of the most common scenario is Diamond problem.

What is diamond problem?

Consider the below diagram which shows multiple inheritance as Class D extends both Class B & C. Now lets assume we have a method definition in class A and Class B & C overrides that method in their own way. Wait!! here the problem comes - Because D is extending both B & C so if D wants to use the same method which method would eligible either from B or C? Ambiguity. That’s the main reason why Java doesn’t support multiple inheritance.
multiple inheritance diamond problem Does Java support Multiple inheritance?

How to achieve multiple inheritance in Java using interfaces?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface X
{
   public void myMethod();
}
interface Y
{
   public void myMethod();
}
class Demo
{
   public void myMethod()
   {
        System.out.println(" Multiple inheritance example using interfaces");
    }
}
class testMultiple extends Demo implements X, Y
{
....
}
As you can see that in above example class extends only one class but it can implements more than one interfaces. SO that’s how we can achieve multiple inheritance in Java.

Multilevel inheritance in java with example

by Chaitanya Singh
We discussed a bit about Multilevel inheritance in types of inheritance in java. In this tutorial we will explain multilevel inheritance with the help of  diagram and example program.

Diagram representation:

Multilevel Inheritance Diagram Multilevel inheritance in java with example
It’s pretty clear with the diagram that in Multilevel inheritance there is a concept of grand parent class. If we take the example of above diagram then class C inherits class B and class B inherits class A which means B is a parent class of C and A is a parent class of B. So in this case class C is implicitly inheriting the properties and method of class A along with B that’s what is called multilevel inheritance.

Example Program:

In this example we have three classes –  Car, Maruti and Maruti800. We have done a setup – class Maruti extends Car and class Maurit800 extends Maurti. With the help of this Multilevel hierarchy setup our Maurti800 class is able to use the methods of both the classes (Car and Maruti).
package beginnersbook.com;
class Car{
       public Car()
       {
              System.out.println("Class Car");
       }
       public void vehicleType()
       {
              System.out.println("Vehicle Type: Car");
       }
}
class Maruti extends Car{
       public Maruti()
       {
              System.out.println("Class Maruti");
       }
       public void brand()
       {
              System.out.println("Brand: Maruti");
       }
       public void speed()
       {
              System.out.println("Max: 90Kmph");
       }
}
public class Maruti800 extends Maruti{
 
        public Maruti800()
        {
               System.out.println("Maruti Model: 800");
        }
        public void speed()
              {
                    System.out.println("Max: 80Kmph");
              }
        public static void main(String args[])
        {
               Maruti800 obj=new Maruti800();
               obj.vehicleType();
               obj.brand();
               obj.speed();
        }
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

What is an Interface in java – Basics with examples

by Chaitanya Singh
An interface in java is an abstract type which is used to specify an interface (generic sense) that java class will implement.

Declaration

Interfaces are created by specifying a keyword “interface”. E.g.:
1
2
3
4
5
interface Interf
{
  public void method1 ();
  public void method2 ();
}

Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Class 1
class Bea implements Interf
{
  public void method1 ()
  {
     System.out.println(“implementation method1”);
  }
  public void method2 ()
  {
     System.out.println(“implementation method2”);
  }

  public static void main(String arg[])
  {
    Interf i=new Interf();
    i. method1 ();
  }

}

Key points:

1) While providing implementation of any interface method, it needs to be mentioned as public.
2) Class implementing any interface must implement all the methods, otherwise the class should be declared as “abstract”.
3) Interface cannot be declared as private, protected or transient.
4) All the interface methods are by default abstract and public.
5) Variables declared in interface are by default public, static and final.

1
2
3
4
5
6
7
8
interface Try
{
   int a=10;
   public int a=10;
   public static final int a=10;
   final int a=10;
   static int a=0;
}
All of the above statements are identical.
6) Interface variables must be initialized at the time of declaration otherwise compiler will through an error.
1
2
3
4
interface Try
{
      int x;
}
Above code will throw a compile time error.
7) Inside any implementation class, you cannot change the variables declared in interface because by default, they are public, static and final.
1
2
3
4
5
6
7
Class Sample implement Try
{
  public static void main(String arg[])
  {
     x=20; //compile time error
  }
}
8) Any interface can extend any other interface but cannot implement it.
9) A class can implements any number of interfaces.
10) If there are having two are more same methods in two interfaces and a class implements both interfaces, implementation of one method is enough.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface A
{
  public void aaa();
}
interface B
{
   public void aaa();
}
class Central implement A,B
{
   public static void main(String arg[])
   {
      public void aaa()
      {
        .....
      }
    }
}
11) Methods with same signature but different return type can’t be implemented at a time for two or more interfaces.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface A
{
   public void aaa();
}
Interface B
{
   public int aaa();
}

class Central implement A,B
{
   public static void main(String arg[])
   {
      public void aaa() // error
      {
      }
      public int aaa() // error
      {
      }
   }
}
12) Variable names conflicts can be resolved by interface name e.g:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface A
{
    int x=10;
}
interface B
{
    int x=100;
}
class Hello implement A,B
{
    public static void Main(String arg[])
    {
       System.out.println(x); // reference to x is ambiguous both variables
       System.out.println(A.x);
       System.out.println(B.x);
    }
}

Benefits:

Following are the benefits of interfaces:
  1. Without bothering about the implementation part, we can achieve the security of implementation
  2. In java, multiple inheritances are not allowed, but alternative to that can be provided with interfaces as a class can extend only one class but can implement any number of interfaces. It saves you from Deadly Diamond of Death(DDD).

How to throw exception in java with example

by Chaitanya Singh
In java we have predefined implicit exceptions such as Arithmetic Exception, ArrayIndexOutOfBoundsException etc. There are certain conditions coded for such exceptions and whenever those cases or conditions occurs these exceptions are thrown implicitly.
Do you know that a programmer can create a new exception and throw it explicitly? In order to throw user defined exceptions throw keyword is being used. In this tutorial, we will see how to create a new exception and throw it in a program using throw keyword.
You can also throw an implicit exception such as Arithmetic exception using throw in java for your defined condition.

Syntax of throw statement

throw AnyThrowableInstance;
for e.g.:
public void sample(){
   //Statements
   //if (somethingWrong)
   IOException e = new IOException();
   throw e;
   //More Statements
 }
Note:
  • A call to the above mentioned sample method should be always placed in a try block as it is throwing a Checked Exception – IOException.
  • Exceptions in Java are compulsorily of type Throwable. If you attempt to throw an object that is not throwable, the  compiler refuses to compile your program and it would show a compilation error.
Flow of execution while throwing an exception using throw keyword
Whenever a throw statement is encountered in a program the next statement doesn’t execute. Control immediately transferred to try block to see if the thrown exception is handled there. If thrown exception is handled then control is transferred to corresponding catch block otherwise next try block is being checked for exception and so on. If none of the try-catch block handled thrown exception then a system generated exception message is being populated on screen, same as we get for unhandled implicit exceptions.

Examples of throw exception in Java

Example 1: How to throw your own exception explicitly using throw keyword
class MyOwnException extends Exception {
public MyOwnException(String msg){
super(msg);
}
}
 
public class EmployeeTest {
 
    static void  employeeAge(int age) throws MyOwnException{
            if(age < 0)
                  throw new MyException("Age can't be less than zero");
            else
                 System.out.println("Input is valid!!");
     }
     public static void main(String[] args) {
             try {
                  employeeAge(-2);
            }
           catch (MyOwnException e) {
               e.printStackTrace();
          }
     }
}
Output:
Age can’t be less than zero

Points to Note: Exception call should be in try block.
Example2: How to throw a predefined exception using throw keyword
class Exception2{
   static int sum(int num1, int num2){
     if (num1 == 0)
        throw new ArithmeticException("First parameter is not valid");
     else
        System.out.println("Both parameters are correct!!");
   }
   public static void main(String args[]){
      int ans=sum(0,12);
      System.out.println("Continue Next statements");
   }
}
Output:
Exception in thread main java.lang.ArithmeticException: First parameter is not valid

Similar to example 2 you can throw any predefined exception such as NullPointerException, ArrayIndexOutOfBoundsException etc.
Target keywords: how to throw NullPointerException java,  java method throws exception, Throw exception in Java.

Java Static Class Block Methods and Variables

by Chaitanya Singh
This tutorial is to help you understand the use of Static keyword in Java. It can be used along with Class name, Variables, Methods and block. We will cover it one by one in below sequence.
1. Static Class
2. Static Block
3. Static Methods
4. Static Variables

1. Java Static Class

A Class can be made static only if it is a nested Class. The nested static class can be accessed without having an object of outer class.

Examples of Static Class

Example1:
1
2
3
4
5
6
7
8
9
10
11
12
class Example1{

static class X{
static String str="Inside Class X";
}

public static void main(String args[])
{
 X.str="Inside Class Example1";
 System.out.println("String stored in str is- "+ X.str);
}
}
Output: String stored in str is- Inside Class Example1
Example2: Compile time Error!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Example2{
int num;

static class X{
static String str="Inside Class X";
num=99;
}

public static void main(String args[])
{
 Example2.X obj = new Example2.X();
 System.out.println("Value of num="+obj.str);
}
}
Output: Compile time error. Static inner class cannot access instance data of outer class.

2. Java Static Block

Static block is generally used to change the default values of static variables. This block gets executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute as per the sequence given in the code.

Examples of Static Block

Example3: Single static block
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Example3{
static int num;
static String mystr;
static{
 num = 97;
 mystr = "Static keyword in Java";
}

public static void main(String args[])
{
 System.out.println("Value of num="+num);
 System.out.println("Value of mystr="+mystr);
}
}
Output:
Value of num=97
Value of mystr=Static Keyword in Java

Example4: Multiple Static blocks execution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Example4{
static int num;
static String mystr;
static{
 System.out.println("Static Block 1");
 num = 68;
 mystr = "Block1";
}

static{
 System.out.println("Static Block 2");
 num = 98;
 mystr = "Block2";
}

public static void main(String args[])
{
 System.out.println("Value of num="+num);
 System.out.println("Value of mystr="+mystr);
}
}
Output:
Static Block 1
Static Block 2
Value of num=98
Value of mystr=Block 2

3. Java Static Methods

Static Methods can be used to access class variables without having any object of the class. It can access non-static methods and variables with the help of instances(objects). These methods can be accessed directly in static and non-static methods.
Example5: Public static void main itself is a static method
1
2
3
4
5
6
7
8
9
10
11
12
class Example5{
static int i;
static String s;

public static void main(String args[]) //Its a Static Method
{
 Example5 obj=new Example5();
 //Non Static variables accessed using object obj
 System.out.println("i:"+obj.i);
 System.out.println("s:"+obj.s);
}
}
Output:
i:0
s:null

Example6: Static method display()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Example6{
static int i;
static String s;

static void display()
{
 //Its a Static method
 Example6 obj1=new Example6();
 System.out.println("i:"+obj1.i);
 System.out.println("i:"+obj1.i);
}

void funcn()
{
 //Static method called in non-static method
 display();
}

public static void main(String args[]) //Its a Static Method
{
 //Static method called in another static method
 display();
}
}

4.  Java Static Variables

  • Static variables are also known as Class Variables.
  • Such variables get default values based on the data type.
  • Data stored in static variables is common for all the objects( or instances ) of that Class.
  • Memory allocation for such variables only happens once when the class is loaded in the memory.
  • These variables can be accessed in any other class using class name.
  • Unlike non-static variables, such variables can be accessed directly in static and non-static methods.
Example7: Static variables can be accessed without reference in Static method
1
2
3
4
5
6
7
8
9
10
class Example7{
static int var1;
static String var2;

public static void main(String args[]) //Its a Static Method
{
 System.out.println("Var1 is:"+Var1);
 System.out.println("Var2 is:"+Var2);
}
}
Output:
Var1 is:0
Var2 is:null

In above example you can notice that both the variables are accessed in void main method without any object(reference).
Example8: Static variables are common for all instances
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Example8{
static int Var1=77; Static integer variable
String Var2;//non-static string variable

public static void main(String args[])
{
 Example8 ob1 = new Example8();
 ob1.Var1=88;
 ob2.Var2="I'm Object1";
 Example8 ob2 = new Example8();
 ob2.Var2="I'm Object2";
 System.out.println("ob1 integer:"+ob1.Var1);
 System.out.println("ob1 String:"+ob1.Var2);
 System.out.println("ob2 integer:"+ob2.Var1);
 System.out.println("ob2 STring:"+ob2.Var2);
}
}
Output:
ob1 integer:88
ob1 String:I’m Object1
ob2 integer:88
ob2 String:I’m Object2

In above example String variables is non-static and integer variable is Static. So you can see that String variable value is different for both objects but integer variable value is common for both the instances.

What is Finally Block

1. The finally statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block.
2. After all other try-catch processing is complete, the code inside the finally block executes. It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch parts of the block.
3. In normal execution the finally block is executed after try block. When any exception occurs first the catch block is executed and then finally block is executed.
4. An exception in the finally block, exactly behaves like any other exception.
5. The finally block in java code is executed even if the try or catch block contains control transfer statements like return, break or continue.
>>To understand above concepts better refer the examples at the end of this post.

Syntax of Finally block in Java

try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}

Cases wherein finally block doesn’t execute

The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

Java Finally and Return

Finally block executes even if there is a return statement in try-catch block. PFB the example -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}

public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
Output of above program:
This is Finally block
Finally block ran even after return statement
112

Java Finally and Close()

Close() is generally used to close all the open streams in one go. Its a good practice to use close() inside finally block. Since finally block executes even if exception occurs so you can be sure that all input and output streams are closed properly.
E.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
....
try{
      OutputStream osf = new FileOutputStream( "filename" );
      OutputStream osb = new BufferedOutputStream(opf);
      ObjectOutput op = new ObjectOutputStream(osb);
      try{
        output.writeObject(writableObject);
      }
      finally{
        op.close();
      }
}
catch(IOException e1){
      System.out.println(e1);
}
...

Java finally block without catch

A try-finally block is possible without catch block. Which means a try block can be used with finally without having a catch block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
InputStream input = null;
try {
input = new FileInputStream("inputfile.txt");
} finally {
if (input != null) {
try {
in.close();
} catch (IOException exp) {
System.out.println(exp);
}
}
}
...

Java Finally and System.exit()

System.exit() statement behaves differently than return statement. Unlike return statement whenever System.exit() gets called in try block then Finally block doesn’t get executed. Refer the below example to understand it better -
1
2
3
4
5
6
7
8
9
10
11
12
13
....
try {
//try block
System.out.println("Inside try block");
System.exit(0)
}
catch (Exception exp) {
System.out.println(exp);
}
finally {
System.out.println("Java finally block");
}
....
In the above example if the System.exit(0) gets called without any exception then finally won’t execute. However if any exception occurs while calling System.exit(0) then finally block will be executed.

Handling try-catch-finally block

  • Either a try statement should be associated with a catch block or with finally.
  • Since catch performs exception handling and finally performs the cleanup, the best approach is to merge both of them.
Syntax:
try
{
//statements that may cause an exception
}
catch (…)‏
{
//error handling code
}
finally
{
//statements to be executed
}

Examples of Try catch finally block in Java

Example 1: Below example illustrates finally block when no exception occurs in try block 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Example1{
 public static void main(String args[]){

try{
 System.out.println("First statement of try block");
 int num=45/3;
 System.out.println(num);
 }

catch(ArrayIndexOutOfBoundsException e){
 System.out.println("ArrayIndexOutOfBoundsException");
 }

finally{
 System.out.println("finally block");
 }
 System.out.println("Out of try-catch-finally block");
 }
 }
Output:
finally block
Out of try-catch-finally block

Example 2: Below example illustrates finally block when exception occurs in try block but doesn’t get handled in catch block 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Example2{
 public static void main(String args[]){

try{
 System.out.println("First statement of try block");
 int num=45/0;
 System.out.println(num);
 }

catch(ArrayIndexOutOfBoundsException e){
 System.out.println("ArrayIndexOutOfBoundsException");
 }

finally{
 System.out.println("finally block");
 }
 System.out.println("Out of try-catch-finally block");
 }
 }
Output:
finally block
System generated Arithmetic exception message

Example 3: Below example illustrates finally block in java, when exception occurs in try block and handled in catch block 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Example3{
 public static void main(String args[]){
 try{
 System.out.println("First statement of try block");
 int num=45/0;
 System.out.println(num);
 }

catch(ArithmeticException e){
 System.out.println("ArithmeticException");
 }

finally{
 System.out.println("finally block");
 }
 System.out.println("Out of try-catch-finally block");
 }
 }
Output:
ArithmeticException
finally block
Out of try-catch-finally block

Target keywords: exception thrown in finally block, try catch in finally block, try/catch finally java

Thread life cycle in java and thread scheduling

by Chaitanya Singh
In previous post I have covered almost all the terms related to Java threads. Here we will learn Thread life cycle in java, we’ll also see thread scheduling.

Thread Life cycle in Java

  • The start method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread’s run method.
  • A thread becomes “Not Runnable” when one of these events occurs:
    • If sleep method is invoked.
    • The thread calls the wait method.
    • The thread is blocking on I/O.
  • A thread dies naturally when the run method exits.

Recommended Reads:

  1. Multithreading in Java
Below diagram clearly depicts the various phases of thread life cycle in java.
 thread life cycle in java flowchart Thread life cycle in java and thread scheduling

2. Thread Scheduling

  • Execution of multiple threads on a single CPU, in some order, is called scheduling.
  • In general, the runnable thread with the highest priority is active (running)
  • Java is priority-preemptive
    • If a high-priority thread wakes up, and a low-priority thread is running
    • Then the high-priority thread gets to run immediately
  • Allows on-demand processing
  • Efficient use of CPU

2.1 Types of scheduling

  • Waiting and Notifying
    • Waiting [wait()] and notifying [notify(), notifyAll()] provides means of communication between threads that synchronize on the same object.
  • wait(): when wait() method is invoked on an object, the thread executing that code gives up its lock on the object immediately and moves the thread to the wait state.
  • notify(): This wakes up threads that called wait() on the same object and moves the thread to ready state.
  • notifyAll(): This wakes up all the threads that called wait() on the same object.
  • Running and Yielding
    • Yield() is used to give the other threads of the same priority a chance to execute i.e. causes current running thread to move to runnable state.
  • Sleeping and Waking up
    • nSleep() is used to pause a thread for a specified period of time i.e. moves the current running thread to Sleep state for a specified amount of time, before moving it to runnable state. Thread.sleep(no. of milliseconds);

2.2 Thread Priority

  • When a Java thread is created, it inherits its priority from the thread that created it.
  • You can modify a thread’s priority at any time after its creation using the setPriority method.
  • Thread priorities are integers ranging between MIN_PRIORITY (1) and MAX_PRIORITY (10) . The higher the integer, the higher the priority.Normally the thread priority will be 5.

2.3 isAlive() and join() methods

  • isAlive() method is used to determine if a thread is still alive. It is the best way to determine if a thread has been started but has not yet completed its run() method. final boolean isAlive();
  • The nonstatic join() method of class Thread lets one thread “join onto the end” of another thread. This method waits until the thread on which it is called terminates. final void join();

3. Blocking Threads

  • When reading from a stream, if input is not available, the thread will block
  • Thread is suspended (“blocked”) until I/O is available
  • Allows other threads to automatically activate
  • When I/O available, thread wakes back up again
    • Becomes “runnable” i.e. gets into ready state

4. Grouping of threads

  • Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually.
  • To put a new thread in a thread group the group must
  • be explicitly specified when the thread is created
    • - public Thread(ThreadGroup group, Runnable runnable)
    • - public Thread(ThreadGroup group, String name)
    • - public Thread(ThreadGroup group, Runnable runnable, String name)
  • A thread can not be moved to a new group after the thread has been created.
  • When a Java application first starts up, the Java runtime system creates a ThreadGroup named main.
  • Java thread groups are implemented by the java.lang.ThreadGroup class.
Target keywords: thread life cycle in java, java threading tutorial, using threads in java, javathread run.

Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid

by Chaitanya Singh
Below are Various types of inheritance in Java. We will see each one of them one by one with the help of examples and flow diagrams.

1) Single Inheritance

Single inheritance is damn easy to understand. When a class extends another one class only then we  call it a single inheritance. The below flow diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would be  a child class of A.

Single Inheritance Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid

Single Inheritance example program in Java
Class A
{
   public void methodA()
   {
     System.out.println("Base class method");
   }
}
 
Class B extends A
{
   public void methodB()
   {
     System.out.println("Child class method");
   }
   public static void main(String args[])
   {
     B obj = new B();
     obj.methodA(); //calling super class method
     obj.methodB(); //calling local method
  }
}

2) Multiple Inheritance

Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple inheritance” is that the derived class will have to manage the dependency on two base classes.
Multiple Inheritance Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often leads to problems in the hierarchy. This results in unwanted complexity when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.

3) Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class. As you can see in below flow diagram C is subclass or child class of B and B is a child class of A. For more details and example refer – Multilevel inheritance in Java.
Multilevel Inheritance Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid
Multilevel Inheritance example program in Java
Class X
{
   public void methodX()
   {
     System.out.println("Class X method");
   }
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
   public void methodZ()
   {
     System.out.println("class Z method");
   }
   public static void main(String args[])
   {
     Z obj = new Z();
     obj.methodX(); //calling grand parent class method
     obj.methodY(); //calling parent class method
     obj.methodZ(); //calling local method
  }
}

4) Hierarchical Inheritance

In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D. Read More at - Hierarchical Inheritance in java with example program.
Hierarchical Inheritance Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid

5) Hybrid Inheritance

In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple inheritance. A typical flow diagram would look like below. A hybrid inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you heard it right. By using interfaces you can have multiple as well as hybrid inheritance in Java.
Read the full article here - hybrid inheritance in java with example program.
Hybrid inheritance Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid


3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Best explanation on static keyword.
    https://www.flowerbrackets.com/static-keyword-in-java/

    ReplyDelete

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...