Accenture Interview Qustion Ans Answer
Accenture Interview Qustion Ans Answer
class Main
{
// This function prints the first repeated
// character in str[]
static char firstRepeating(char str[])
{
// Creates an empty hashset
HashSet<Character> h = new HashSet<>();
return '\0';
}
Output:
e
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "geeksforgeeks";
getOccuringChar(str);
}
}
Output:
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1
Ans-ArrayList:-
LinkedList:-
Ans-Comparable interface: Class whose objects to be sorted must implement this interface.In
this,we have to implement compareTo(Object) method.
For example:
1 public class Country implements Comparable{
2 @Override
3 public int compareTo(Object arg0) {
4 Country country=(Country) arg0;
5 return (this.countryId < country.countryId ) ? -1: (this.countryId > country.co
}}
6
If any class implements comparable inteface then collection of that object can be sorted
automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of
compareTo method in that class.
Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap
or SortedSet like TreeSet without implementing any other interface.
Comparator interface: Class whose objects to be sorted do not need to implement this
interface.Some third class can implement this interface to sort.e.g.CountrySortByIdComparator
class can implement Comparator interface to sort collection of country object by id. For
example:
1 public class CountrySortByIdComparator implements Comparator<Country>{
2
3 @Override
4 public int compare(Country country1, Country country2) {
5
6 return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.get
7 }
8
}
9
Using Comparator interface,we can write different sorting based on different attributes of objects
to be sorted.You can use anonymous comparator to compare at particular line of code. For
example:
01 Country indiaCountry=new Country(1, 'India');
02 Country chinaCountry=new Country(4, 'China');
03 Country nepalCountry=new Country(3, 'Nepal');
Country bhutanCountry=new Country(2, 'Bhutan');
04
05 List<Country> listOfCountries = new ArrayList<Country>();
06 listOfCountries.add(indiaCountry);
07 listOfCountries.add(chinaCountry);
08 listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
09
10 //Sort by countryName
11
12 Collections.sort(listOfCountries,new Comparator<Country>() {
13
14 @Override
15 public int compare(Country o1, Country o2) {
16
17 return o1.getCountryName().compareTo(o2.getCountryName());
}
18 });
19
20
21
Comparator vs Comparable
Parameter Comparable Comparator
Sorting logic Sorting logic must be in same class whose objects are being sorted. Hence this is Sorting logic is in separate class. Hence we
called natural ordering of objects can write different sorting based on different
attributes of objects to be sorted. E.g. Sorting
using id,name etc.
Implementation Class whose objects to be sorted must implement this interface.e.g Country class Class whose objects to be sorted do not
needs to implement comparable to collection of country object by id need to implement this interface.Some other
class can implement this interface. E.g.-
CountrySortByIdComparator class can
implement Comparator interface to sort
collection of country object by id
int compareTo(Object o1) int compare(Object o1,Object o2)
Sorting method This method compares this object with o1 object and returns a integer.Its value has This method compares o1 and o2 objects.
following meaning and returns a integer.Its value has following
1. positive – this object is greater than o1 meaning.
2. zero – this object equals to o1 1. positive – o1 is greater than o2
3. negative – this object is less than o1 2. zero – o1 equals to o2
3. negative – o1 is less than o1
Calling method Collections.sort(List) Collections.sort(List, Comparator)
Here objects will be sorted on the basis of CompareTo method Here objects will be sorted on the basis of
Compare method in Comparator
Package Java.lang.Comparable
Java.util.Comparator
Java code:
For Comparable: We will create class country having attribute id and name.This class will
implement Comparable interface and implement CompareTo method to sort collection of
country object by id.
1. Country.java
01
02
03
package org.arpit.javapostsforlearning;
04 //If this.cuntryId < country.countryId:then compare method will return -1
05 //If this.countryId > country.countryId:then compare method will return 1
06 //If this.countryId==country.countryId:then compare method will return 0
07 public class Country implements Comparable{
int countryId;
08
String countryName;
09
10 public Country(int countryId, String countryName) {
11 super();
12 this.countryId = countryId;
13 this.countryName = countryName;
}
14
15 @Override
16 public int compareTo(Object arg0) {
17 Country country=(Country) arg0;
18 return (this.countryId < country.countryId ) ? -1: (this.countryId > country.c
19 }
20
public int getCountryId() {
21 return countryId;
22 }
23
24 public void setCountryId(int countryId) {
25 this.countryId = countryId;
}
26
27 public String getCountryName() {
28 return countryName;
29 }
30
31 public void setCountryName(String countryName) {
32 this.countryName = countryName;
}
33
34 }
35
36
37
2.ComparatorMain.java
package org.arpit.javapostsforlearning;
01
02 import java.util.ArrayList;
03 import java.util.Collections;
04 import java.util.List;
05
06 public class ComparatorMain {
07
/**
08 * @author Arpit Mandliya
09 */
public static void main(String[] args) {
10 Country indiaCountry=new Country(1, 'India');
11 Country chinaCountry=new Country(4, 'China');
12 Country nepalCountry=new Country(3, 'Nepal');
13 Country bhutanCountry=new Country(2, 'Bhutan');
14
List<Country> listOfCountries = new ArrayList<Country>();
15 listOfCountries.add(indiaCountry);
16 listOfCountries.add(chinaCountry);
17 listOfCountries.add(nepalCountry);
18 listOfCountries.add(bhutanCountry);
19
20 System.out.println('Before Sort : ');
for (int i = 0; i < listOfCountries.size(); i++) {
21 Country country=(Country) listOfCountries.get(i);
22 System.out.println('Country Id: '+country.getCountryId()+'||'+'Countr
23 }
24 Collections.sort(listOfCountries);
25
System.out.println('After Sort : ');
26 for (int i = 0; i < listOfCountries.size(); i++) {
27 Country country=(Country) listOfCountries.get(i);
28 System.out.println('Country Id: '+country.getCountryId()+'|| '+'Count
29 }
30 }
31
}
32
33
34
35
36
37
38
Output:
01
02 Before Sort :
Country Id: 1||Country name: India
03 Country Id: 4||Country name: China
04 Country Id: 3||Country name: Nepal
05 Country Id: 2||Country name: Bhutan
06 After Sort :
07 Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
08 Country Id: 3|| Country name: Nepal
09 Country Id: 4|| Country name: China
10
For Comparator: We will create class country having attribute id and name and will create
another class CountrySortByIdComparator which will implement Comparator interface and
implement compare method to sort collection of country object by id and we will also see how to
use anonymous comparator.
1.Country.java
01
02
03 package org.arpit.javapostsforlearning;
04
public class Country{
05
int countryId;
06 String countryName;
07
08 public Country(int countryId, String countryName) {
09 super();
10 this.countryId = countryId;
this.countryName = countryName;
11 }
12
13 public int getCountryId() {
14 return countryId;
15 }
16
17 public void setCountryId(int countryId) {
this.countryId = countryId;
18 }
19
20 public String getCountryName() {
21 return countryName;
22 }
23
public void setCountryName(String countryName) {
24 this.countryName = countryName;
25 }
26
27 }
28
29
2.CountrySortbyIdComparator.java
01
02 package org.arpit.javapostsforlearning;
03
import java.util.Comparator;
04
//If country1.getCountryId()<country2.getCountryId():then compare method will return
05 //If country1.getCountryId()>country2.getCountryId():then compare method will return
06 //If country1.getCountryId()==country2.getCountryId():then compare method will return
07 public class CountrySortByIdComparator implements Comparator<Country>{
08
09 @Override
public int compare(Country country1, Country country2) {
10
11 return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.ge
12 }
13
14 }
15
3.ComparatorMain.java
01 package org.arpit.javapostsforlearning;
02
import java.util.ArrayList;
03 import java.util.Collections;
04 import java.util.Comparator;
05 import java.util.List;
06
07 public class ComparatorMain {
08
/**
09 * @author Arpit Mandliya
10 */
11 public static void main(String[] args) {
12 Country indiaCountry=new Country(1, 'India');
13 Country chinaCountry=new Country(4, 'China');
Country nepalCountry=new Country(3, 'Nepal');
14 Country bhutanCountry=new Country(2, 'Bhutan');
15
16 List<Country> listOfCountries = new ArrayList<Country>();
17 listOfCountries.add(indiaCountry);
18 listOfCountries.add(chinaCountry);
19 listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
20
21 System.out.println('Before Sort by id : ');
22 for (int i = 0; i < listOfCountries.size(); i++) {
23 Country country=(Country) listOfCountries.get(i);
24 System.out.println('Country Id: '+country.getCountryId()+'||'+'Countr
}
25 Collections.sort(listOfCountries,new CountrySortByIdComparator());
26
27 System.out.println('After Sort by id: ');
28 for (int i = 0; i < listOfCountries.size(); i++) {
29 Country country=(Country) listOfCountries.get(i);
30 System.out.println('Country Id: '+country.getCountryId()+'|| '+'Count
}
31
32 //Sort by countryName
33 Collections.sort(listOfCountries,new Comparator<Country>() {
34
35 @Override
36 public int compare(Country o1, Country o2) {
return o1.getCountryName().compareTo(o2.getCountryName());
37 }
38 });
39
40 System.out.println('After Sort by name: ');
41 for (int i = 0; i < listOfCountries.size(); i++) {
42 Country country=(Country) listOfCountries.get(i);
System.out.println('Country Id: '+country.getCountryId()+'|| '+'Count
43 }
44 }
45
46 }
47
48
49
50
51
52
53
54
Output:
01
02 Before Sort by id :
03 Country Id: 1||Country name: India
04 Country Id: 4||Country name: China
05 Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
06 After Sort by id:
07 Country Id: 1|| Country name: India
08 Country Id: 2|| Country name: Bhutan
09 Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
10 After Sort by name:
11 Country Id: 2|| Country name: Bhutan
12 Country Id: 4|| Country name: China
13 Country Id: 1|| Country name: India
14 Country Id: 3|| Country name: Nepal
15
}
for (int i: arraylist) {
System.out.println(i);
}
It is giving error while swapping, The LHS should be variable. I understand it. Set method
works here but I do not want to use. Is there a way to do it without using set method? Help
is really appreciated.
Or
arraylist.get(i)= arraylist.get(i);
arraylist.get(j) =tmp;
You can't assign a value to a method call. As the compiler told you, the left hand side of an
assignment must be a variable.
Ans-Association
Association is relation between two separate classes which establishes through their
Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many.
In Object-Oriented programming, an Object communicates to other Object to use
functionality and services provided by that object. Composition and Aggregation are
the two forms of association.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Association
import java.io.*;
// class bank
class Bank
{
private String name;
// bank name
Bank(String name)
{
this.name = name;
}
// employee class
class Employee
{
private String name;
// employee name
Employee(String name)
{
this.name = name;
}
System.out.println(emp.getEmployeeName() +
" is employee of " + bank.getBankName());
}
}
Output:
Neha is employee of Axis
In above example two separate classes Bank and Employee are associated through
their Objects. Bank can have many employees, So it is a one-to-many relationship.
Aggregation
It is a special form of Association where:
It represents Has-A relationship.
It is a unidirectional association i.e. a one way relationship. For example,
department can have students but vice versa is not possible and thus
unidirectional in nature.
In Aggregation, both the entries can survive individually which means ending
one entity will not effect the other entity
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate
//the concept of Aggregation.
import java.io.*;
import java.util.*;
// student class
class Student
{
String name;
int id ;
String dept;
}
}
String name;
private List<Student> students;
Department(String name, List<Student> students)
{
this.name = name;
this.students = students;
String instituteName;
private List<Department> departments;
// main method
class GFG
{
public static void main (String[] args)
{
Student s1 = new Student("Mia", 1, "CSE");
Student s2 = new Student("Priya", 2, "CSE");
Student s3 = new Student("John", 1, "EE");
Student s4 = new Student("Rahul", 2, "EE");
// making a List of
// CSE Students.
List <Student> cse_students = new ArrayList<Student>();
cse_students.add(s1);
cse_students.add(s2);
// making a List of
// EE Students
List <Student> ee_students = new ArrayList<Student>();
ee_students.add(s3);
ee_students.add(s4);
Composition
Composition is a restricted form of Aggregation in which two entities are highly
dependent on each other.
It represents part-of relationship.
In composition, both the entities are dependent on each other.
When there is a composition between two entities, the composed object cannot
existwithout the other entity.
Lets take example of Library.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate
// the concept of Composition
import java.io.*;
import java.util.*;
// class book
class Book
{
return books;
}
// main method
class GFG
{
public static void main (String[] args)
{
import java.io.*;
// Engine class
final class Car
{
Car(Engine engine)
{
this.engine = engine;
}
//if(engine != null)
{
engine.work();
System.out.println("Car is moving ");
}
}
}
class GFG
{
public static void main (String[] args)
{
}
}
Output:
Engine of car has been started
Car is moving
In case of aggregation, the Car also performs its functions through an Engine. but the
Engine is not always an internal part of the Car. An engine can be swapped out or even
can be removed from the car. That’ why we make The Engine type field non-final.
9)hashset internal flow.
Ans-HashSet uses HashMap internally to store it’s objects. Whenever you create a HashSet
object, one HashMap object associated with it is also created. This HashMap object is used to
store the elements you enter in the HashSet. The elements you add into HashSet are stored
as keys of this HashMap object. The value associated with those keys will be a constant.
Every constructor of HashSet class internally creates one HashMap object. You can check this in
the source code of HashSet class in JDK installation directory. Below is the some sample code of
the constructors of HashSet class.
2
//Constructor - 1
3
4
public HashSet()
5
{
6
map = new HashMap<>(); //Creating internally backing HashMap object
7
}
8
9 //Constructor - 2
10
12 {
addAll(c);
14
}
15
16
//Constructor - 3
17
18
public HashSet(int initialCapacity, float loadFactor)
19
{
20
map = new HashMap<>(initialCapacity, loadFactor); //Creating internall
21 }
22
23 //Constructor - 4
24
{
26
map = new HashMap<>(initialCapacity); //Creating internally backing
27
}
28
29
30
You can notice that each and every constructor internally creates one new HashMap object.
Whenever you insert an element into HashSet using add() method, it actually creates an entry in
the internally backing HashMap object with element you have specified as it’s key and constant
called “PRESENT” as it’s value. This “PRESENT” is defined in the HashSet class as below.
4 }
You can notice that, add() method of HashSet class internally calls put() method of backing
HashMap object by passing the element you have specified as a key and constant “PRESENT”
as it’s value.
3 return map.remove(o)==PRESENT;
}
4
Let’s see one example of HashSet and how it maintains HashMap internally.
1
public class HashSetExample
2
{
3
public static void main(String[] args)
4
{
5
//Creating One HashSet object
6
10
11 set.add("RED");
12
13 set.add("GREEN");
14
set.add("BLUE");
15
16
set.add("PINK");
17
18
//Removing "RED" from HashSet
19
20
set.remove("RED");
21
}
22
}
23
See the below picture how above program works internally. You can observe that internal
HashMap object contains elements of HashSet as keys and constant “PRESENT” as their value.
In the same manner, all methods of HashSet class process internally backing HashMap object to
get the desired result. If you know how HashMap works, it will be easy for you to understand
how HashSet works. You go through the source code of HashSet class once, you will get a clear
picture about how HashSet works internally in Java.
10)difference between fail fast and failsafe
Ans-In this article, we’ll introduce the concept of Fail-Fast and Fail-
Safe Iterators.Fail-Fast systems abort operation as-fast-as-possible exposing
failures immediately and stopping the whole operation.
Whereas, Fail-Safe systems don’t abort an operation in the case of a failure. Such
systems try to avoid raising failures as much as possible.
2. Fail-Fast Iterators
Fail-fast iterators in Java don’t play along when the underlying collection gets
modified.
Collections maintain an internal counter called modCount. Each time an item is added
or removed from the Collection, this counter gets incremented.
When iterating, on each next() call, the current value of modCount gets compared with
the initial value. If there’s a mismatch, it
throws ConcurrentModificationException which aborts the entire operation.
Default iterators for Collections from java.util package such
as ArrayList, HashMap, etc. are Fail-Fast.
1 ArrayList<Integer> numbers = // ...
2
6 numbers.add(50);
}
7
3
Iterator<Integer> iterator = numbers.iterator();
4
while (iterator.hasNext()) {
5
if (iterator.next() == 30) {
6 iterator.remove(); // ok!
7 }
8 }
10 iterator = numbers.iterator();
while (iterator.hasNext()) {
11
if (iterator.next() == 40) {
12
numbers.remove(2); // exception
13
}
14
}
15
3. Fail-Safe Iterators
Fail-Safe iterators favor lack of failures over the inconvenience of exception handling.
Those iterators create a clone of the actual Collection and iterate over it. If any
modification happens after the iterator is created, the copy still remains untouched.
Hence, these Iterators continue looping over the Collection even if it’s modified.
However, it’s important to remember that there’s no such thing as a truly Fail-Safe
iterator. The correct term is Weakly Consistent.
That means, if a Collection is modified while being iterated over, what
the Iterator sees is weakly guaranteed. This behavior may be different for
different Collections and is documented in Javadocs of each such Collection.
The Fail-Safe Iterators have a few disadvantages, though. One disadvantage is that
the Iterator isn’t guaranteed to return updated data from the Collection, as it’s
working on the clone instead of the actual Collection.
Another disadvantage is the overhead of creating a copy of the Collection, both
regarding time and memory.
Iterators on Collections from java.util.concurrent package such
as ConcurrentHashMap, CopyOnWriteArrayList, etc. are Fail-Safe in nature.
1
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
2
3
map.put("First", 10);
4 map.put("Second", 20);
5 map.put("Third", 30);
6 map.put("Fourth", 40);
10 while (iterator.hasNext()) {
In the code snippet above, we’re using Fail-Safe Iterator. Hence, even though a new
element is added to the Collection during the iteration, it doesn’t throw an exception.
The default iterator for the ConcurrentHashMap is weakly consistent. This means that
this Iterator can tolerate concurrent modification, traverses elements as they existed
when Iterator was constructed and may (but isn’t guaranteed to) reflect modifications
to the Collection after the construction of the Iterator.
Hence, in the code snippet above, the iteration loops five times, which means it does
detect the newly added element to the Collection.
11)how to create datasource in hibernate.
Ans-I'm creating SessionFactory and I have my datasource as object in code where I'm
creating SessionFactory, but i cannot set datasource to Hibernate Configuration object. So
how can I set my datasource to my SessionFactory?
# Oracle DB - "foo"
spring.datasource.url=jdbc:oracle:thin:@//db-server-foo:1521/FOO
spring.datasource.username=fooadmin
spring.datasource.password=foo123
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# PostgreSQL DB - "bar"
bar.datasource.url=jdbc:postgresql://db-server-bar:5432/bar
bar.datasource.username=baradmin
bar.datasource.password=bar123
bar.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database=default
src/main/java
- com.foobar
- foo
- domain
- repo
- bar
- domain
- repo
package com.foobar;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.foobar.foo.repo" }
)
public class FooDbConfig {
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource") DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.foobar.foo.domain")
.persistenceUnit("foo")
.build();
}
@Primary
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
5. Create a Configuration Class for the
PostgreSQL database “bar” named
“BarDbConfig.java”
package com.foobar;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "barEntityManagerFactory",
transactionManagerRef = "barTransactionManager",
basePackages = { "com.foobar.bar.repo" }
)
public class BarDbConfig {
@Bean(name = "barDataSource")
@ConfigurationProperties(prefix = "bar.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "barEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean
barEntityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("barDataSource") DataSource dataSource
) {
return
builder
.dataSource(dataSource)
.packages("com.foobar.bar.domain")
.persistenceUnit("bar")
.build();
}
@Bean(name = "barTransactionManager")
public PlatformTransactionManager barTransactionManager(
@Qualifier("barEntityManagerFactory") EntityManagerFactory
barEntityManagerFactory
) {
return new JpaTransactionManager(barEntityManagerFactory);
}
}
6. Create an Entity “Foo.java” for the Oracle
database “foo”
package com.foobar.foo.domain;
@Entity
@Table(name = "FOO")
public class Foo {
@Id
@GeneratedValue
@Column(name = "ID")
private Long id;
@Column(name = "FOO")
private String foo;
Foo(String foo) {
this.foo = foo;
}
Foo() {
// Default constructor needed by JPA
}
}
package com.foobar.foo.repo;
@Repository
public interface FooRepository extends JpaRepository<Foo, Long>
{
}
8. Create an Entity “Bar.java” for the PostgreSQL
database “bar”
package com.foobar.bar.domain;
@Entity
@Table(name = "BAR")
public class Bar {
@Id
@GeneratedValue
@Column(name = "ID")
private Long id;
@Column(name = "BAR")
private String bar;
Bar(String bar) {
this.bar = bar;
}
Bar() {
// Default constructor needed by JPA
}
}
package com.foobar.bar.repo;
@Repository
public interface BarRepository extends JpaRepository<Bar, Long>
{
}
10. Create the Spring Boot Main Class
“Application.java”
package com.foobar;
@SpringBootApplication
public class Application {
package com.foobar;
@RestController
public class FooBarController {
@Autowired
FooBarController(FooRepository fooRepo, BarRepository barRepo)
{
this.fooRepo = fooRepo;
this.barRepo = barRepo;
}
@RequestMapping("/foobar/{id}")
public String fooBar(@PathVariable("id") Long id) {
Foo foo = fooRepo.findById(id);
Bar bar = barRepo.findById(id);
In Spring Web MVC, DispatcherServlet class works as the front contro ller. It is responsible to
manage the flow of the spring mvc application.
The @Controller annotation is used to mark the class as the controller in Spring 3.
The @RequestMapping annotation is used to map the request url. It is applied on the method.
Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the Controller
class name associated with the given request.
Step 3: So request transfer to the Controller, and then controller will process the request by
executing appropriate methods and returns ModelAndView object (contains Model data and View
name) back to the DispatcherServlet.
Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view
page.
Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the
result.
Now Let us understand Spring MVC flow with hello world application Example.
First of all, we create Dynamic web project in eclipse and following are the required files for the
same:
JavaController.java
welcomePage.jsp
web.xml
welcome-servlet.xml
index.jsp
JavaController.java
JavaController.java
Java
0
1 package com.codeNuclear;
3 import javax.servlet.http.HttpServletRequest;
5 import org.springframework.stereotype.Controller;
6 import org.springframework.ui.ModelMap;
7 import org.springframework.web.bind.annotation.RequestMapping;
8 import org.springframework.web.servlet.ModelAndView;
10
11 @Controller
13 {
14 @RequestMapping("/codeNuclear")
16 {
17
20
21 System.out.println(message);
22 model.addAttribute("message", message);
23
25 }//ModelAndView closed
26 }
27
welcomePage.jsp
welcomePage.jsp
Java
0
2 pageEncoding="ISO-8859-1"%>
4 <html>
5 <body>
7 ${welcomeMessage}
8 </font>
9 </body>
10 </html>
11
web.xml
web.xml
XHTML
4 <display-name>SpringMvcExample</display-name>
5
6 <servlet>
7 <servlet-name>welcome</servlet-name>
8 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
9 <load-on-startup>1</load-on-startup>
10 </servlet>
11
12 <servlet-mapping>
13 <servlet-name>welcome</servlet-name>
14 <url-pattern>/</url-pattern>
15 </servlet-mapping>
16 <welcome-file-list>
17 <welcome-file>/</welcome-file>
18 </welcome-file-list>
19 </web-app>
welcome-servlet.xml
servlet.xml
XHTML
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="
6 http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
10
13 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
16 </bean>
17
18 </beans>
19
index.jsp
index.jsp
Java
2 pageEncoding="ISO-8859-1"%>
4 <html>
5 <head>
7 </head>
8 <body>
11 Welcome...
13 </font>
14
15 </body>
16 </html>
17
Step 2)Once you click on that link, container will check the URL pattern at web.xml and passes
the request to the DispatcherServlet.
Java
Means first argument is ‘View’ page name [ Where we are sending our result ], second, third
arguments are key,values.
Step 5)So DispatcherServlet search for the name welcomePage in /jsp folder with extension .jsp ,
once the file was opened you can access the data by using the key welcomeMessage [2nd
parameter in ModelAndView object].
Check welcomePage.jsp and printing the result by calling the key ${welcomeMessage}
from welcomePage.jsp.
Output
14) how to give security in spring mvc
Ans- https://docs.spring.io/spring-security/site/docs/current/guides/html5/hellomvc-
javaconfig.html
Ans-Dependency injection is basically providing the objects that an object needs (its
dependencies) instead of having it construct them itself. It's a very useful technique for
testing, since it allows dependencies to be mocked or stubbed out.
Dependencies can be injected into objects by many means (such as constructor injection or
setter injection). One can even use specialized dependency injection frameworks (e.g.
Spring) to do that, but they certainly aren't required. You don't need those frameworks to
have dependency injection. Instantiating and passing objects (dependencies) explicitly is
just as good an injection as injection by framework..
Ans- have @Autowired service which has to be used from within a static method. I know this
is wrong but I cannot change the current design as it would require a lot of work, so I need
some simple hack for that. I can't change randomMethod() to be non-static and I need to use
this autowired bean. Any clues how to do that?
@Service
public class Foo {
public int doStuff() {
return 1;
}
}
Ans- A class that takes a required dependency as a constructor argument can only be
instantiated if that argument is provided (you should have a guard clause to make sure the
argument is not null.) A constructor therefore enforces the dependency requirement
whether or not you're using Spring, making it container-agnostic.
If you use setter injection, the setter may or may not be called, so the instance may never
be provided with its dependency. The only way to force the setter to be called is
using @Required or @Autowired , which is specific to Spring and is therefore not container-
agnostic.
So to keep your code independent of Spring, use constructor arguments for injection.
t1.start();
}
}
3. Implement the java.util.concurrent.Callable interface
}
}
Favor Callable interface with the Executor framework for thread pooling.
The Runnable or Callable interface is preferred over extending the Thread class
Ans- Threading is a facility to allow multiple tasks to run concurrently within a single
process. Threads are independent, concurrent execution through a program, and each
thread has its own stack.
In Java threads can be implemented in two ways.
e.g.
System.out.println("thread is running...");
t1.start();
Output:thread is running...
e.g.
System.out.println("thread is running...");
t1.start();
Output:thread is running...
Creating a thread in Java
- The limitation with "extends Thread" approach is that if you extend Thread, you can not
extend other class . Java does not support multiple inheritance.
- In "implements Runnable" , we are creating a different Runnable class for a specific task. It
gives us the freedom to reuse the specific behavior task whenever required.
"extends Thread" contains both thread and job specific behavior code. Hence once thread
completes execution , it can not be restart again.
- "implements Runnable" makes the code loosely-coupled and easier to read .Because the
code is split into two classes . Thread class for the thread specific code and your Runnable
implementation class for your task that should be run by a thread code.
"extends Thread" makes the code tightly coupled . Single class contains the thread code as
well as the task that needs to be done by the thread.
As per he above difference second approach has many advantages over the first approach so
second approach is preferable.
Ans- https://dzone.com/articles/how-spring-mvc-really-works
presentation layer:
It is also known as Client layer. Top most layer of an application. The main functionality of this layer
is to communicate with Application layer. For example, login page of Facebook where an end user
could see text boxes and buttons to enter user id, password and to click on sign-in. This is also called
view of the application.
Example: JSP
Business layer:
It is also called business logic layer or logical layer. As per the Facebook login page example, once user
clicks on the login button, business layer interacts with Database layer and sends required information
to the Presentation layer. It controls an application’s functionality by performing detailed processing.
This layer acts as a mediator between the Presentation and the Database layer. Complete business logic
will be written in this layer.
Example: STRUTS,SPRING
Data layer:
The data is stored in this layer. Business layer communicates with Database layer to retrieve the data.
It contains methods that connects the database and performs required action e.g.: insert, update,
delete etc.
Step 1: When ever we submitting the request from client(Browser) to Server component then
controller receives the request from Browser. So you must remember every request will reach to
controller component.
Step 2: The controller receives the request from Browser then Controller has to identify a particular
model. Then it will execute business logic. Here model is might be java class or business
logic's available. Here controller acts as mediator between view and the model. Finally, after
performing some action on server side then controller identify respective view component. That means
JSP page has view part.
Step 3: After executing model part if it is required to interact with database then model part interact
with database.
step 4: Then view layer displays of the model to the end user. Then generate the require dynamic web
page return to Browser. Finally view part send to the response to the client(Browser)
Ans- Iterators are used in Collection framework in Java to retrieve elements one by one. There
are three iterators.
Enumeration :
import java.util.Enumeration;
import java.util.Vector;
v.addElement(i);
System.out.println(v);
Enumeration e = v.elements();
while (e.hasMoreElements())
int i = (Integer)e.nextElement();
System.out.print(i + " ");
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
Limitations of Enumeration :
Enumeration is for legacy classes(Vector, Hashtable) only. Hence it is not a universal iterator.
Remove operations can’t be performed using Enumeration.
Only forward direction iterating is possible.
Iterator:
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can
perform both read and remove operations. It is improved version of Enumeration with additional
functionality of remove-ability of a element.
Iterator must be used whenever we want to enumerate elements in all Collection framework
implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map
interface. Iterator is the only cursor available for entire collection framework.
Iterator object can be created by calling iterator() method present in Collection interface.
// Here "c" is any Collection object. itr is of
// type Iterator interface and refers to "c"
Iterator itr = c.iterator();
Iterator interface defines three methods:
// Returns true if the iteration has more elements
public boolean hasNext();
import java.util.ArrayList;
import java.util.Iterator;
al.add(i);
System.out.println(al);
while (itr.hasNext())
int i = (Integer)itr.next();
// getting even elements one by one
if (i % 2 != 0)
itr.remove();
System.out.println();
System.out.println(al);
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
[0, 2, 4, 6, 8]
Limitations of Iterator :
Only forward direction iterating is possible.
Replacement and addition of new element is not supported by Iterator.
ListIterator:
It is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides bi-
directional iteration.
ListIterator must be used when we want to enumerate elements of List. This cursor has more
functionality(methods) than iterator.
ListIterator object can be created by calling listIterator() method present in List interface.
// Here "l" is any List object, ltr is of type
// ListIterator interface and refers to "l"
ListIterator ltr = l.listIterator();
ListIterator interface extends Iterator interface. So all three methods of Iterator interface are
available for ListIterator. In addition there are six more methods.
// Forward direction
// Returns true if the iteration has more elements
public boolean hasNext();
// Backward direction
// Other Methods
import java.util.ArrayList;
import java.util.ListIterator;
al.add(i);
System.out.println(al);
while (ltr.hasNext())
int i = (Integer)ltr.next();
// iterator
if (i%2==0)
ltr.add(i); // to add
System.out.println();
System.out.println(al);
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
[1, 1, 1, 3, 3, 3, 5, 5, 5, 7, 7, 7, 9, 9, 9]
Limitations of ListIterator : It is the most powerful iterator but it is only applicable for List
implemented classes, so it is not a universal iterator.
2 : We don’t create objects of Enumeration, Iterator, ListIterator because they are interfaces. We
use methods like elements(), iterator(), listIterator() to create objects. These methods have
anonymous Inner classes that extends respective interfaces and return this class object. This can
be verified by below code. For more on inner class refer
filter_none
edit
play_arrow
brightness_4
// Java program to demonstrate iterators references
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
Enumeration e = v.elements();
System.out.println(e.getClass().getName());
System.out.println(itr.getClass().getName());
System.out.println(ltr.getClass().getName());
}
Output:
java.util.Vector$1
java.util.Vector$Itr
java.util.Vector$ListItr
In this article we will explore most commonly used Spring Annotations and also look at some
example program.
1. @Configuration: Used to indicate that a class declares one or more @Bean methods. These
classes are processed by the Spring container to generate bean definitions and service requests for
those beans at runtime.
2. @Bean: Indicates that a method produces a bean to be managed by the Spring container. This is
one of the most used and important spring annotation. @Bean annotation also can be used with
parameters like name, initMethod and destroyMethod.
name – allows you give name for bean
initMethod – allows you to choose method which will be invoked on context register
destroyMethod – allows you to choose method which will be invoked on context shutdown
For example:
@Configuration
public class AppConfig {
@Bean(name = "comp", initMethod = "turnOn",
destroyMethod = "turnOff")
Computer computer(){
return new Computer();
}
}
3. @PreDestroy and @PostConstruct are alternative way for bean initMethod and
destroyMethod. It can be used when the bean class is defined by us. For example;
4.
5. public class Computer {
6.
7. @PostConstruct
8. public void turnOn(){
9. System.out.println("Load operating system");
10. }
11.
12. @PreDestroy
13. public void turnOff(){
14. System.out.println("Close all programs");
15. }
16. }
17. @ComponentScan: Configures component scanning directives for use with @Configuration
classes. Here we can specify the base packages to scan for spring components.
18. @Component: Indicates that an annotated class is a “component”. Such classes are considered as
candidates for auto-detection when using annotation-based configuration and classpath scanning.
19. @PropertySource: provides a simple declarative mechanism for adding a property source to
Spring’s Environment. There is a similar annotation for adding an array of property source files
i.e @PropertySources.
20. @Service: Indicates that an annotated class is a “Service”. This annotation serves as a
specialization of @Component, allowing for implementation classes to be autodetected through
classpath scanning.
21. @Repository: Indicates that an annotated class is a “Repository”. This annotation serves as a
specialization of @Component and advisable to use with DAO classes.
22. @Autowired: Spring @Autowired annotation is used for automatic injection of beans. Spring
@Qualifier annotation is used in conjunction with Autowired to avoid confusion when we have
two of more bean configured for same type.
Spring MVC Annotations
Some of the important Spring MVC annotations are:
1. @Controller
2. @RequestMapping
3. @PathVariable
4. @RequestParam
5. @ModelAttribute
6. @RequestBody and @ResponseBody
7. @RequestHeader and @ResponseHeader
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.spring</groupId>
<artifactId>spring-annotations</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring Annotations</name>
<properties>
<spring.framework>4.3.0.RELEASE</spring.framework>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework}</version>
</dependency>
</dependencies>
</project>
This will pull up all the spring core jars for our project.
Component Classes
Next step is to create component classes. Here I am imitating multiple database components, one
for MySQL and another for Oracle.
package com.journaldev.drivers;
package com.journaldev.drivers;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:mysqldatabase.properties")
public class MySqlDriver implements DataBaseDriver {
@Value("${databaseName}")
private String databaseName;
@Value("${disableStatementPooling}")
private String disableStatementPooling;
databaseName=school
disableStatementPooling=true
package com.journaldev.drivers;
package com.journaldev.service;
import com.journaldev.drivers.DataBaseDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
@Qualifier("oracleDriver")
private DataBaseDriver dataBaseDriver;
Spring Beans
Final step is to create our spring beans and configuration classes to glue everything together.
package com.journaldev.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import com.journaldev.drivers.DataBaseDriver;
import com.journaldev.drivers.MySqlDriver;
import com.journaldev.drivers.OracleDriver;
@Configuration
@ComponentScan("com.journaldev")
@PropertySource("classpath:oracledatabase.properties")
public class AppConfig {
@Autowired
Environment environment;
@Bean
DataBaseDriver oracleDriver() {
OracleDriver oracleDriver = new OracleDriver();
oracleDriver.setDriver(environment.getProperty("db.driver"
));
oracleDriver.setUrl(environment.getProperty("db.url"));
oracleDriver.setPort(Integer.parseInt(environment.getProperty("d
b.port")));
oracleDriver.setUser(environment.getProperty("db.user"));
oracleDriver.setPassword(environment.getProperty("db.password"))
;
return oracleDriver;
@Bean
DataBaseDriver mysqlDriver() {
return new MySqlDriver();
}
}
Notice the bean definition for oracleDriver. In this method, we are reading properties
from oracledatabase.properties file that is being set to environment variable by Spring
framework.
db.url=localhost
db.port=4444
db.user=vasiliy
db.password=yilisav
db.driver=driver_name
Our spring annotations example project is ready to test. As a summary, we performed following
steps:
package com.journaldev;
import
org.springframework.context.annotation.AnnotationConfigApplicati
onContext;
import
org.springframework.context.support.AbstractApplicationContext;
import com.journaldev.config.AppConfig;
import com.journaldev.drivers.DataBaseDriver;
import com.journaldev.service.UserService;
appContext.close();
}
}
Below image shows the output produced. Notice that we haven’t configured any logging
framework, so all the spring framework logging is getting printed into console in red color.
25)Difference between SessionFactory and session.
Ans- Do we have any other differences other than the below? Also please validate whether
the below are correct
1. SessionFactory objects are one per application and Session objects are one per client.
2. SessionFactory is to create and manage Sessions. Session is to provide a CRUD interface for
mapped classes, and also access to the more versatile Criteria API.
3. SessionFactory is thread safe where as Session is not thread safe
persist() also guarantees that it will not execute an INSERT statement if it is called
outside of transaction boundaries. This is useful in long-running conversations with an
extended Session/persistence context.
save() does not guarantee the same, it returns an identifier, and if an INSERT has to be
executed to get the identifier (e.g. "identity" generator, not "sequence"), this INSERT
happens immediately, no matter if you are inside or outside of a transaction. This is not
good in a long-running conversation with an extended Session/persistence context.
class Test {
// Driver code
static public void main (String[] args)
{
String str = "geeksforgeeks";
int pos = findRepeatFirstN2(str);
if (pos == -1)
System.out.println("Not found");
else
System.out.println( str.charAt(pos));
}
}