Follow me on Instagram -
https://www.instagram.com/virenautomationtesting/
Follow me on Twitter-
Saturday, 13 May 2017
TestNg Interview Best question and answers
TestNG scenarios with priority including negative priority
In TestNG, we can use ‘priority’ to decide the order of the test case execution. The rules are :
1. If you are not setting any priority to a test case along with @Test annotation then TestNG will consider it as priority=0 by default.So, keeping with priority =0 and with default priority is not plan either keep without priority or priority=0. Both are same things.
2. Yes, we can set negative priority with test case in TestNG.
3. If you are setting negative priority for a test case then it will be executed firstly compare to test case having priority positive or without priority.
4. Yes, you can give two same priorities for many test cases then the execution will depend on the alphabetical order of name of the @Test methods.
You can find all scenarios below with priority test cases. This is a very important part of TestNG. If you are going for a Selenium WebDriver with TestNG interview, then you will be surely asked about the priority scenarios.
Create a TestNG class in your Eclipse and test all these cases-
Q 1.
@Test(priority=0)
public void test(){
System.out.println("low priority");
}
@Test(priority=1)
public void test1()
{
System.out.println("high priority");
}
Ans: low priority
High priority
Q. 2
@Test(priority=1)
public void test(){
System.out.println("low priority");
}
@Test(priority=0)
public void test1()
{
System.out.println("high priority");
}
Ans: high priority
Low priority
Q .3
@Test(priority=1)
public void test(){
System.out.println("low priority");
}
@Test(priority=1)
public void aest1()
{
System.out.println("high priority");
}
Ans:
high priority
low priority
PASSED: aest1
PASSED: test
Q 4.
@Test(priority= -1)
public void test(){
System.out.println("low priority");
}
@Test(priority=0)
public void test1()
{
System.out.println("high priority");
}
Ans:- low priority
high priority
PASSED: test
PASSED: test1
@Test(priority= -1)
public void test(){
System.out.println("low priority");
}
@Test(priority=-2)
public void test1()
{
System.out.println("high priority");
}
Ans :
high priority
low priority
PASSED: test1
PASSED: test
Q 5. No Priority, priority=-1
@Test
public void test(){
System.out.println("low priority");
}
@Test(priority=-1)
public void test1()
{
System.out.println("high priority");
}
Ans:
high priority
low priority
PASSED: test1
PASSED: test
Q.6
@Test
public void test(){ //no priority
System.out.println("test Priority=null");
}
@Test(priority=-1)
public void testn()
{
System.out.println("test Priority=Negative");
}
@Test(priority=0) //priority=0
public void test1()
{
System.out.println("test Priority=zero");
}
@Test(priority= 1) //priority=1
public void test3()
{
System.out.println("test Priority=1");
}
Ans:-
test Priority=Negative
test Priority=null
test Priority=zero
test Priority=1
PASSED: testn
PASSED: test
PASSED: test1
PASSED: test3
In TestNG, we can use ‘priority’ to decide the order of the test case execution. The rules are :
1. If you are not setting any priority to a test case along with @Test annotation then TestNG will consider it as priority=0 by default.So, keeping with priority =0 and with default priority is not plan either keep without priority or priority=0. Both are same things.
2. Yes, we can set negative priority with test case in TestNG.
3. If you are setting negative priority for a test case then it will be executed firstly compare to test case having priority positive or without priority.
4. Yes, you can give two same priorities for many test cases then the execution will depend on the alphabetical order of name of the @Test methods.
You can find all scenarios below with priority test cases. This is a very important part of TestNG. If you are going for a Selenium WebDriver with TestNG interview, then you will be surely asked about the priority scenarios.
Create a TestNG class in your Eclipse and test all these cases-
Q 1.
@Test(priority=0)
public void test(){
System.out.println("low priority");
}
@Test(priority=1)
public void test1()
{
System.out.println("high priority");
}
Ans: low priority
High priority
Q. 2
@Test(priority=1)
public void test(){
System.out.println("low priority");
}
@Test(priority=0)
public void test1()
{
System.out.println("high priority");
}
Ans: high priority
Low priority
Q .3
@Test(priority=1)
public void test(){
System.out.println("low priority");
}
@Test(priority=1)
public void aest1()
{
System.out.println("high priority");
}
Ans:
high priority
low priority
PASSED: aest1
PASSED: test
Q 4.
@Test(priority= -1)
public void test(){
System.out.println("low priority");
}
@Test(priority=0)
public void test1()
{
System.out.println("high priority");
}
Ans:- low priority
high priority
PASSED: test
PASSED: test1
@Test(priority= -1)
public void test(){
System.out.println("low priority");
}
@Test(priority=-2)
public void test1()
{
System.out.println("high priority");
}
Ans :
high priority
low priority
PASSED: test1
PASSED: test
Q 5. No Priority, priority=-1
@Test
public void test(){
System.out.println("low priority");
}
@Test(priority=-1)
public void test1()
{
System.out.println("high priority");
}
Ans:
high priority
low priority
PASSED: test1
PASSED: test
Q.6
@Test
public void test(){ //no priority
System.out.println("test Priority=null");
}
@Test(priority=-1)
public void testn()
{
System.out.println("test Priority=Negative");
}
@Test(priority=0) //priority=0
public void test1()
{
System.out.println("test Priority=zero");
}
@Test(priority= 1) //priority=1
public void test3()
{
System.out.println("test Priority=1");
}
Ans:-
test Priority=Negative
test Priority=null
test Priority=zero
test Priority=1
PASSED: testn
PASSED: test
PASSED: test1
PASSED: test3
Friday, 10 March 2017
"Collection is the super most Interface in the collections framework and present into the "java.util" package.Interviewer will ask you like super most inteface is Iterable in JCF as collection interface extends the Iterable inteface then you should say as Iterable Inteface is present into java.lang package not in java.util.All interfaces(Data Structures) like List,Queue,set and Map commonly extending the Collection interface."
Note: Map is not a part of java collections framework but still it is extending the Collection interface.
Q 1. What is a Collection?
Ans :- "A collection is a object in java,which contains multiple objects may be same type or different type to group into a single unit".
Sometimes ,collection is also called a container which contains other objects called elements.
Q 2. What does stand for JCF in java?
Ans :- "JCF stands for 'Java collections framework' is a unified architecture for representing and manipulating collections
(eg. ArrayList, LinkedList) those are commonly implementing the Collection interface."
Q 3. What are the benefits of JCF and why do we need JCF in java ?
Ans:
1)Reduce the programming efforts
2)Increase the program speed and quality
3)Reducing the efforts in designing the new API's
Q 4.What does mean by collections ?
Ans :-"Collections is a class in java which implements the data structures like List,Set,Queue and used to store ,
retrieve ,delete ,searching, sorting data"
Q 5. How will you insert different different kinds of objects into ArrayList:-
Inserting different different kinds of objects into ArrayList and verifying that the object is present or not.
package AllCollections;
import java.lang.*;
import java.util.*;
interface Fruit{
}
///simple a interface creating
class Apple implements Fruit{
}
//Creating a class which is implementing the above interface (rule :class ->
implements interface)
public class DemoOfArrayList
{
public static void main(String[] args)
{
// Inserting different-2 object type into AL
ArrayList list = new ArrayList();
list.add(10);//adding a integer object
list.add(true);//adding a boolean object
list.add("hello");//adding a string object
list.add(new String("Bangalore"));
Apple ap =new Apple();
list.add(ap);
//Checking a object into a AL
System.out.println(list.contains(10));
System.out.println(list.contains("Viren"));
System.out.println(list.contains("Bangalore"));
System.out.println(list.contains(ap));
}
}
Q 6. Write a program to convert a ArrayList into Array:
package AllCollections;
import java.util.ArrayList;
import java.util.*;
public class ListToArrayConversion
{
static ArrayList list; //Defining a ArrayList and making as generic
static Object obj[]; //Defining a Array type object
//Declare a static method
static ArrayList getList()
{
System.out.println("Enter the list objects...");
list =new ArrayList();
list.add(10);
list.add(20);
list.add("Hello");
list.add(new String ("viren"));
System.out.println("Printing the List.."+"\n"+list);
return list;
}
static void convertListToArray()
{
ArrayList l=getList();
obj=l.toArray();
System.out.println("Printing the Array values .."+"\n");
for (Object o:obj)
{
System.out.println(o);
}
}
public static void main(String arg[])
{
convertListToArray();
}
}
Q 7 . Write a program to sort an array
import java.util.*;
public class DemoOfArraySorting
{
public static void main(String[] args)
{
int a[]={10,25,56,23,58,30};
System.out.println("Printing the arraya before sorting ..");
for (int x:a)
{
System.out.println(x);
}
Arrays.sort(a);
System.out.println("Printing the array after sorting..");
for (int y:a)
{
System.out.println(y);
}
}
Q 8. The difference between Iterator and ListIterator:-
The difference between Iterator and ListIterator :
Using Iterator,we can traverse the List objects in forward direction only with hasNext() and next() methods where using ListIterator we can traverse the List Objects into both direction as in forward using hasNext() and next() methods and reverse directions with hasPrevious() and previous() methods.
Q 9.Write a program to show the difference between Iterator and ListIterator interface ?
package AllCollections;
import java.util.*;
public class DemoOfIteratorAndListIterator
{
static ArrayList list;
static Iterator itr;
static ListIteratorlsitr;
static ArrayList getList()
{
System.out.println("Adding elements into list..");
list= new ArrayList();
list.add(10);
list.add("Hello");
list.add(20);
System.out.println(list);
return list;
}
//demo of Iterator
static void demoOfIterator()
{
ArrayList list1=getList();
itr=list1.iterator();
while (itr.hasNext())
{
System.out.println(itr.next()); }
}
//demo of ListIterator
static void demoOfListIterator()
{
ArrayList list1=getList();
lsitr =list1.listIterator(); //List Iterator
while (lsitr.hasNext())
{
System.out.println(lsitr.next());
System.out.println("Printing the next index number" +lsitr.nextIndex());
}
while (lsitr.hasPrevious()) {
System.out.println(lsitr.previous());
System.out.println("Printing the previous index number" +lsitr.previousIndex());
// -1 0 1 2
}
}
public static void main(String arg[])
{
demoOfIterator();
demoOfListIterator();
}
}
Q.10 How will you compare two lists in java ?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Test01 {
public static void compareLists(ArrayList<Integer> a, ArrayList<Integer> b)
{
boolean result = true;
if(a.size()==b.size())
{
if(a.equals(b))
{
System.out.println("Equal");
}
else
{
System.out.println("not Equal");
}
}
}
public static void main(String arg[])
{
ArrayList<Integer> al1= new ArrayList<Integer>(Arrays.asList(10,20,50));
ArrayList<Integer> al2= new ArrayList<Integer>(Arrays.asList(10,20,50));
compareLists(al1,al2);
System.out.println(al1.toString());
}
}
Q 11. What is a Map in java?
Ans :- "Map is an Interface in java that maps keys to corresponding values and key-value pairs called Entry." It is not child interface of the Collection interface.
Q 12. When should we use the Map ?
Ans:"Suppose we have a group of individual objects and we want to represent to them as key-value pairs then we should go for Map."
Eg. Suppose, I have 100 students and I want to store them according to their roll number then I will use Map to store so that searching will easy to access the particular student.
Roll No Name
--------- --------
101 Ravi
203 Ram
Here, both key(Roll No) and value(Name) are objects and duplicate keys are not allowed.
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> hash = new HashMap<Integer, String>();
hash.put(101, "Ravi");
hash.put(302, "Ram");
System.out.println("Map elemnets :"+hash);
}
}
O/P
Map elemnets :{101=Ravi, 302=Ram}
Q.13 What is HashMap in java ?
Ans: "HashMap is a non-synchronized class in java which allows us to store object as key value pair and implements the Map Interface."
Q.14 Please explain properties of the HashMap ?
Ans:
1. It is not thread safe because it is unsynchronized.
2. It allows one null key and any number of null values.
3. It does not follow any order which means it does not return the keys and values in the same order in which they have been inserted into the HashMap.
4.Hash Map objects are iterate through Iterator.
5. Hash Map is much faster and uses less memory.
Q. 15 Why should we use HashMap ?
Ans : The purpose of a map is to store items based on a key that can be used to retrieve the item at a later point. It is a data structure, based on hashing principle.
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Integer,String> hash = new HashMap<Integer, String>();
hash.put(101, "Ravi");
hash.put(302, "Ram");
System.out.println("Map elemnets :"+hash);
}
}
O/P
Map elemnets :{101=Ravi, 302=Ram}
Go Back
Q 1-What is Automation Testing or Test automation?
Ans:-" Software automation testing is a process in which we use a software tool to execute pre-scripted tests on a software application before it is released into production."Test automation can automate some repetitive but necessary tasks in a formalized testing process.Tests carried out with these tools can be run repeatedly, at any time of day.
Q 2. What types of testing can be automated?
Ans:"Automated testing is typically used in functional, regression testing, performance testing, load testing, network testing and security testing. The tools are very useful to speed up the test cycle as they can replicate manual testing processes at a much faster rate."
Q 3. Why we need the Test automation instead of Manual testing ?
Ans: Reasons
1. Regression testing can be laborious and time-consuming to do manually.
2. In addition, a manual approach might not always be effective in finding certain classes of defects.
3.Test automation offers a possibility to perform these types of testing effectively. Once automated tests have been developed, they can be run quickly and repeatedly.
4. Many times, this can be a cost-effective method for regression testing of software products that have a long maintenance life.
5. Even minor patches over the lifetime of the application can cause existing features to break which were working at an earlier point in time.have software coding ability, since the test cases are written in the form of source code which, when run, produce output according to the assertions that are a part of it.
Q 4. What are the advantages of the automation testing process ?
Ans:
In order to save test execution time and resource we can automate manual test cases, which save human effort and time as well.
> Automated Software Testing Saves Time and Money
"Every time source code is modified software tests should be repeated. For each release of the software it may be tested on
all supported operating systems and hardware configurations. Manually repeating these tests is costly and time consuming.
Once created, automated tests can be run over and over again at no additional cost and they are much faster than manual tests. Automated software testing can reduce the time to run repetitive tests from days to hours. A time savings that translates directly into cost savings."
.>Vastly Increases Your Test Coverage
"Test automation can easily execute thousands of different complex test cases during every test run providing coverage that is impossible with manual tests."
>Testing Improves Accuracy
"Sometime times a tester will make mistakes during manual testing.
Automated tests perform the same steps precisely every time they are executed and never
forget to record detailed results. Testers freed from repetitive manual tests have more time to create new automated software tests and deal with complex features"
> Automation Does What Manual Testing Cannot
"Even the largest software and QA departments cannot perform a controlled
web application test with thousands of users. Automated testing can simulate tens,
hundreds or thousands of virtual users interacting with a network, software and web applications."
Q 5. What are the disadvantage of the automation testing process?
Ans:-Skill level:
In automated testing the Test Engineer or Software quality assurance person must have software coding ability,since the test cases are written in the form of source code which, when run, produce output according to the assertions that are a part of it.
Tool needed-To write code we need suported tools and jar files.
Failed tests:
The time required to decide which of these reasons actually applies to your failed test.
failed, because of an actual bug. (just for completeness, as this is of course advantageous)
failed, because your test code has been written with a traditional bug.
failed, because your test code has been written for an older version of your product and is no longer
Non-failed tests
If you change something in your product's code, but the test doesn't account for it at all, then it gives you this "false sense of security".compatible
failed, because the requirements have changed and the tested behavior is now deemed 'correct'
>Proficiency is required to write the automation test scripts.
>Debugging the test script is major issue. If any error is present in the test script, sometimes it may lead to deadly consequences.
>Test maintenance is costly in case of playback methods. Even though a minor change occurs in the GUI, the test script has to be rerecorded or replaced by a new test script.
Maintenance of test data files is difficult, if the test script tests more screens.
Q 6. Which version of the selenium have you used?
Ans . Selenium 2 (Selenium WebDriver.)
Q 7 .Why are you using the selenium only?
Ans:-
1. Open source: Selenium is a open source tool available in market that means you no need to pay anything for this to require the licence and it’s freely available.
2. Browser support: Selenium support all the latest browsers like Chrome, MF,IE, Opera
3. Support different tools: Selenium support multiple tools like TestNG, Maven, AutoIt etc. those are also free available into the market.
4. Supporting large community: Many people are working on selenium in market and they have posted many posts regarding any issue in selenium and you can easily get the solution of the selenium related problem. We have many solutions and blogs for selenium.
5. Self API-Selenium WebDriver have own API so you no need to write much code and you just need to use the Interface and class in your code.
6. Mobile automation: Selenium also support mobile automation like Android , iOS.
Q 8. Explain the Selenium limitations?
Ans:-
1. Selenium does not support the Window based/desktop applications. It only supports the web applications.
2. We can’t automate the charts and graphs related test cases through the selenium.
3. We cannot automate the barcode and Capctha code using the selenium.
4. Selenium is open source so there is no official support.
Q 9. What types of the test cases you have automated?
Ans-I have automated the functional test cases including smoke test cases, regression test cases, end to end test cases.
Eg. I have automated the complete search functionality .
We did not automate the login and email and negative test scenarios and windows apps access test cases
Q 10. What type of framework have you designed?
Yes, I have designed the Hybrid and Data Driven framework.
Q 11. What is a Software Build and Release ?
In a software company, every day developers write new code based on the new requirements or bug fixes and then they will compile it to create an executable form. After that a final executable form is produced by a build tool which is 'set of all executable forms' which we called "software build ".
"A build is a executable form of a software which consists of all developed new features as well as few bug fixes and tested until it becomes stable" . It is a pre-release version and can be recognized by a build number.
This build is deployed into testing environment so that the tester can test the developed new functionality or bug fixes. Initial testing carried out on the build, is smoke testing, this done to check the stability I.e whether further testing can be carried out on this build.
Ex. Suppose you want to develop an Gmail application then let's say first, developer will develop the login page feature. We can say that we have developed the 10% portion of the application. Developer will create executable form after compiling the login source code file and then build tool will pick this code and generate the build for test team to test the stability. Next time, developer will develop the Inbox feature then we have next build version having the new feature and bug fixes in the first build. Testing team will again test this build stability. So let's say we have done the 20% portion of the application. This process will go continue till 100%, ie. until final Build is stable.
Implies no bugs or very few bugs and all features have been developed. Which means it is a complete software, which is ready to use. Now this final build is called a software. It is called a Release.
Ans:-" Software automation testing is a process in which we use a software tool to execute pre-scripted tests on a software application before it is released into production."Test automation can automate some repetitive but necessary tasks in a formalized testing process.Tests carried out with these tools can be run repeatedly, at any time of day.
Q 2. What types of testing can be automated?
Ans:"Automated testing is typically used in functional, regression testing, performance testing, load testing, network testing and security testing. The tools are very useful to speed up the test cycle as they can replicate manual testing processes at a much faster rate."
Q 3. Why we need the Test automation instead of Manual testing ?
Ans: Reasons
1. Regression testing can be laborious and time-consuming to do manually.
2. In addition, a manual approach might not always be effective in finding certain classes of defects.
3.Test automation offers a possibility to perform these types of testing effectively. Once automated tests have been developed, they can be run quickly and repeatedly.
4. Many times, this can be a cost-effective method for regression testing of software products that have a long maintenance life.
5. Even minor patches over the lifetime of the application can cause existing features to break which were working at an earlier point in time.have software coding ability, since the test cases are written in the form of source code which, when run, produce output according to the assertions that are a part of it.
Q 4. What are the advantages of the automation testing process ?
Ans:
In order to save test execution time and resource we can automate manual test cases, which save human effort and time as well.
> Automated Software Testing Saves Time and Money
"Every time source code is modified software tests should be repeated. For each release of the software it may be tested on
all supported operating systems and hardware configurations. Manually repeating these tests is costly and time consuming.
Once created, automated tests can be run over and over again at no additional cost and they are much faster than manual tests. Automated software testing can reduce the time to run repetitive tests from days to hours. A time savings that translates directly into cost savings."
.>Vastly Increases Your Test Coverage
"Test automation can easily execute thousands of different complex test cases during every test run providing coverage that is impossible with manual tests."
>Testing Improves Accuracy
"Sometime times a tester will make mistakes during manual testing.
Automated tests perform the same steps precisely every time they are executed and never
forget to record detailed results. Testers freed from repetitive manual tests have more time to create new automated software tests and deal with complex features"
> Automation Does What Manual Testing Cannot
"Even the largest software and QA departments cannot perform a controlled
web application test with thousands of users. Automated testing can simulate tens,
hundreds or thousands of virtual users interacting with a network, software and web applications."
Q 5. What are the disadvantage of the automation testing process?
Ans:-Skill level:
In automated testing the Test Engineer or Software quality assurance person must have software coding ability,since the test cases are written in the form of source code which, when run, produce output according to the assertions that are a part of it.
Tool needed-To write code we need suported tools and jar files.
Failed tests:
The time required to decide which of these reasons actually applies to your failed test.
failed, because of an actual bug. (just for completeness, as this is of course advantageous)
failed, because your test code has been written with a traditional bug.
failed, because your test code has been written for an older version of your product and is no longer
Non-failed tests
If you change something in your product's code, but the test doesn't account for it at all, then it gives you this "false sense of security".compatible
failed, because the requirements have changed and the tested behavior is now deemed 'correct'
>Proficiency is required to write the automation test scripts.
>Debugging the test script is major issue. If any error is present in the test script, sometimes it may lead to deadly consequences.
>Test maintenance is costly in case of playback methods. Even though a minor change occurs in the GUI, the test script has to be rerecorded or replaced by a new test script.
Maintenance of test data files is difficult, if the test script tests more screens.
Q 6. Which version of the selenium have you used?
Ans . Selenium 2 (Selenium WebDriver.)
Q 7 .Why are you using the selenium only?
Ans:-
1. Open source: Selenium is a open source tool available in market that means you no need to pay anything for this to require the licence and it’s freely available.
2. Browser support: Selenium support all the latest browsers like Chrome, MF,IE, Opera
3. Support different tools: Selenium support multiple tools like TestNG, Maven, AutoIt etc. those are also free available into the market.
4. Supporting large community: Many people are working on selenium in market and they have posted many posts regarding any issue in selenium and you can easily get the solution of the selenium related problem. We have many solutions and blogs for selenium.
5. Self API-Selenium WebDriver have own API so you no need to write much code and you just need to use the Interface and class in your code.
6. Mobile automation: Selenium also support mobile automation like Android , iOS.
Q 8. Explain the Selenium limitations?
Ans:-
1. Selenium does not support the Window based/desktop applications. It only supports the web applications.
2. We can’t automate the charts and graphs related test cases through the selenium.
3. We cannot automate the barcode and Capctha code using the selenium.
4. Selenium is open source so there is no official support.
Q 9. What types of the test cases you have automated?
Ans-I have automated the functional test cases including smoke test cases, regression test cases, end to end test cases.
Eg. I have automated the complete search functionality .
We did not automate the login and email and negative test scenarios and windows apps access test cases
Q 10. What type of framework have you designed?
Yes, I have designed the Hybrid and Data Driven framework.
In a software company, every day developers write new code based on the new requirements or bug fixes and then they will compile it to create an executable form. After that a final executable form is produced by a build tool which is 'set of all executable forms' which we called "software build ".
"A build is a executable form of a software which consists of all developed new features as well as few bug fixes and tested until it becomes stable" . It is a pre-release version and can be recognized by a build number.
This build is deployed into testing environment so that the tester can test the developed new functionality or bug fixes. Initial testing carried out on the build, is smoke testing, this done to check the stability I.e whether further testing can be carried out on this build.
Ex. Suppose you want to develop an Gmail application then let's say first, developer will develop the login page feature. We can say that we have developed the 10% portion of the application. Developer will create executable form after compiling the login source code file and then build tool will pick this code and generate the build for test team to test the stability. Next time, developer will develop the Inbox feature then we have next build version having the new feature and bug fixes in the first build. Testing team will again test this build stability. So let's say we have done the 20% portion of the application. This process will go continue till 100%, ie. until final Build is stable.
Implies no bugs or very few bugs and all features have been developed. Which means it is a complete software, which is ready to use. Now this final build is called a software. It is called a Release.
What is String and main string methods used in selenium
Case 1: Case ignore case
in string object:-
String s1="Male";
String s2 ="MALE";
if(s1.equalsIgnoreCase(s2) use;
Case 2: Splitting decimal numbers:-
String s="50.02";
String arr[]=s.split("\\.");
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
Case 3. continue statement
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
Case 4:- Ternary operands and alternate way of the if -else
int a =30,b=40;
System.out.println(a>b?"true" :"false");
Case 5:Character class cases:-
1. Character ch = 'a';
System.err.println(ch); =a
2 Character ch = '1';
System.err.println(ch.isLetter(ch)); =false
3. Character ch = '1';
System.err.println(ch.isDigit(ch));=true
4. Character ch = ' ';
System.err.println(ch.isWhitespace(ch)); ==true
5. Character ch = 'a';
System.err.println(ch.isUpperCase(ch));==false
6. Character ch = 'n';
System.err.println(ch.isLowerCase(ch));==true
7. Character ch = 'n';
System.err.println(ch.toString());==One char string
Case 6:
String s="25.23";
Double d=Double.parseDouble(s);
double dd=d.doubleValue();
double db= 25.23;
if (dd==db)
System.out.println("Equal");
Case 7: String s="25.23";
double d= Double.parseDouble(s);
case 8: List in single line initialze
ArrayList<Integer> al= new ArrayList<Integer>(Arrays.asList(10,20,30,50,60,80));
Go Back
String s1="Male";
String s2 ="MALE";
if(s1.equalsIgnoreCase(s2) use;
Case 2: Splitting decimal numbers:-
String s="50.02";
String arr[]=s.split("\\.");
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
Case 3. continue statement
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
Case 4:- Ternary operands and alternate way of the if -else
int a =30,b=40;
System.out.println(a>b?"true" :"false");
Case 5:Character class cases:-
1. Character ch = 'a';
System.err.println(ch); =a
2 Character ch = '1';
System.err.println(ch.isLetter(ch)); =false
3. Character ch = '1';
System.err.println(ch.isDigit(ch));=true
4. Character ch = ' ';
System.err.println(ch.isWhitespace(ch)); ==true
5. Character ch = 'a';
System.err.println(ch.isUpperCase(ch));==false
6. Character ch = 'n';
System.err.println(ch.isLowerCase(ch));==true
7. Character ch = 'n';
System.err.println(ch.toString());==One char string
Case 6:
String s="25.23";
Double d=Double.parseDouble(s);
double dd=d.doubleValue();
double db= 25.23;
if (dd==db)
System.out.println("Equal");
Case 7: String s="25.23";
double d= Double.parseDouble(s);
case 8: List in single line initialze
ArrayList<Integer> al= new ArrayList<Integer>(Arrays.asList(10,20,30,50,60,80));
Go Back
Main Use of Constructor in Java
Case 1. When a class do not have any constructor then compiler will put default constructor with a super() method as first line in that constructor in case of inheritance to call super class default constructor.
class Test{Test(){
System.out.println("Super default");
}
}
public class Test01 extends Test
{
/*Test01() <-------you can also write default const that compiler does internally
{
super(); <--------------Should be first line in block
}*/
public static void main(String arg[])
{
Test01 tt= new Test01();
}
}
OP- Super default
Case 2: When you define a argument constructor in super class then extending the same class and if you are not define the argument const in sub class then you will get CTE.
class Test{
int a;
Test(int a)
{
this.a=a;
System.out.println("super parameter value:"+this.a);
}
}
public class Test01 extends Test
{ //no argu const
public static void main(String arg[])
{
Test t = new Test(10);
}
}
CTE:- Implicit super constructor Test() is undefined for default constructor. Must define an explicit constructor.
Here, if you are not defining the argument const in sub class then how will you call the super class respective constructor.
Hence, you have to write the argument const in sub class with super(args) as first line as below code:-
class Test{
int a;
Test(int a)
{
this.a=a;
System.out.println("super parameter value:"+this.a);
}
}
public class Test01 extends Test
{
Test01(int aa)
{
super(aa);
}
public static void main(String arg[])
{
Test t = new Test(10);
}
}
OP-super parameter value:10
or
Write default cont in super class explicitly:
code:-
class Test{
int a;
Test()
{
}
Test(int a)
{
this.a=a;
System.out.println("super parameter value:"+this.a);
}
}
public class Test01 extends Test
{
public static void main(String arg[])
{
Test t = new Test(10);
}
}
Case 3:We have define a argument constructor in super class and defined a default const in sub class with super() method as first line then you will get the CTE.
Code:-
class Test{
int a;
Test(int a)
{
this.a=a;
System.out.println("super parameter value:"+this.a);
}
}
public class Test01 extends Test
{
Test01()
{
super();
}
public static void main(String arg[])
{
Test t = new Test(10);
}
}
CTE- The constructor Test() is undefined
Explanation:-Whenever you not define any const in super class then compiler will put by default it. But if you have a argument const in your super class then compiler will not put any default const into same class. In that case if you are writing a default const in your sub class then you will get a compiler time error because default const is not present in super class by default.
To resolve this issue ,write a default const explicitly in super class.
Code:-
class Test{
int a;
Test()
{
}
Test(int a)
{
this.a=a;
System.out.println("super parameter value:"+this.a);
}
}
public class Test01 extends Test
{
Test01()
{
super();
}
public static void main(String arg[])
{
Test t = new Test(10);
}
}
Subscribe to:
Comments (Atom)