Can we Override static methods in java? - NO
If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class
Can we overload static methods? - Yes
We can have two ore more static methods with same name, but differences in input parameters.
what is factory design pattern?
Pattern provides one of the best ways to create an object - We create object without exposing the creation logic to the client and refer to newly created object using a common interface.
https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
how you initialize Page factory object
https://www.seleniumeasy.com/selenium-tutorials/page-factory-pattern-in-selenium-webdriver
what is POM design pattern?
https://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html
is java pure object oriented? - NO
- because it supports primitive data type [Non Object types] like byte,short,int,long,float,double,char,boolean,which are not objects.
- evrything in java is class, except primitive datatypes.still wrapper classess are there..for this reason we can say java is not fully object oriented language
-The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value
-the main difference between two types is that primitive types store actual values but reference type stores handle to object in the heap
-modification on one primitive variable doesn't affect the copy but it does in the case of the reference variable
int i = 20; int j = i; j++; // will not affect i, j will be 21 but i will still be 20
List<String> list = new ArrayList(2);
List<String> copy = list;
copy.add("EUR");
// adding a new element into list, it would be visible to both list and copy
System.out.printf("value of list and copy after modification list: %s, copy: %s %n", list, copy);
staic class :
Static classes are basically a way of grouping classes together in Java. Java doesn't allow you to create top-level static classes; only nested (inner) static classes.
public class CarParts {
public static class Wheel {
public Wheel() {
System.out.println("Wheel created!");
}
}
public CarParts() {
System.out.println("Car Parts object created!");
}
}
wrapper class:
Each Java primitive has a corresponding wrapper:
boolean, byte, short, char, int, long, float, double
Boolean, Byte, Short, Character, Integer, Long, Float, Double
These are all defined in the java.lang package, hence we don't need to import them manually.
Basically, generic classes (Collection Framework)only work with objects and don't support primitives. As a result, if we want to work with them, we have to convert primitive values into wrapper objects.
heap memory vs stack memory:
stack memory is used to store local variables and function call
heap memory is used to store objects in Java
Each Thread in Java has their own stack which can be specified using
If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError:
If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is a lot lesser than the size of heap memory in Java.
ariables stored in stacks are only visible to the owner Thread while objects created in the heap are visible to all thread. In other words, stack memory is kind of private memory of Java Threads while heap memory is shared among all threads.
== vs equals
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //True
Showing posts with label core java. Show all posts
Showing posts with label core java. Show all posts
Thursday, 23 January 2020
Friday, 2 August 2019
Interview qns on final keyword | java
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
2) Java final method
If you make any method as final, you cannot override it.
3)Java final class
If you make any class as final, you cannot extend it.
Q)Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
Q)Can we initialize blank final variable?
Yes, but only in constructor. For example:
Q)static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it. int cube(final int n){ n = n+2; }
Q)Can we declare a constructor final?
No, because constructor is never inherited.
If you make any variable as final, you cannot change the value of final variable(It will be constant).
2) Java final method
If you make any method as final, you cannot override it.
3)Java final class
If you make any class as final, you cannot extend it.
Q)Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
Q)Can we initialize blank final variable?
Yes, but only in constructor. For example:
Q)static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it. int cube(final int n){ n = n+2; }
Q)Can we declare a constructor final?
No, because constructor is never inherited.
Monday, 22 July 2019
Interview Qns - Core java
Output please
public class Test123 {
static {
System.out.println("first static block");
}
static {
System.out.println("Second static block");
}
public static void main(String[] args) {
System.out.println("Main Method");
Test123 t = new Test123();
}
Test123() {
System.out.println("COnstructor");
}
}
Output:
first static block
Second static block
Main Method
COnstructor
Yes, we can write n number of static blocks
Main method executes after static blocks
--------------------------------
Can we write Throwable in Catch block??
public void doNotCatchThrowable() {
try {
// do something
} catch (Throwable t) {
// don't do this!
}
}
Throwable is the superclass of all exceptions and errors. You can use it in a catch clause, but you should never do it!
If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application. Typical examples for that are the OutOfMemoryError or the StackOverflowError. Both are caused by situations that are outside of the control of the application and can’t be handled.
So, better don’t catch a Throwable unless you’re absolutely sure that you’re in an exceptional situation in which you’re able or required to handle an error.
-----------------------------------
The task is to write a program to generate the largest number possible using these digits.
Input : arr[] = {8, 6, 0, 4, 6, 4, 2, 7}
Output : Largest number: 87664420
static int findMaxNum(int arr[])
{
// sort the given array in
// ascending order and then
// traverse into descending
Arrays.sort(arr);
int num = arr[0];
int n = arr.length;
// generate the number
for(int i = n - 1; i >= 0; i--)
{
num = num * 10 + arr[i];
}
return num;
}
--------------------------------------
Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
FileReader thows FileNotFoundException is a subclass of IOException - hence am throwing
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Ex:
ClassNotFoundException,
IOException,
SQLException
Unchecked: are the exceptions that are not checked at compiled time
Ex:
NullPointerException
ArithmeticException,
ArrayStoreException,
ClassCastException
IndexOutofbounds
---------------------------------------
Inheritance - Class casting - Parent to Child and Child to parent
public class Parent {
public void m1() {
System.out.println("parent method");
}
}
public class Child1 extends Parent {
public void m1() {
System.out.println("Child1 method");
}
public static void main(String[] args) {
Parent p = new Parent();
p.m1();
Child1 c = new Child1();
c.m1();
Parent p1 = new Child1();
p1.m1();
Child1 cer = (Child1) p;// RuntimeError : java.lang.ClassCastException:
// javaProg.Parent cannot be cast
// to
// javaProg.Child1
Child1 cerr1 = (Child1) new Parent();// Runtime error :
// java.lang.ClassCastException: javaProg.Parent cannot be
// cast to javaProg.Child1
}
}
output:
parent method
Child1 method
Child1 method
Note - Only Child to parent casting is possible, Rest all Runtime Exception
--------------------------------------------------
Remove duplicates from array
// NOTE : SORTED ARRAY
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n]; // lets use temp array
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1]; // ADD LAST ITEM TO TEMP ARRAY
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
---------------------------------------------------
Input : arr[] = {8, 6, 0, 4, 6, 4, 2, 7}
Output : Largest number: 87664420
static int findMaxNum(int arr[])
{
// sort the given array in
// ascending order and then
// traverse into descending
Arrays.sort(arr);
int num = arr[0];
int n = arr.length;
// generate the number
for(int i = n - 1; i >= 0; i--)
{
num = num * 10 + arr[i];
}
return num;
}
--------------------------------------
Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
FileReader thows FileNotFoundException is a subclass of IOException - hence am throwing
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Ex:
ClassNotFoundException,
IOException,
SQLException
Unchecked: are the exceptions that are not checked at compiled time
Ex:
NullPointerException
ArithmeticException,
ArrayStoreException,
ClassCastException
IndexOutofbounds
---------------------------------------
Inheritance - Class casting - Parent to Child and Child to parent
public class Parent {
public void m1() {
System.out.println("parent method");
}
}
public class Child1 extends Parent {
public void m1() {
System.out.println("Child1 method");
}
public static void main(String[] args) {
Parent p = new Parent();
p.m1();
Child1 c = new Child1();
c.m1();
Parent p1 = new Child1();
p1.m1();
Child1 cer = (Child1) p;// RuntimeError : java.lang.ClassCastException:
// javaProg.Parent cannot be cast
// to
// javaProg.Child1
Child1 cerr1 = (Child1) new Parent();// Runtime error :
// java.lang.ClassCastException: javaProg.Parent cannot be
// cast to javaProg.Child1
}
}
output:
parent method
Child1 method
Child1 method
--------------------------------------------------
Remove duplicates from array
// NOTE : SORTED ARRAY
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n]; // lets use temp array
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1]; // ADD LAST ITEM TO TEMP ARRAY
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
---------------------------------------------------
how to make thread safe
Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is a Java synchronized static method example:
public static synchronized void add(int value){
count += value;
}
Also here the synchronized keyword tells Java that the method is synchronized.
Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.
If the static synchronized methods are located in different classes, then one thread can execute inside the static synchronized methods of each class. One thread per class regardless of which static synchronized method it calls.
Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is a Java synchronized static method example:
public static synchronized void add(int value){
count += value;
}
Also here the synchronized keyword tells Java that the method is synchronized.
Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.
If the static synchronized methods are located in different classes, then one thread can execute inside the static synchronized methods of each class. One thread per class regardless of which static synchronized method it calls.
--------------------------------------
public vs protected
The protected specifier allows access by all subclasses of the class in a program, whatever package they reside in, as well as to other code in the same package. The default specifier allows access by other code in the same package, but not by code that is in subclasses residing in different packages
The protected specifier allows access by all subclasses of the class in a program, whatever package they reside in, as well as to other code in the same package. The default specifier allows access by other code in the same package, but not by code that is in subclasses residing in different packages
----------------------------------------
Guess the out put of below prog
Java System exit() Method
The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.
System.exit(0) or EXIT_SUCCESS; ---> indicates Successful termination
System.exit(1) or EXIT_FAILURE; ---> indicates unsuccessful termination with Exception
System.exit(-1) or EXIT_ERROR; ---> indicates Unsuccessful termination
Guess the out put of below prog
try{
System.exit(-1);
System.out.println("in try");
}
catch(Exception ex){
System.out.println("in Exception block");
}
output : Nothing - as program exits then and there
System.exit(-1);
System.out.println("in try");
}
catch(Exception ex){
System.out.println("in Exception block");
}
output : Nothing - as program exits then and there
Java System exit() Method
The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.
System.exit(0) or EXIT_SUCCESS; ---> indicates Successful termination
System.exit(1) or EXIT_FAILURE; ---> indicates unsuccessful termination with Exception
System.exit(-1) or EXIT_ERROR; ---> indicates Unsuccessful termination
Subscribe to:
Posts (Atom)