Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Get ReadyWithJava

The document discusses various Java programming concepts including polymorphism, method overriding, exception handling, and the differences between data structures like String, StringBuffer, and StringBuilder. It also covers Java 8 features such as Streams and Lambda expressions, as well as Spring framework concepts like bean scopes and the Singleton design pattern. Additionally, it touches on SQL queries and design patterns, providing examples and explanations for each topic.

Uploaded by

saloni.kohli.ab
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Get ReadyWithJava

The document discusses various Java programming concepts including polymorphism, method overriding, exception handling, and the differences between data structures like String, StringBuffer, and StringBuilder. It also covers Java 8 features such as Streams and Lambda expressions, as well as Spring framework concepts like bean scopes and the Singleton design pattern. Additionally, it touches on SQL queries and design patterns, providing examples and explanations for each topic.

Uploaded by

saloni.kohli.ab
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 29

oops

7)Where you have used polymorphism in your project

class Child extends Parent{

String name="Child";
}
class Parent{

String name="Parent";
}

parent p =new child();


System.out.println("Hello World"+p.name); //what will be output
16.Animal class and Cat class variable overriding and method overriding.
Follow up: if method are static
Diff ClassNotFoundException vs NoClassDefFoundError?

25.Difference between String, StringBuffer and StringBuilder?


Convert List/Set to Concatenated String with Delimiter in Java8 String

Java Streams to Concatenate String


1. List<String> fruits= new ArrayList<>();
2. fruits.add("mango"); fruits.add ("apple");
3. for(String str:fruits){

4. fruits.add("banana");
5.sysout(fruits.size);

6.}
why variables must be effectively final/final in java lambda

There are four kinds of method references:


Reference to a static method
Reference to an instance method of a particular object
Reference to an instance method of an arbitrary object of a particular
type
Reference to a constructor

List<Employee>
Employee-> name, salary
https://www.sitesbay.com/java/java-polymorphism

Parent

ClassNotFoundException is a runtime exception that is thrown when an


application tries to load a class at runtime using the Class.forName() or
loadClass() or findSystemClass() methods ,and the class with specified name are
not found in the classpath.

NoClassDefFoundError is an error that is thrown when the Java Runtime System


tries to load the definition of a class, and that class definition is no longer
available
When you compile the above program, two .class files will be generated. One is
A.class and another one is B.class. If you remove the A.class file and run the
B.class file, Java Runtime System will throw NoClassDefFoundError like below:

Using Java 8 String.join


Since Java 8, the String has new method – called as join.

List<String> words = Arrays.asList("Convert", "List", "of", "Strings", "To",


"String");
String output = String.join(",", words);
System.out.println(output);
.collect(Collectors.joining(","));
List<Integer> intList = Arrays.asList(1, 2, 3);
String result = intList.stream()
.map(n -> String.valueOf(n))
.collect(Collectors.joining("-", "{", "}"));
Lambdas can interact with variables defined outside the body of the lambda
Using these variables is called variable capture
These variables must be effectively final.

Types :
Local Variable Capture
Static Variable Capture

The restriction to effectively final variables prohibits access to dynamically-


changing local variables, whose capture would likely introduce concurrency
problems. To lower risk of bugs, they decided to ensure captured variables are
never mutated. From a lambda, you can't get a reference to anything that isn't
final

HashMap <key: name, value: salary>

int countNoOfWords (Strint countNoOfWords (String string) { int count =0; char ch [] =new char(string
new obj()-- no obj found.(noclassdeffound)
New instance()-- no object.. Classnot found

I/P
List<String> fruits= new ArrayList<>();
fruits.add("mango");

fruits.add("apple"); fruits.add("banana");

O/P
String result="mango+apple+banana"
ng) { int count =0; char ch [] =new char(string.length); for(int i=0; i<string.length();i++){ch[i]=string.charAt(i
+){ch[i]=string.charAt(i); if((i>0) && (ch[i]=' ') || ((ch[0]!=' ' && i==0)) ) count++; } return count; }ing string) {
turn count; }ing string) { int count =0; char ch [] =new char(string.length); for(int i=0; i<string.length();i++){c
i<string.length();i++){ch[i]=string.charAt(i); if((i>0) && (ch[i]=' ') || ((ch[0]!=' ' && i==0)) ) count++; } return
=0)) ) count++; } return count; }
This is a simple java program java is cool

this 1
is 2
a 1
simple 1
java 2
cool 1
ques

Internal working of arraylist


How the size of ArrayList grows dynamically?

system.arraycopy vs arrays.copyof
5. Follow up question, We have one object named e1 with property called Name. initalize the obj with
name “ABC”, 20. We have added that object into HashMap (map.put(e1,”value”)), now we change the
value of name from “ABC” to “MNO” by e1.setName() and try to get the value by map.get(e1). Will it
give “value” or null ?

Employee e1= new Employee();


e1.setName("ABC");

Map<Employee,String> map= new HashMap();


map.put(e1,"first");

e1.setName("IRIS");

Sysout(map.get(e1));
hashCode() equals ()is implemnted based on propety name
4. Suppose we have Student class with properties “name” & “age” and we have implemented only
hashCode() but not equals() methods. Now we created two objects s1, s2 with same property value
“RAM”, 20 respectively.
When we add them into HashMap then what will be the size of map?

Employee e1= new Employee();


Employee e2= new Employee();
e1.setName("ABC");
e2.setName("ABC");
Map<Employee,String> map= new HashMap();
map.put(e1,"first");
map.put(e2,"second");

Sysout(map.size());
hashCode() is implemnted based on propety name

Hash collision
24.When ConcurrentModificationException Occurred and how to avoid that?
class Employee {
int number;
String name;

int hashcode(){
return 1; }

public boolean equals(Object obj){


return false;
}

}
public class Main
{
public static void main(String[] args) {
Employee emp = new Employee(1,"abc");
Employee emp2 = new Employee(1,"abc");

HashMap<Employee,String> map = new HashMap<Employee,String>();


map.put(emp,"a");
map.put(emp2,"a");
System.out.println(map.size());
}
ANS

Arrays.copyOf() method is used to copy the collection to the array.


NullPointerException is thrown if the collection that passed into the constructor is null.

The difference is that Arrays.copyOf does not only copy elements, it also creates a new array. System.arraycopy
copies into an existing array.
it uses System.arraycopy internally to fill up the new array:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}

null as hashCode() is implemnted based on propety name so when externally objects name property is changed it
cannot retreive it example below:-package com.java.hashcodeimpl;
size will be 2 since based on equals comparison both objects will be different
Linked list will be created

returning same hash code

1. List<String> fruits= new ArrayList<>();


2. fruits.add("mango"); fruits.add ("apple");
3. for(String str:fruits){

4. fruits.add("banana");
5.sysout(fruits.size);

6.}
2

map.put(emp,"a");
map.put(emp2,"a");
map.put(emp2,"c");

2
TYPE

Arraylist

Arraylist

hashmap
hashmap

concurrentModificationException @ line no 3
6.ConcurrentHashMap ? internal implementation
No need to put any lock when getting the element from ConcurrentHashMap.
remove (Object key) going to remove an element from a
Segment, we need a lock on the that Segment.
7.Follow up question – we have 2 threads t1, t2, one is reading and other is updating
the same ConcurrentHashMap, now how you will make sure that reader thread must
get updated value?

how CHM grow if size is full


The table inside ConcurrentHashMap is divided among Segments (which extends Reentrant Lock)

reenterent lock & syncronized


volatile
producer consumer
https://dzone.com/articles/how-concurrenthashmap-works-internally-in-java

gments (which extends Reentrant Lock),


web service
SOAP vs Rest
different type of request get put post delete
fetch :atomicity (get+put)
8)Scopes of bean in spring, Difference between sigleton and prototype scopes in spring.

9.Singleton pattern ? in what scenario you will use singleton ?


2.Bean factory and Application context difference

3. Followup:Where you will use Bean factory. Give an example?

scoped bean injection problem.?

4.Prototype reference inside singleton. who creates singleton and lifecycle


<bean id="a" class="A" scope="singleton">
<property name="b" ref="b"/>
</bean>

<bean id="b" class="B" scope="prototype"/>


getA().getB()

7.Java singleton design pattern and spring singleton

8.what will happen when i call get bean when two beans with same type but different id
primary annotation
post and put
Singleton Bean will have one instance throughout application and Prototype bean will have
new instance in each request

Bean Factory

>Bean instantiation/wiring

Application Context
>Bean instantiation/wiring
>Automatic BeanPostProcessor registration
>Automatic BeanFactoryPostProcessor registration
>Convenient MessageSource access (for i18n)
>ApplicationEvent publication
> Internationalization using MessageSources
The ApplicationContext interface extends an interface called MessageSource,

it is generally recommended that it be used in preference to the BeanFactory, except for a


few limited situations such as in an Applet, where memory consumption might be critical
and a few extra kilobytes might make a difference

no new instance of prototype bean is created. Every time the same instance which is
created at the start-up is returned.
Solution:
>application context: Instead of Autowired, we used BeanUtil class to load prototype bean
in API method.
>Lookup :@Lookup tells Spring to return an instance of the method’s return type when we
invoke it.
>By setting the proxy mode to ScopedProxyMode.TARGET_CLASS, Spring will create a new
instance of the prototype whenever you call its method.

Java considers something a singleton if it cannot create more than one instance of that
class within a given class loader, whereas Spring would consider something a singleton if it
cannot create more than one instance of a class within a given container/context.
9)You have two tables employee and organisation, in select e.count(*), o.departName from
employee you have orgId and employee detail and in Employee e inner join organisation on
organisation you have organisation detail e.deptID=o.deptID and o.deprtName = 'HR'
and department (Hr, Account, IT). Count the number group by deprtName
of employees in Hr department

transient keyword?

sequence generator statergy


12.Write a query to find employee having duplicates SELECT name as Name,
name, explude employees with unique name COUNT(name) AS DublicateCount FROM
Employee GROUP BY name
HAVING COUNT(name) > 1

17. Write query for History Table(Comments id, time, SELECT * FROM History t1 WHERE Date
comments) Comments id can have duplicate id’s, time IN (SELECT Date FROM History AS T2
is incrementing, comments can be duplicate Find last WHERE T2.ID = t1.ID
10 rows for all the Comments id’s ORDER BY Date DESC LIMIT
10)

[2:46 PM] Pritam Shirbhate (Guest)


Select Name,
Case when Gender='Male' then 'M'
when Gender='Female' then 'F'
end
​[2:47 PM] Pritam Shirbhate (Guest)
from employee;

update employee setgender=(case when gender='F' the

update employee e set gender =


decode(gender, 'M', 'F', 'M') ;

UPDATE EMP SET GENDER =


DECODE(GENDER,'M','F','F'.'M',NULL);
ename count

RAM 4

Ayesha 3
IRIS 1

pepsi--> for each country, year new licence--> get latest licence no of each c Pepsi Country licence no
in LNC001
r=(case when gender='F' then 'M' elseif 'M' then 'F') in LNC006
br LNC008

ename Gender br LNC009


RAM F br LNC011

Sakshi M us LNC016
Shiva F us LNC017
Ayesha M
year country licence no year java streams
2019 in LNC006 2020
2020 br LNC011 2021
2018 us LNC017 2019

2020
2021

2018
2019
design pattern 32 type

creational singleton protoype factory builder


behavioural visitor
builder: limited mount of attribute of object
basic info lik ename n contact and email
by default thease field.

send a visitor

You might also like