package MavenTestNG;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class A3JavaLibrary {
//ctrl space
// tab - to indent
/* Strategies and rules in JAVA;
//second and third line of code will print as single statment as there is no PrintLn
// TODO Auto-generated method stub
//SysOut and click ctrl+space will open the options to get display complete print statement
//type main and click ctrl+space to get display complete main method statement
//click Ctrl+I which will indent code in your program
//select line of code and Ctrl + 7 which will comment the selected code lines
//right click on package/class and selct refactor option to rename the package/class name
//public is access modifier , each class will have first line with package name
//Main method used to execute the program
//void is a return type -if no return type nothing to mention, if any return type then mention as String/Int which will be returned
//static can be called in any class/method
//Compile program and run/execute java code using Run button/ right click -run as Java application
//right click on class -then Run as Java application to see output of code
Type SysOut and click Ctrl+Space to automatically bring the print statement syntax;
System.print("XYZ"); //prints in same line
system.println("ABC); //prints in next line
//Use "//" to comment sigle line AND for multiple lines use as /* text /*
*Declare variable and assign values -then use those variables to print;
static int a =4;
system.println(a);
*Use double quotes to print string values and do not use for variables to be printed;
*void means not retrurn anything as an output;
*If function return expected string or int -then mention String/Int in method as return type;
**STRING: It is one of the in-built class in JAVA;
There are two ways to define strings;
1) String leteral way Eg: String a ="Value of String";
2) by creating object of String class way Eg: String sn = new String("Value of String);
**STRING METHODS:
String st ="JavaTraining";
System.out.println(st.charAt(3));
System.out.println(st.indexOf("T"));
System.out.println(st.substring(4));
System.out.println(st.substring(4, 9));
System.out.println(st.concat("Venkat is learning"));
System.out.println(st.length());
System.out.println(st.toUpperCase());
System.out.println(st.toLowerCase());
System.out.println(st.replace("t", "s"));
String arr[]=st.split("T");
System.out.println(arr[0]);
System.out.println(arr[1]);
***METHODS- these are blocks in java class
Reusability we will use to call in other programs;
Methods should be written outside the main block and call in main block;
Create an object of class in any other class, and reuse those methods,variables,functions;
***IF CONDITION: based condition true or false-then respective block will be executed
If you have single line in statement - then we can remove braces under true/false condition and Java will execute that statement.
if(5>2) //Condition
{
SysOut.pintln(Execute this first statement)
}
else{
SysOut.pintln(Execute this second statement)
}
***FOR LOOP:
for(i=0; i<=10; i=i+2)
{
if(1==8)
SysOut.pintln("8 is displayed");
else
System.Out.println("it is not found");
}
}
***WHILE LOOP SYNTAX:
int k=0; //INCREMENTAL WHILE LOOP
while(k<10)
{
System.out.println("while loop value now is "+ k);//this will print value from 0 to 10 incremental value
k++; //this condition will terminate the loop when it becomes false
}
int m=10;//DECREMENTAL WHILE LOOP
while(m<0)
{
System.out.println("while loop value now is "+ m); //this will print from 10 to 1-decremental value
m--; //this condition will terminate the loop when it becomes false
}
***DO WHILE LOOP- execute block until the condition become false -this will execute at lease once
int n=10;
do {
System.out.println("DO WHILE LOOP value is " + n);
n++;
}
while(n<=30); //Execution will be terminated once n value reaches to 30 as per condition
***NESTED LOOPS: (WITH OUTER AND INNER LOOPS; each outer loop cycle will execute all cycles from inner loop)
for(int x=1; x<=3; x++) //Outer For loop will execute 3 times
{
for(int y=1;y<=4;y++) //Inner for loop will execute 4 times
{
System.out.println("this line is from INNER loop");
}
System.out.println("this is for OUTER loop value");
}
**** NESTED FOR LOOP to PRINT PYRAMID model output:
int r=1;
for(int p=0; p<4; p++) //Outer For loop will execute 3 times
{
for(int q=1;q<=4-p;q++) //Inner for loop will execute 4 times
{
System.out.print(r);
System.out.print("\t"); //this is used to add space after the output value
r++;
}
System.out.println("");
}
System.out.println("Pyramid model printed Descending model");
*****NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output
int c1=1;
for(int a1=1; a1<5; a1++) //Outer For loop will execute 3 times
{
for(int b1=1;b1<=a1;b1++) //Inner for loop will execute 4 times
{
System.out.print(c1);
System.out.print("\t"); //this is used to add space after the output value
c1++;
}
System.out.println("");
}
System.out.println("Pyramid model printed Ascending model");
***BREAKPOINT - double click on the line number will add breakpoint -which will used for execute code in DEBUG mode
STEPINTO-F5 - to execute code step by step
STEPOVER-F6
****INTERFACE METHODS- IMPLEMENTATION IN CLASS
public class AusTrafficSystem implements CentralTraffic {
/* You can use interfaces without body in other class by using syntax as "Implements InterfaceName" (you can mention multiple interfaces using comma seperated)
once you implemented interface, we need to improt the all interface methods to new class
Once all interface methods are loaded in to the target class we can add additional code blocks to those interface methods
We need to create object of interface in target class to execute all blocks -SYNTAX is "interfacename Objname = new Classname();"
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("HELLO ");
CentralTraffic au=new AusTrafficSystem();
au.redStop();
au.flashyello();
au.greenGo();
AusTrafficSystem at = new AusTrafficSystem();
at.walkOnSymbol();
}
public void walkOnSymbol() {
System.out.println("local method");
}
@Override
public void greenGo() {
// TODO Auto-generated method stub
System.out.println("Green");
}
**** ABSTARCTTiON AND ABSTRACT METHOD:
Abstraction - process of hiding implementatio details
Abstract Method is a method defined without body.
Parent class - where child classes are inherited
INTERFACES - all methods in interface are Abstract methods
A class which is declared with abstract keyword called as Abstract class
A class can be called as Abstract class if that has atleast one abstract menthod.
Class may contain both implimentation methods & Non implimentation methods.
Abstract classes achieves partial Abstraction whereas Interfaces achive 100 % abstraction
We can create object for Abstract classes / we cannot instntiate abstract classes.
Abstract methods should be declared as public methods- which they need to be reused. (they should public or protected)
Child classes will be forced to implement abstract class methods
extends keyword used to inheritence of parent class in child class
implements keyword used to implement interface methods.
*****Inheritence in JAVA
Reuse of parent class related methods, properties in other child
classes using inheritance concept:
NOTE: Java will not support/allow multiple inhertitence in single child class.
//Use "extends" keyword for inheritance of parent class, methods, properties in child classes.
public class childClass extends parentClass
{
public void engine() {
System.out.println("new Engine");
}
public void color() {
System.out.println(color); //this color property is being used from parent class which was inhertited
}
public static void main(String[] args) {
childClass cc=new childClass();
cc.color();
cc.engine();
}
}
*****FUNCTIONOVERRIDING /METHOD OVERRIDING:
When both methods(parent class method1, child class method2) are having same method name, signature, arguments and return type-
then java will give prefernce to the local child class method 2 and it will overide the parent class method 1;
This is called functionoverriding.
In Function overloading method arguments/return types different where as in FunctionOverloading arguments and all are same.
****FINCTION OVERLOADING:
If same class is using multiple methods with same method names are called as Function overloading.
Those methods should be differentiated with different arguments
Rules are 1) either argumets count should be different OR 2) arguments data type/return type should be different,else java will throw errors
public class functionOvverloading {
public static void main(String[] args) {
// TODO Auto-generated method stub
functionOvverloading fo = new functionOvverloading();
fo.getdata(3);
fo.getdata("Hello");
fo.getdata(2, 5);
}
public void getdata(int a) {
System.out.println(a); //method 1 has argument return type as int
}
public void getdata(String a) {
System.out.println(a); //method 2 has argument return type as String
}
public void getdata(int a, int b) {
System.out.println(b); //method 3 has multiple arguments than method 1
}
}
*****ARRAYS: A container which stores mutiple values of same data type.
If you want to save multiple values we will use Arrays
new keyword allocates memory which will provide space for 5 values;
declares an array and allocated memory for 5 integers
*** SINGLE DIMENTION ARRAY: SYNTAX int a[index]=value;
*** MULTI DIMENTIONAL ARRAY: SYNTAX int a[row index][column index]={value1, value2}
public class Arrays {
public static void main(String[] args) {
/SINGLE DIMENTION ARRAYS
//1st method of array initialization and assign values to array
int b[]= {10,20,30,40,50,600};
for(int j=0; j<b.length;j++)
{
System.out.println("Single dimentional array 0 value is " + b[j]);
}
//2nd method of array initialization and assign values to array
int a[] = new int[5]; //declares an array a[] and allocated memory for 5 integers
a[0]=2;
a[1]=3;
a[2]=10;
a[3]=14;
a[4]=15;
for(int i=0; i<a.length;i++)
{
System.out.println("Single dimentional array 1 value is " + a[i]);
}
//MULTI DIMENTIONAL ARRAY: int a[row][column]
int p[][] = new int[2][3]; //declares an array a[] and allocated memory for 5 integers
p[0][0]=2;
p[0][1]=3;
p[0][2]=10;
p[1][0]=14;
p[1][1]=15;
p[1][2]=16;
System.out.println("Multi dimentional array 0 value is " + p[1][2]);
for(int i1=0;i1<2;i1++) {
for(int j1=0;j1<3;j1++) {
System.out.println("Multi dimention array content is " + p[i1][j1]);
}
}
int q[][]= {{100,20,30},{40,50,600}};
System.out.println("Multi dimentional array 1 value is " + q[1][0]);
}
}
**** DATE CLASS:
*DATE Class comes from util package which will used to retrive date,Current date, current time, to print date we need to convert o String and then print stmt
import java.text.SimpleDateFormat;
import java.util.Date;
Date dt = new Date();
System.out.println(dt.toString());
//print as Sat Dec 05 12:30:46 AEDT 2020
//Simple date format class
SimpleDateFormat sdf=new SimpleDateFormat("M/dd/yyyy");
System.out.println(sdf.format(dt));
SimpleDateFormat sd=new SimpleDateFormat("M/dd/yyyy hh:mm:ss");
System.out.println(sd.format(dt));
**** CALENDAR CLASS will be used to get the date, time , month details using this date class in java
Calendar cal=Calendar.getInstance();
SimpleDateFormat sdt=new SimpleDateFormat("M/dd/yyyy hh:mm:ss");
System.out.println(sdt.format(cal.getTime()));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.WEEK_OF_MONTH));
System.out.println(cal.get(Calendar.YEAR));
***** CONSTRUCTOR
Constructor will not return any value..it is just like method but not retun any value
Code from constructor will be executed automatically when constructor object is created.
Name of the constructor should be always class name only when you creating constructor in class
Implicit constructor will be called by java when no constuctor OR parameterised constructor defined and instanciated in class
Constructor defined code, vairables and statements will be resued in clss when object of constructor is created
Constructors are 2 types -
1 default constructor OR non-parameterized constructor
2 parameterised constructor with parameters [this will execute when we pass parameters while creating an object of constructor]
Parameterzied constroctors will execute and ignore default constructor when user passed parameters.
public class ConstructorDemo {
//Creating constructor without any return type
public ConstructorDemo()
{
int a =100;
System.out.println("I am in the default constructor method stmt");
System.out.println("Value of from default constructor is " +a);
}
//Creating method with return type
public void getData()
{
System.out.println("I am in generic method statement");
}
public ConstructorDemo(int a, int b)
{
System.out.println("I am in the parameterised constructor");
}
public static void main(String[] args) {
ConstructorDemo cd=new ConstructorDemo(); //Instantiating non parameterized/default costructor
ConstructorDemo cd1=new ConstructorDemo(5,6);//Instantiating parameterized/user created costructor
}
//PARAMETERISED CONSTRUCTOR (default one)
}
**** SUPER KEYWORD-
this super keyword will be used to refer the variables from the parent class
When the same same method or same variables declared in child and parents class
When we use super constructor in child class-It should be in the first line of child class
SYNTAX- super(); //super keyword with constructors
SYNTAX- super.name; //super keyword with variables
SYNTAX- super(); //super keyword with methods
static String name = "Steven Academy";
public void engine() {
super();
System.out.println("new Engine");
System.out.println(name); //this will refer to the local child class declared variable and print
System.out.println(super.name); //Super keyword will refer to parent class and refers from the parent class
super.getData(); // this method will call from parent class
}
***** THIS KEYWORD
If same name of local and global variable is used in class and if we need to use the global varaible value- then java allows to use
THIS.variable name which will refer to the global level declared variable.
this KEYWORD will refers/ties to the class level objects/global level variables
String city = "Delhi"; Global/class level variable
String city ="Chennai" Local method level variable
System.out.println(city); //statement output will be Chennai
System.out.println(this.city);//statement output will be Delhi
*****STATIC KEYWORD
//static keyword will allows to share this keyword across class as class variables and it can be updated by other methods
//static will save memory
//static method will be uses/accepts only static variables
//static methods can be called in class without creating oblects- SYNTAX- className.staticMethodName
//Static block is which can be defined with all static variables, so this block created variables can be used in all static methods.
EG: static String city='Hyd';
public static void getCity()
{
System.out.println(state); //this will thorow error to make if non static address variable
}
**** FINAL KEYWORD
IF class name as final, then we can not extend the class
If the variable declared as final variable -then we can not change the variable value
If the method is declared as final method, we can not override the method again.
EG: final void finalMethod() //this final method can not be override in other child classes due to final KEYWORD
{
final int i1=90; //this i1 variable value can not be changed as final keyword used before the variable declaraton.
System.out.println(i1);
}
******* PACKAGES- TYPES of Packages:
Package is set of classes and interfaces
1] java.lang -default java inbuilt package come from compiler
2] java.util - this package have collections, classes & interfaces
3] java.io - file reading and file output
user defined package- will list on top of the class
Class A can use Class B directly if both classes are in the same package.
If class A is in package 1 and you want to use Class a is in package2, then we need to import the class from package1.
SYNTAX- import.package.classname
**** ACCESS MODIFIERS/ SPCIFIERS in JAVA:
1 Default-If not mentioned for methods/variables, then java will treat default modifier and
allows everywhere in that package alone:
2 public -If method/variables eclared as public- they can access in anywhere in same/other package
3 private -If method/variables eclared as private- they can't access outside of the class
4 protected -If method/variables eclared as protected those will be accessed in all the classes of same package.
then only child classes which are inherited are able to use those methods/variable.
DEFAULT + other packages-child class which are inherited using extends keyword.
**** EXCEPTIONS in JAVA [TRY ,CATCH, FINALLY blocks]
We use Try-Catch blocks to handle java exveptions and see those error messages
One TRY can be followed by multiple catch blocks in script
CATCH should be an immediate Try block.
Exception is the parent class used for all kind of exceptions in Catch block:
FINALLY block will be execute block of code-when execution fails in midle or PASS, then this block will be executed always, Finally should have atleast 1 try block
public static void main(String[] args){
int a =8;
int b=0;
try{
int k=b/a;
System.out.println(k);
}
Catch(exception e){
System.out.println(e);
}
Catch(indexOutOfBoundsException ets){
System.out.println(ets);
}
Catch(ArithmeticException et){
System.out.println(et);
}
finally{
System.out.println("this is finally block code");
//to delete cookies, close browser cam be used in finally block;
}
*****ARRAYLIST INTERFACE
//ArrayList has dynamic size to add records where Array have fixed size
//ArraList class have multiple methods to add,remove records and print records based on index or text -contains methods etc
//ArrayList, LinkedList, Vector will accept duplicate values
//You can access, insert,remove any value in any index using Array List methods below
ArrayList<String> ar=new ArrayList<String>();
ar.add("venkat");
ar.add("java");
ar.add("testing");
ar.add("testing1");
System.out.println(ar);
ar.add(0, "Rajkumar");//to add reord to Array List
System.out.println(ar);
ar.remove(1); //to remove record from Array List
System.out.println("ArrayList output is " + ar);
System.out.println("ArrayList value at index 0 position is " + ar.get(0));
System.out.println("ArrayList output based on contains method is " + ar.contains("testing")); //contains method returns true or flase
System.out.println("ArrayList output based on value is " + ar.indexOf("testing"));
System.out.println("ArrayList is empty or not? is " + ar.isEmpty());
System.out.println("Size of ArrayList is " + ar.size());
System.out.println(ar.contains("testing"));
}
******HASH SET INTERFACE:
// HashSet treeSet, LinkedHashSet implements SET Interface
//These Set will not accept duplicate values, where list will accept duplicate values
//There is no guarantee where elements are added in sequence order-they will store randomly.
public static void main(String[] args) {
HashSet<String> hs=new HashSet<String>();
hs.add("Venkatesh");
hs.add("UK");
hs.add("USA");
hs.add("USA2");
hs.add("USA3");
hs.add("USA4");
hs.add("India");
System.out.println(hs);
hs.add("India");//this duplicate value will just ignored and will not add to hashList
System.out.println(hs);
System.out.println(hs.remove("India"));
System.out.println(hs.isEmpty());
System.out.println(hs.size());
System.out.println(hs);
System.out.println("========================");
Iterator<String> it=hs.iterator();
//System.out.println(it.next()); //This stmt will execute the next record from the HashSet records.
while(it.hasNext())
{
System.out.println(it.next());
}
}
*********JAVA STREAMS ver8 Compatible:
=====================================================================================================================
JAVA STREAMS avaialble from Java version 8 onwards to optimize the code efficently to perform aggregate opertaions over SETS/LIST/ARRAY LISTS
Stream will perform action parallellay using Lambda Expression(new arrow operator "->")
Strems will not change the data source;
We can create a stream API directly and apply filter conditon, terminal operation; without converting from list to Stream
Stream.of("Adam","Anan","Ankit","Keshav","Ram","Raj")
If action is more than one line- then we should write code in {}
forEach- to get item based on for each condition;
limit(1)- this will limit results to single;
MAP method--> to modify results in uppercase, lowercase for filtered results.
For SORTED output results we will use ArrayList, streams to arraylist conversion -then print required index
Array to ArraList conversion [ Arrays.asList()]
sorted method - to get results in sort ASC order
Match/anyMatch method-to find matched records
Collect method- to collect results and covert into List
(.collect(Collectors.toList()); //to print required sorted/limited/required output only
DISTINCT method - to filter records which are unique ones
WEBTABLE- SORTING-
1click sort,
2capture all webelements into Original List
3grab text of webelements in to new list
4apply sort from the result in sorted list.
5compare original and sorted list
Scan the column/attribute using getText X and print X,
WEBTABLE-PAGINATION Handling:(when multiple page exist)
STEPS TO WORK WITH JAVA STREAMS:
1.Create a java stream
assign/Convert ArryList/set to Java Streams
with filter(condition);
Lamda Expression filter(parameter -> action)(s->s,startsWith("A"));
2.Perform Intermediate stream operation (filtered stream) [filtered data]
Intermediate streal life will be based on final stream(termination operation)
Data type should be as "Long"
3.Perform Termination stream operation [action on filtered data]
********* WEB PAGE FILTER RESULTS VALIDATION USING JAVA STREAMS
public class filter {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://rahulshettyacademy.com/greenkart/#/offers");
driver.findElement(By.id("search-field")).sendKeys("Rice");
List<WebElement> veggies=driver.findElements(By.xpath("//tr/td[1]"));
//1 results
List<WebElement> filteredList= veggies.stream().filter(veggie->veggie.getText().contains("Rice")).
collect(Collectors.toList());
//1 result
Assert.assertEquals(veggies.size(), filteredList.size());
}
}
=====================================================================================================================
******HASHMAP EXAMPLE:
public class HashMapExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Integer, String> hm=new HashMap<Integer, String>();
hm.put(0, "Hello");
hm.put(1, "Venkatesh");
hm.put(2, "Java");
hm.put(3, "Morning");
System.out.println(hm);
System.out.println(hm.get(2));
//hm.remove(3);
System.out.println(hm);
//Convert Hash Table to Set collections and Print those key-pair values;
Set sn=hm.entrySet();
Iterator it=sn.iterator();
while(it.hasNext())
{
System.out.println(it.next());
Map.Entry mp=(Map.Entry)it.next();
System.out.println(mp.getKey());
System.out.println(mp.getValue());
}
}
*****HASHTABLE EXAMPLE
DIFFERENCE BETWEEN HASHMAP and HASHTABLE
Hashmap -not have synchronization, multiple prog can access at a time, not synchronized
Hashmap allows null values,
Hashmap.put(3,"");
Hashmap.put(3,"null");
Hashmap values can be iterated using iterator interface
Hashtable - has Synchronization, multiple prog can not access at a time, one by one access
Hashtable not allows null values
Hashtable cannot support iterator interface.. need other enumerator
===========================EXAMPLE CODES==================================
public class Interview {
//FIND MINIMUM VALUE FROM THE GIVEN MULTI DIM ARRAY
public static void main(String[] args) {
// TODO Auto-generated method stub
int abc[][]= {{1,2,3},{4,5,6},{6,7,8}};
int min=abc[0][0];
for(int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
if(abc[i][j]<min)
{
min=(abc[i][j]);
}
}
}
System.out.println("Minimum value from the given array is " + min);
}
}
*/
public static void main(String[] args) {
int myInt = 10;
String text = "Hello";
String blank = " ";
String name = "Venkatesham";
double myDouble = 9.59;
System.out.println("My Number is "+ myDouble + ".");
String greeting = text + blank + name;
System.out.println(greeting);
System.out.println(text);
System.out.println(myInt);
//STRINGS and STRING METHODS
/*String st ="JavaTraining";
System.out.println(st.charAt(3));
System.out.println(st.indexOf("T"));
System.out.println(st.substring(4));
System.out.println(st.substring(4, 9));
System.out.println(st.concat("Venkat is learning"));
System.out.println(st.length());
System.out.println(st.toUpperCase());
System.out.println(st.toLowerCase());
String arr[]=st.split("T");
System.out.println(arr[0]);
System.out.println(arr[1]);
*/
//Print the STRING IN REVERSE -POLYNDRUM
String st1 = "MADAM";
String st0 = "" ;
//FOR LOOP
for(int i=st1.length()-1; i>=0; i--)
{
st0 = st0 + st1.charAt(i);
}
System.out.println(st1);
System.out.println(st0);
if(st1==st0)
System.out.println("This is polyndrum");
else
{
System.out.println("This is not a Polyndrum");
}
for(int j=0; j<=10; j=j+2)
{
if(j==8)
System.out.println("8 is displayed");
else
System.out.println("it is not found");
}
//WHILE LOOP
int k=0;
while(k<10)
{
System.out.println("while loop value now is "+ k);//this will print value from 0 to 10 incremental value
k++; //this condition will terminate the loop when it becomes false
}
int m=10;
while(m<0)
{
System.out.println("while loop value now is "+ m); //this will print from 10 to 1-decremental value
m--; //this condition will terminate the loop when it becomes false
}
//DO WHILE LOOP
int n=10;
do {
System.out.println("DO WHILE LOOP value is " + n);
n++;
}
while(n<=30); //Execution will be terminated once n value reaches to 30 as per condition
//NESTED FOR LOOP with Outer and Inner for loops
for(int x=1; x<=3; x++) //Outer For loop will execute 3 times
{
for(int y=1;y<=4;y++) //Inner for loop will execute 4 times
{
System.out.println("this line is from INNER loop");
}
System.out.println("this is for OUTER loop value");
}
//NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output
int r=1;
for(int p=0; p<4; p++) //Outer For loop will execute 3 times
{
for(int q=1;q<=4-p;q++) //Inner for loop will execute 4 times
{
System.out.print(r);
System.out.print("\t"); //this is used to add space after the output value
r++;
}
System.out.println("");
}
System.out.println("Pyramid model printed Descending model");
//NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output
int c1=1;
for(int a1=1; a1<5; a1++) //Outer For loop will execute 3 times
{
for(int b1=1;b1<=a1;b1++) //Inner for loop will execute 4 times
{
System.out.print(c1);
System.out.print("\t"); //this is used to add space after the output value
c1++;
}
System.out.println("");
}
System.out.println("Pyramid model printed Ascending model");
//NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output
for(int a2=1; a2<5; a2++) //Outer For loop will execute 3 times
{
for(int b2=1;b2<=a2;b2++) //Inner for loop will execute 4 times
{
System.out.print(b2);
System.out.print("\t"); //this is used to add space after the output value
}
System.out.println("");
}
System.out.println("Pyramid model printed Ascending model");
}
}
/* ******OOPS Interview questions
What are the core concepts of OOPS?
OOPS core concepts are;
Abstraction
Encapsulation
Polymorphism
Inheritance
Composition
Association
Aggregation
What is Abstraction?
Abstraction is an OOPS concept to construct the structure of the real world objects. During this construction only the general states and behaviors are taken and more specific states and behaviors are left aside for the implementers.
What is Encapsulation?
Encapsulation is an OOPS concept to create and define the permissions and restrictions of an object and its member variables and methods. A very simple example to explain the concept is to make the member variables of a class private and providing public getter and setter methods. Java provides four types of access level modifiers: public, protected, no modifier and private.
What is the difference between Abstraction and Encapsulation?
�Program to interfaces, not implementations� is the principle for Abstraction and �Encapsulate what varies� is the OO principle for Encapsulation.
Abstraction provides a general structure of a class and leaves the details for the implementers. Encapsulation is to create and define the permissions and restrictions of an object and its member variables and methods.
Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using four types of access level modifiers: public, protected, no modifier and private.
What is Polymorphism?
Polymorphism is the occurrence of something in various forms. Java supports various forms of polymorphism like polymorphic reference variables, polymorphic method, polymorphic return types and polymorphic argument types.
What is Inheritance?
A subclass can inherit the states and behaviors of it�s super class is known as inheritance.
What is multiple inheritance?
A child class inheriting states and behaviors from multiple parent classes is known as multiple inheritance.
What is the diamond problem in inheritance?
In case of multiple inheritance, suppose class A has two subclasses B and C, and a class D has two super classes B and C.If a method present in A is overridden by both B and C but not by D then from which class D will inherit that method B or C? This problem is known as diamond problem.
Why Java does not support multiple inheritance?
Java was designed to be a simple language and multiple inheritance introduces complexities like diamond problem. Inheriting states or behaviors from two different type of classes is a case which in reality very rare and it can be achieved easily through an object association.
What is Static Binding and Dynamic Binding?
Static or early binding is resolved at compile time. Method overloading is an example of static binding.
Dynamic or late or virtual binding is resolved at run time. Method overriding is an example of dynamic binding.
What is a Class?
A class is the specification or template of an object.
What is an Object?
Object is instance of class.
What is Runtime Polymorphism?
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a super class. The
What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.
What is abstract class?
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final method.
Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
What is interface?
Interface is a blueprint of a class that have static constants and abstract methods.It can be used to achieve fully abstraction and multiple inheritance.
Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract keywords can't be used together.
Can an Interface be final?
No, because its implementation is provided by another class.
What is marker interface?
An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc.
What is difference between abstract class and interface?
Abstract class Interface
1)An abstract class can have method body (non-abstract methods). Interface have only abstract methods.
2)An abstract class can have instance variables. An interface cannot have instance variables.
3)An abstract class can have constructor. Interface cannot have constructor.
4)An abstract class can have static methods. Interface cannot have static methods.
5)You can extends one abstract class. You can implement multiple interfaces.
Can we define private and protected modifiers for variables in interfaces?
No, they are implicitly public.
When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the object implements the referenced interface.
*/
No comments:
Post a Comment