Java Interview Questions-1
Java Interview Questions-1
~Navnath Jadhav
1) What is Java?
⚫ Java is a general purpose, class based, high-level,
object oriented programming language and it is
platform independent.
⚫ Java is fast, secure and reliable.
⚫ It was developed by sun microsystem
⚫ There are a lot of applications, websites and
games that are developed using java.
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in window,
web-based, enterprise and mobile
applications.
Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. It interpreter for printing systems but later
was an extension of C extended as a support network computing.
programming language. It was designed with a goal of being easy to
use and accessible to a broader audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Pointers C++ supports pointers. You can Java supports pointer internally. However,
write pointer program in C++. you can't write the pointer program in java.
It means java has restricted pointer support
in Java.
Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both.
Interpreter compiled and run using the Java source code is converted into bytecode
compiler which converts source at compilation time. The interpreter
code into machine code so, C++ executes this bytecode at runtime and
is platform dependent. produces output. Java is interpreted that is
why it is platform independent.
Call by Value and C++ supports both call by value Java supports call by value only. There is no
Call by reference and call by reference. call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and unions.
Union unions.
Thread Support C++ doesn't have built-in support Java has built-in thread support.
for threads. It relies on third-party
libraries for thread support.
Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We can
that we can decide whether or not override all non-static methods by default.
override a function. In other words, non-static methods are
virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.
Inheritance Tree C++ creates a new inheritance Java uses a single inheritance tree always
tree always. because all classes are the child of Object
class in java. The object class is the root of
the inheritance tree in java.
o Simple: Java is easy to learn. The syntax of Java is based on C++ which
makes easier to write the program in it.
o Interpreted: Java uses the Just-in-time (JIT) interpreter along with the
compiler for the program execution.
o Multithreaded: We can write Java programs that deal with many tasks
at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web
applications, etc.
Definition The JDK (Java The Java Runtime The Java Virtual
Development Kit) is a Environment (JRE) is Machine (JVM) is a
software an implementation of platform-
development kit that JVM. It is a type of independent abstract
develops applications software package that machine that has
in Java. Along with provides class libraries three notions in the
JRE, the JDK also of Java, JVM, and form of specifications.
consists of various various other This document
development tools components for describes the
(Java Debugger, running the requirement of JVM
JavaDoc, compilers, applications written in implementation.
etc.) Java programming.
Functionality The JDK primarily JRE has a major JVM specifies all of
assists in executing responsibility for the implementations.
codes. It primarily creating an It is responsible for
functions in environment for the providing all of these
development. execution of code. implementations to
the JRE.
Platform The JDK is platform- JRE, just like JDK, is The JVM is platform-
Dependency dependent. It means also platform- independent. It
that for every dependent. It means means that you
different platform, that for every won’t require a
you require a different platform, different JVM for
different JDK. you require a different every different
JRE. platform.
Tools Since JDK is JRE, on the other JVM does not consist
primarily responsible hand, does not consist of any tools for
for the development, of any tool- like a software
it consists of various debugger, compiler, development.
tools for debugging, etc. It rather contains
monitoring, and various supporting
developing java files for JVM, and the
applications. class libraries that
help JVM in running
the program.
Why Use It? Why use JDK? Why use JRE? Why use JVM?
Some crucial reasons Some crucial reasons Some crucial reasons
to use JDK are: to use JRE are: to use JVM are:
necessary application.
• JVM is also
independent of
the OS and
hardware. It
means that
once a user
writes a Java
program, they
can easily run
it anywhere.
14) What gives Java its 'write once and run anywhere'
nature?
The bytecode. Java compiler converts the Java programs into the class file
(Byte Code) which is the intermediate language between source code and
machine code. This bytecode is not platform specific and can be executed on
any computer.
run it by java A
For example, In the class simulating the collection of the students in a college,
the name of the college is the common attribute to all the students. Therefore,
the college name will be defined as static.
26)Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
1. <class_name>(){}
Example of default constructor
Output:
Bike is created
a default constructor.
The default constructor is used to provide the default values to the object like
0, null, etc., depending on the type.
Example of default constructor that displays the
default values
Output:
0 null
0 null
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not be
same as the class name.
1. class Test
2. {
3. int i;
4. public Test(int k)
5. {
6. i=k;
7. }
8. public Test(int k, int m)
9. {
10. System.out.println("Hi I am assigning the value max(k, m) to i");
11. if(k>m)
12. {
13. i=k;
14. }
15. else
16. {
17. i=m;
18. }
19. }
20. }
21. public class Main
22. {
23. public static void main (String args[])
24. {
25. Test test1 = new Test(10);
26. Test test2 = new Test(12, 15);
27. System.out.println(test1.i);
28. System.out.println(test2.i);
29. }
30. }
31.
There are many ways to copy the values of one object into another in java.
They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another
using java constructor.
Output:
111 Karan
111 Karan
The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time
of class loading.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data members
will get memory each time when the object is created. All students have its
unique rollno and name, so instance data member is good in such case. Here,
"college" refers to the common property of all objects. If we make it static, this
field will get the memory only once.
Output:
Output:
1
1
Output:
1
2
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an
instance of a class.
o A static method can access static data member and can change the
value of it.
1. //Java Program to get the cube of a given number using the static met
hod
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Test it Now
Output:125
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-
static method directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Test it Now
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Test it Now
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6.
Since JDK 1.7, it is not possible to execute a Java class without the main
method.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Test it Now
Output:
1)A method that is declared as static is known as the static A method that is not declared as
method. static is known as the instance
method.
2)We don't need to create the objects to call the static The object is required to call the
methods. instance methods.
3)Non-static (instance) members cannot be accessed in the Static and non-static variables both
static context (static method, static block, and static nested can be accessed in instance
class) directly. methods.
4)For example: public static int cube(int n){ return n*n*n;} For example: public void msg(){...}.
Output
hi !! I am good !!
i = 102
Output
10
Output
o Single-level inheritance
o Multi-level inheritance
o Multiple Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
Inheritance in Java
. Inheritance
. Types of Inheritance
. Why multiple inheritance is not possible in Java in case of class?
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
The extends keyword indicates that you are making a new class that derives
from an existing class. The meaning of "extends" is to increase the
functionality.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
In the above example, Programmer object can access the field of own class as
well as of Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Consider a scenario where A, B, and C are three classes. The C class inherits A
and B classes. If A and B classes have the same method and you call it from
child class object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same method
or different, there will be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Address.java
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }
Output
111 varun
gzb UP india
112 arun
gno UP india
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }
13. }
Test it Now
Output:
animal is created
dog is created
1. class Person
2. {
3. String name,address;
4. int age;
5. public Person(int age, String name, String address)
6. {
7. this.age = age;
8. this.name = name;
9. this.address = address;
10. }
11. }
12. class Employee extends Person
13. {
14. float salary;
15. public Employee(int age, String name, String address, float salary)
16. {
17. super(age,name,address);
18. this.salary = salary;
19. }
20. }
21. public class Test
22. {
23. public static void main (String args[])
24. {
25. Employee e = new Employee(22, "Mukesh", "Delhi", 90000);
26. System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "
+e.age+" Address: "+e.address);
27. }
28. }
Output
Example:
Output:
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Test it Now
Output:
Output
o The method must have the same name as in the parent class.
o The method must have the same signature as in the parent class.
o Two classes must have an IS-A relationship between them.
1) Method overloading increases the Method overriding provides the specific implementation of
readability of the program. the method that is already provided by its superclass.
2) Method overloading occurs within Method overriding occurs in two classes that have IS-A
the class. relationship between them.
3) In this case, the parameters must In this case, the parameters must be the same.
be different.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
More Details.
2 It is also known as static binding, It is also known as dynamic binding, late binding,
early binding, or overloading. overriding, or dynamic method dispatch.
4 It provides fast execution because the It provides slower execution as compare to compile-
type of an object is determined at time because the type of an object is determined at
compile-time. run-time.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6. public static void main(String args[]){
7. Bike b = new Splendor();//upcasting
8. b.run();
9. }
10. }
Test it Now
Output:
1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6. public static void main(String args[]){
7. Bike obj=new Honda3();
8. System.out.println(obj.speedlimit);//90
9. }
Test it Now
Output:
90
Static Binding
1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }
Dynamic Binding
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }
Test it Now
Output
true
An object of subclass type is also a type of parent class. For example, if Dog
extends Animal then object of Dog can be referred by either Dog or Animal
class.
o Abstract Class
o Interface
More details.
More details.
Output
running safely
More details.
88) Can you use abstract and final both with a method?
No, because we need to override the abstract method to provide its
implementation, whereas we can't override the final method.
An abstract class can have instance variables. An interface cannot have instance variables.
An abstract class can have the constructor. The interface cannot have the constructor.
An abstract class can have static methods. The interface cannot have static methods.
You can extend one abstract class. You can implement multiple interfaces.
The abstract class can provide the implementation The Interface can't provide the
of the interface. implementation of the abstract class.
The abstract keyword is used to declare an abstract The interface keyword is used to declare an
class. interface.
An abstract class can extend another Java class and An interface can extend another Java interface
implement multiple Java interfaces. only.
An abstract class can be extended using An interface class can be implemented using
keyword extends keyword implements
A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
o By providing only the setter or getter method, you can make the class
read-only or write-only. In other words, you can skip the getter or
setter methods.
o It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the
logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
o It is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.
o The encapsulate class is easy to test. So, it is better for unit testing.
o The standard IDE's are providing the facility to generate the getters and
setters. So, it is easy and fast to create an encapsulated class in Java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
1. javac -d . your_class_name.java
o Now, run the class file by using the absolute class file name, like
following.
1. java package_name.class_name
More details.
o Error: Error cause the program to exit since they are not recoverable.
For Example, OutOfMemoryError, AssertionError, etc.
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions, e.g., IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions,
e.g., ArithmeticException, NullPointerException, etc. Unchecked exceptions are
not checked at compile-time.
Output:
More details.
1) The throw keyword is used to throw an The throws keyword is used to declare an exception.
exception explicitly.
2) The checked exceptions cannot be The checked exception can be propagated with throws
propagated with throw only.
4) The throw keyword is used within the The throws keyword is used with the method signature.
method.
5) You cannot throw multiple exceptions. You can declare multiple exceptions, e.g., public void
method()throws IOException, SQLException.
More details.
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Test it Now
Output:
exception handled
normal flow...
Java: String Handling Interview Questions
There is given a list of string handling interview questions with short and
pointed answers. If you know any string handling interview question, kindly
post it in the comment section.
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the en
d
5. System.out.println(s);//will print Sachin because strings are immutable
objects
6. }
7. }
Test it Now
Output:
Sachin
More details.
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance
is returned. If the string doesn't exist in the pool, a new string instance is
created and placed in the pool. String objects are stored in a special memory
area known as the string constant pool For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the constant string pool.
The variable s will refer to the object in a heap (non-pool).
1. String s1="Welcome";
2. String s2="Welcome";
3. String s3="Welcome";
Only one object will be created using the above code because strings in Java
are immutable.
Output
a equals b
Explanation
The operator == also check whether the references of the two string objects
are equal or not. Although both of the strings contain the same content, their
references are not equal because both are created by different
ways(Constructor and String literal) therefore, a == b is unequal. On the other
hand, the equal() method always check for the content. Since their content is
equal hence, a equals b is printed.
Output
true
Explanation
The intern method returns the String object reference from the string pool. In
this case, s1 is created by using string literal whereas, s2 is created by using
the String pool. However, s2 is changed to the reference of s1, and the
operator == returns true.
3) The String class overrides the equals() method of Object The StringBuffer class doesn't
class. So you can compare the contents of two strings override the equals() method of
by equals() method. Object class.
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22. }
Output:
o MatchResult Interface
o Matcher class
o Pattern class
o PatternSyntaxException class
165) How the metacharacters are different from the
ordinary characters?
Metacharacters have the special meaning to the regular expression engine.
The metacharacters are ^, $, ., *, +, etc. The regular expression engine does
not consider them as the regular characters. To enable the regular expression
engine treating the metacharacters as ordinary characters, we need to escape
the metacharacters with the backslash.
1. import java.util.regex.*;
2. class RegexExample2{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches(".s", "as")); //line 4
5. System.out.println(Pattern.matches(".s", "mk")); //line 5
6. System.out.println(Pattern.matches(".s", "mst")); //line 6
7. System.out.println(Pattern.matches(".s", "amms")); //line 7
8. System.out.println(Pattern.matches("..s", "mas")); //line 8
9. }}
Output
true
false
false
false
true
Explanation
line 4 prints true since the second character of string is s, line 5 prints false
since the second character is not s, line 6 prints false since there are more than
3 characters in the string, line 7 prints false since there are more than 2
characters in the string, and it contains more than 2 characters as well, line 8
prints true since the third character of the string is s.
There are two types of nested classes, static nested class, and non-static
nested class. The non-static nested class can also be called as inner-class
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing an interface or extending class. Its na
Class decided by the java compiler.
More details.
Output:
nice fruits
Consider the following example for the working of the anonymous class using
interface.
1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }
Test it Now
Output:
nice fruits
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.
More details.
More details.
More details.
3) By anonymous object:
1. new Employee();
InputStream Hierarchy
190) What do you understand by an IO stream?
The stream is a sequence of data that flows from source to destination. It is
composed of bytes. In Java, three streams are created for us automatically.
192) What are the super most classes for all the streams?
All the stream classes can be divided into two types of classes that are
ByteStream classes and CharacterStream Classes. The ByteStream classes are
further divided into InputStream classes and OutputStream classes.
CharacterStream classes are also divided into Reader classes and Writer
classes. The SuperMost classes for all the InputStream classes is
java.io.InputStream and for all the output stream classes is
java.io.OutPutStream. Similarly, for all the reader classes, the super-most class
is java.io.Reader, and for all the writer classes, it is java.io.Writer.
1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt")
;
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
Java FileInputStream class obtains input bytes from a file. It is used for
reading byte-oriented data (streams of raw bytes) such as image data, audio,
video, etc. You can also read character-stream data. However, for reading
streams of characters, it is recommended to use FileReader class. Consider the
following example for reading bytes from a file.
1. import java.io.FileInputStream;
2. public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8.
9. fin.close();
10. }catch(Exception e){System.out.println(e);}
11. }
12. }
13.
1. package com.javatpoint;
2. import java.io.*;
3. import java.security.PermissionCollection;
4. public class FilePermissionExample{
5. public static void main(String[] args) throws IOException {
6. String srg = "D:\\IO Package\\java.txt";
7. FilePermission file1 = new FilePermission("D:\\IO Package\\-
", "read");
8. PermissionCollection permission = file1.newPermissionCollection();
9. permission.add(file1);
10. FilePermission file2 = new FilePermission(srg, "write");
11. permission.add(file2);
12. if(permission.implies(new FilePermission(srg, "read,write"))) {
13. System.out.println("Read, Write permission is granted for the pat
h "+srg );
14. }else {
15. System.out.println("No Read, Write permission is granted for th
e path "+srg); }
16. }
17. }
Output
198) In Java, How many ways you can take input from
the console?
In Java, there are three ways by using which, we can take input from the
console.
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class Person
5. {
6. public static void main(String[] args) throws IOException
7. {
8. System.out.println("Enter the name of the person");
9. BufferedReader reader = new BufferedReader(new InputStr
eamReader(System.in));
10. String name = reader.readLine();
11. System.out.println(name);
12. }
13. }
o Using Scanner class: The Java Scanner class breaks the input into
tokens using a delimiter that is whitespace by default. It provides many
methods to read and parse various primitive values. Java Scanner class
is widely used to parse text for string and primitive types using a
regular expression. Java Scanner class extends Object class and
implements Iterator and Closeable interfaces. Consider the following
example.
1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){
4. String str = "Hello/This is JavaTpoint/My name is Abhishek
.";
5. //Create scanner with the specified String Object
6. Scanner scanner = new Scanner(str);
7. System.out.println("Boolean Result: "+scanner.hasNextBoo
lean());
8. //Change the delimiter of this scanner
9. scanner.useDelimiter("/");
10. //Printing the tokenized Strings
11. System.out.println("---Tokenizes String---");
12. while(scanner.hasNext()){
13. System.out.println(scanner.next());
14. }
15. //Display the new delimiter
16. System.out.println("Delimiter used: " +scanner.delimiter());
17. scanner.close();
18. }
19. }
20.
o Using Console class: The Java Console class is used to get input from
the console. It provides methods to read texts and passwords. If you
read the password using the Console class, it will not be displayed to
the user. The java.io.Console class is attached to the system console
internally. The Console class is introduced since 1.5. Consider the
following example.
1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
1. import java.io.FileInputStream;
2. import java.io.FileOutputStream;
3. import java.io.IOException;
4. import java.io.NotSerializableException;
5. import java.io.ObjectInputStream;
6. import java.io.ObjectOutputStream;
7. import java.io.Serializable;
8. class Person implements Serializable
9. {
10. String name = " ";
11. public Person(String name)
12. {
13. this.name = name;
14. }
15. }
16. class Employee extends Person
17. {
18. float salary;
19. public Employee(String name, float salary)
20. {
21. super(name);
22. this.salary = salary;
23. }
24. private void writeObject(ObjectOutputStream out) throws IOExcepti
on
25. {
26. throw new NotSerializableException();
27. }
28. private void readObject(ObjectInputStream in) throws IOException
29. {
30. throw new NotSerializableException();
31. }
32.
33. }
34. public class Test
35. {
36. public static void main(String[] args)
37. throws Exception
38. {
39. Employee emp = new Employee("Sharma", 10000);
40.
41. System.out.println("name = " + emp.name);
42. System.out.println("salary = " + emp.salary);
43.
44. FileOutputStream fos = new FileOutputStream("abc.ser");
45. ObjectOutputStream oos = new ObjectOutputStream(fos);
46.
47. oos.writeObject(emp);
48.
49. oos.close();
50. fos.close();
51.
52. System.out.println("Object has been serialized");
53.
54. FileInputStream f = new FileInputStream("ab.txt");
55. ObjectInputStream o = new ObjectInputStream(f);
56.
57. Employee emp1 = (Employee)o.readObject();
58.
59. o.close();
60. f.close();
61.
62. System.out.println("Object has been deserialized");
63.
64. System.out.println("name = " + emp1.name);
65. System.out.println("salary = " + emp1.salary);
66. }
67. }
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("
f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }
211 ravi
1) The Serializable interface does not have The Externalizable interface contains is not a marker
any method, i.e., it is a marker interface. interface, It contains two methods, i.e.,
writeExternal() and readExternal().
2) It is used to "mark" Java classes so that The Externalizable interface provides control of the
objects of these classes may get the serialization logic to the programmer.
certain capability.
3) It is easy to implement but has the It is used to perform the serialization and often
higher performance cost. result in better performance.
4) No class constructor is called in We must call a public default constructor while using
serialization. this interface.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
219)What are autoboxing and unboxing? When does it
occur?
The autoboxing is the process of converting primitive data type to the
corresponding wrapper class object, eg., int to Integer. The unboxing is the
process of converting wrapper class object to primitive data type. For eg.,
integer to int. Unboxing and autoboxing occur automatically in Java. However,
we can externally convert one into another by using the methods like valueOf()
or xxxValue().
It can occur whenever a wrapper class object is expected, and primitive data
type is provided or vice versa.
bye
Explanation
The Integer class caches integer values from -127 to 127. Therefore, the
Integer objects can only be created in the range -128 to 127. The
operator == will not work for the value greater than 127; thus bye is printed.
o You don't need to write lengthy and repetitive codes. Just use an
abstract class with a 4- or 5-line long clone() method.
o It is the easiest and most efficient way of copying objects, especially if
we are applying it to an already developed or an old project. Just define
a parent class, implement Cloneable in it, provide the definition of the
clone() method and the task will be done.
o Clone() is the fastest way to copy the array.
o Standard input
o Error output streams
o Standard output
o utility method to copy the portion of an array
o utilities to load files and libraries
There are the three fields of Java System class, i.e., static printstream err, static
inputstream in, and standard output stream.
1. class Singleton{
2. private static Singleton single_instance = null;
3. int i;
4. private Singleton ()
5. {
6. i=90;
7. }
8. public static Singleton getInstance()
9. {
10. if(single_instance == null)
11. {
12. single_instance = new Singleton();
13. }
14. return single_instance;
15. }
16. }
17. public class Main
18. {
19. public static void main (String args[])
20. {
21. Singleton first = Singleton.getInstance();
22. System.out.println("First instance integer value:"+first.i);
23. first.i=first.i+90;
24. Singleton second = Singleton.getInstance();
25. System.out.println("Second instance integer value:"+second.i);
26. }
27. }
28.
1. class A{
2. public static void main(String args[]){
3. for(int i=0;i<args.length;i++)
4. System.out.println(args[i]);
5. }
6. }
Output
sonoo
jaiswal
1
3
abc
235) What is an applet?
An applet is a small java program that runs inside the browser and generates
dynamic content. It is embedded in the webpage and runs on the client side. It
is secured and takes less response time. It can be executed by browsers
running under many platforms, including Linux, Windows, Mac Os, etc.
However, the plugins are required at the client browser to execute the applet.
The following image shows the architecture of Applet.
o init()
o start()
o paint()
o stop()
o destroy()
236) Can you write a Java class that could be used both
as an applet as well as an application?
Yes. Add a main() method to the applet.
1. //Employee.java
2. package mypack;
3. public class Employee implements java.io.Serializable{
4. private int id;
5. private String name;
6. public Employee(){}
7. public void setId(int id){this.id=id;}
8. public int getId(){return id;}
9. public void setName(String name){this.name=name;}
10. public String getName(){return name;}
11. }
Output:
1. import java.util.*;
2. public class BinarySearch {
3. public static void main(String[] args) {
4. int[] arr = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100};
5. int item, location = -1;
6. System.out.println("Enter the item which you want to search");
7. Scanner sc = new Scanner(System.in);
8. item = sc.nextInt();
9. location = binarySearch(arr,0,9,item);
10. if(location != -1)
11. System.out.println("the location of the item is "+location);
12. else
13. System.out.println("Item not found");
14. }
15. public static int binarySearch(int[] a, int beg, int end, int item)
16. {
17. int mid;
18. if(end >= beg)
19. {
20. mid = (beg + end)/2;
21. if(a[mid] == item)
22. {
23. return mid+1;
24. }
25. else if(a[mid] < item)
26. {
27. return binarySearch(a,mid+1,end,item);
28. }
29. else
30. {
31. return binarySearch(a,beg,mid-1,item);
32. }
33. }
34. return -1;
35. }
36. }
Output:
Output:
1. import java.util.Scanner;
2.
3. public class Leniear_Search {
4. public static void main(String[] args) {
5. int[] arr = {10, 23, 15, 8, 4, 3, 25, 30, 34, 2, 19};
6. int item,flag=0;
7. Scanner sc = new Scanner(System.in);
8. System.out.println("Enter Item ?");
9. item = sc.nextInt();
10. for(int i = 0; i<10; i++)
11. {
12. if(arr[i]==item)
13. {
14. flag = i+1;
15. break;
16. }
17. else
18. flag = 0;
19. }
20. if(flag != 0)
21. {
22. System.out.println("Item found at location" + flag);
23. }
24. else
25. System.out.println("Item not found");
26.
27. }
28. }
Output:
Enter Item ?
23
Item found at location 2
Enter Item ?
22
Item not found
Output:
Sorted array
23
23
23
34
45
65
67
89
90
101
Output:
Output:
Output:
1. import java.util.LinkedList;
2. import java.util.Queue;
3.
4. public class DiffOddEven {
5.
6. //Represent a node of binary tree
7. public static class Node{
8. int data;
9. Node left;
10. Node right;
11.
12. public Node(int data){
13. //Assign data to the new node, set left and right children to null
Output:
1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously.
Multithreading is used to obtain the multitasking. It consumes less memory
and gives the fast and efficient performance. Its main advantages are:
1. New: In this state, a Thread class object is created using a new operator,
but the thread is not alive. Thread doesn't start until we call the start()
method.
2. Runnable: In this state, the thread is ready to run after calling the start()
method. However, the thread is not yet selected by the thread
scheduler.
3. Running: In this state, the thread scheduler picks the thread from the
ready state, and the thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or
it is waiting for the other thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when the
run() method exits.
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) The wait() method releases the lock. The sleep() method doesn't release the lock.
Output
thread is executing now........
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at Multithread1.main(Multithread1.java:13)
When the multiple threads try to do the same task, there is a possibility of an
erroneous result, hence to remove this issue, Java uses the process of
synchronization which allows only one thread to be executed at a time.
Synchronization can be achieved in three ways:
o Avoid Nested lock: Nested lock is the common reason for deadlock as
deadlock occurs when we provide locks to various threads so we
should give one lock to only one thread at some particular time.
o Avoid unnecessary locks: we must avoid the locks which are not
required.
o Using thread join: Thread join helps to wait for a thread until another
thread doesn't finish its execution so we can avoid deadlock by
maximum use of join method.
o Synchronization
o Using Volatile keyword
o Using a lock based mechanism
o Use of atomic wrapper classes
o Arrays are always of fixed size, i.e., a user can not increase or decrease
the length of the array according to their requirement or at runtime,
but In Collection, size can be changed dynamically as per need.
o Arrays can only store homogeneous or similar type objects, but in
Collection, heterogeneous objects can be stored.
o Arrays cannot provide the ?ready-made? methods for user
requirements as sorting, searching, etc. but Collection includes
readymade methods to use.
Syntax:
Syntax:
Syntax:
Syntax:
Syntax:
3) ArrayList increases its size by 50% of the Vector increases its size by doubling the
array size. size.
4) ArrayList is not ?thread-safe? as it is not Vector list is ?thread-safe? as it?s every met
synchronized. synchronized.
5) ArrayList takes less memory overhead LinkedList takes more memory overhead, as it stores
as it stores only object the object as well as the address of that object.
1) The Iterator traverses the elements in ListIterator traverses the elements in backward and
the forward direction only. forward directions both.
2) The Iterator can be used in List, Set, ListIterator can be used in List only.
and Queue.
3) The Iterator can only perform remove ListIterator can perform ?add,? ?remove,? and ?set?
operation while traversing the operation while traversing the collection.
collection.
1) The Iterator can traverse legacy and non- Enumeration can traverse only legacy
legacy elements. elements.
4) The Iterator can perform remove operation The Enumeration can perform only traverse
while traversing the collection. operation on the collection.
7) What is the difference between Iterator and
Enumeration?
o The List can contain duplicate elements whereas Set includes unique
items.
o The List is an ordered collection which maintains the insertion order
whereas Set is an unordered collection which does not preserve the
insertion order.
o The List interface contains a single legacy class which is Vector class
whereas Set interface does not have any legacy class.
o The List interface can allow n number of null values whereas Set
interface only allows a single null value.
o Set contains values only whereas Map contains key and values both.
o Set contains unique values whereas Map can contain unique Keys with
duplicate values.
o Set holds a single number of null value whereas Map can include a
single null key with n number of null values.
o HashSet contains only values whereas HashMap includes the entry (key,
value). HashSet can be iterated, but HashMap needs to convert into Set
to be iterated.
o HashSet implements Set interface whereas HashMap implements the
Map interface
o HashSet cannot have any duplicate value whereas HashMap can
contain duplicate values with unique keys.
o HashSet contains the only single number of null value whereas
HashMap can hold a single null key with n number of null values.
2) HashMap can contain one null key and multiple Hashtable cannot contain any null key or null
null values. value.
3) HashMap is not ?thread-safe,? so it is useful for Hashtable is thread-safe, and it can be shared
non-threaded applications. between various threads.
4) 4) HashMap inherits the AbstractMap class Hashtable inherits the Dictionary class.
Collections?
The differences between the Collection and Collections are given below.
4) If we implement the Comparable interface, The The actual class is not changed.
actual class is modified.
Syntax:
SN Array ArrayList
1 The Array is of fixed size, means we cannot ArrayList is not of the fixed size we can change
resize the array as per need. the size dynamically.
3 Arrays can store primitive data types as well ArrayList cannot store the primitive data types it
as objects. can only store the objects.
1. Arrays.asList(item)
1. List_object.toArray(new String[List_object.size()])
1. import java.util.ArrayList;
2. import java.util.Collection;
3. import java.util.Collections;
4. import java.util.Iterator;
5. import java.util.List;
6. public class ReverseArrayList {
7. public static void main(String[] args) {
8. List list = new ArrayList<>();
9. list.add(10);
10. list.add(50);
11. list.add(30);
12. Iterator i = list.iterator();
13. System.out.println("printing the list....");
14. while(i.hasNext())
15. {
16. System.out.println(i.next());
17. }
18. Iterator i2 = list.iterator();
19. Collections.reverse(list);
20. System.out.println("printing list in reverse order....");
21. while(i2.hasNext())
22. {
23. System.out.println(i2.next());
24. }
25. }
26. }
Output
1. import java.util.ArrayList;
2. import java.util.Collection;
3. import java.util.Collections;
4. import java.util.Comparator;
5. import java.util.Iterator;
6. import java.util.List;
7.
8. public class ReverseArrayList {
9. public static void main(String[] args) {
10. List list = new ArrayList<>();
11. list.add(10);
12. list.add(50);
13. list.add(30);
14. list.add(60);
15. list.add(20);
16. list.add(90);
17.
18. Iterator i = list.iterator();
19. System.out.println("printing the list....");
20. while(i.hasNext())
21. {
22. System.out.println(i.next());
23. }
24.
25. Comparator cmp = Collections.reverseOrder();
26. Collections.sort(list,cmp);
27. System.out.println("printing list in descending order....");
28. Iterator i2 = list.iterator();
29. while(i2.hasNext())
30. {
31. System.out.println(i2.next());
32. }
33.
34. }
35. }
Output
1) What is JDBC?
JDBC is a Java API that is used to connect and execute the query to the
database. JDBC API uses JDBC drivers to connect to the database. JDBC API
can be used to access tabular data stored into any relational database.
The forName() method of the Class class is used to register the driver
class. This method is used to load the driver class dynamically. Consider
the following example to register OracleDriver class.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
o Creating connection:
1. Statement stmt=con.createStatement();
o Closing connection:
1. con.close();
2.
Interfaces:
Classes:
o Clob: Clob stands for Character large object. It is a data type that is
used by various database management systems to store character files.
It is similar to Blob except for the difference that BLOB represent binary
data such as images, audio and video files, etc. whereas Clob represents
character stream data such as character files, etc.
Statements Explanation
Statement Statement is the factory for resultset. It is used for general purpose access
database. It executes a static SQL query at runtime.
Statement PreparedStatement
In the case of Statement, the query is compiled each In the case of PreparedStatemen
time we run the program. query is compiled only once.
The Statement is mainly used in the case when we need PreparedStatement is used when we
to run the static query at runtime. to provide input parameters to the
at runtime.
The execute method can be used for The executeQuery The executeUpdate metho
any SQL statements(Select and method can be used only be used to update/delete
Update both). with the select statement. operations in the database.
Type Description
ResultSet.TYPE_SCROLL_SENSITIVE The cursor can move in both the direction. The Resul
sensitive to the changes made by the others to the datab
ResultSet RowSet
ResultSet cannot be serialized RowSet is disconnected from the database and can be serialize
as it maintains the connection
with the database.
ResultSet is returned by the Rowset Interface extends ResultSet Interface and returned by
executeQuery() method of the RowSetProvider.newFactory().createJdbcRowSet() method.
Statement Interface.
More details.
More details.
More details.
More details.
1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. DatabaseMetaData dbmd=con.getMetaData();
10.
11. System.out.println("Driver Name: "+dbmd.getDriverName());
12. System.out.println("Driver Version: "+dbmd.getDriverVersion());
13. System.out.println("UserName: "+dbmd.getUserName());
14. System.out.println("Database Product Name: "+dbmd.getDatabaseProd
uctName());
15. System.out.println("Database Product Version: "+dbmd.getDatabasePro
ductVersion());
16.
17. con.close();
18. }catch(Exception e){ System.out.println(e);}
19. }
20. }
Output
More details.
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@local
host:1521:xe","system","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
10. stmt.addBatch("insert into user420 values(191,'umesh',50000)");
11.
12. stmt.executeBatch();//executing the batch
13.
14. con.commit();
15. con.close();
16. }}
More details.
o Row and Key Locks: These type of locks are used when we update the
rows.
o Page Locks: These type of locks are applied to a page. They are used in
the case, where a transaction remains in the process and is being
updated, deleting, or inserting some data in a row of the table. The
database server locks the entire page that contains the row. The page
lock can be applied once by the database server.
o Table locks: Table locks are applied to the table. It can be applied in
two ways, i.e., shared and exclusive. Shared lock lets the other
transactions to read the table but not update it. However, The exclusive
lock prevents others from reading and writing the table.
o Database locks: The Database lock is used to prevent the read and
update access from other transactions when the database is open.
1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into imgtable val
ues(?,?)");
11. ps.setString(1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\g.jpg");
14. ps.setBinaryStream(2,fin,fin.available());
15. int i=ps.executeUpdate();
16. System.out.println(i+" records affected");
17.
18. con.close();
19. }catch (Exception e) {e.printStackTrace();}
20. }
21. }
Consider the following example to retrieve the image from the table.
1. import java.sql.*;
2. import java.io.*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("select * from imgtable")
;
11. ResultSet rs=ps.executeQuery();
12. if(rs.next()){//now on 1st row
13.
14. Blob b=rs.getBlob(2);//2 means 2nd column data
15. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
16.
17. FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
18. fout.write(barr);
19.
20. fout.close();
21. }//end of if
22. System.out.println("ok");
23.
24. con.close();
25. }catch (Exception e) {e.printStackTrace(); }
26. }
27. }
1. Servlet is loaded
2. servlet is instantiated
3. servlet is initialized
4. service the request
5. servlet is destroyed
Get Post
1) Limited amount of data can be sent because data Large amount of data can be sent becaus
is sent in header. is sent in body.
2) Not Secured because data is exposed in URL bar. Secured because data is not exposed i
bar.
4) Idempotent Non-Idempotent
5) It is more efficient and used than Post It is less efficient and used
7) What is difference between PrintWriter and
ServletOutputStream?
PrintWriter is a character-stream class where as ServletOutputStream is a byte-
stream class. The PrintWriter class can be used to write only character-based
information whereas ServletOutputStream class can be used to write primitive
values as well as character-based information.
o RequestDispacher interface
o sendRedirect() method etc.
1. RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
2. rd.forward(request,response);
12) Difference between forward() method and
sendRedirect() method ?
1) forward() sends the same request 1) sendRedirect() method sends new request always beca
to another resource. uses the URL bar of the browser.
3) forward() method works within the 3) sendRedirect() method works within and outside the s
server only.
more details...
more details...
more details...
more details...
more details...
To create war file from console, you can write following code.
Now all the files of current directory will be converted into abc.war file.
more details...
more details...
more details...
more details...
A JSP page is internally converted into the servlet. JSP has access to the entire
family of the Java API including JDBC API to access enterprise database. Hence,
Java language syntax has been used in the java server pages (JSP). The JSP
pages are more accessible to maintain than Servlet because we can separate
designing and development. It provides some additional features such as
Expression Language, Custom Tags, etc.
More details.
Method Description
o Better performance.
o The compilation of JSP is done before it is processed by the server
which eradicates the need for loading of interpreter and code script
each time.
o JSP has access to all-powerful enterprises.
Easy to maintain: JSP can be easily managed because we can easily
separate our business logic with presentation logic. In Servlet
technology, we mix our business logic with the presentation logic.
o JSP can also be used in combination with servlets.
1) out JspWriter
2) request HttpServletRequest
3) response HttpServletResponse
4) config ServletConfig
5) session HttpSession
6) application ServletContext
7) pageContext PageContext
8) page Object
9) exception Throwable
More details.
1) The include directive includes the content 1) The include action includes the content at re
at page translation time. time.
2) The include directive includes the original 2) The include action doesn't include the o
content of the page, so page size increases at content rather invokes the include() meth
runtime Vendor provided class.
3) It's better for static pages. 3) 3) It's better for dynamic pages.
1. <%
2. response.setHeader("Cache-Control","no-store");
3. response.setHeader("Pragma","no-cache");
4. response.setHeader ("Expires", "0"); //prevents caching at the proxy serv
er
5. %>
More details.
o By include directive
o By include action
13) How can we forward the request from JSP page to
the servlet?
Yes of course! With the help of "forward action" tag, but we need to give the
URL-pattern of the servlet.
More details.
More details.
o Boolean
o Integer
o Floating point
o String
o Null
o page
o request
o session
o application
More details.
1. core tags
2. sql tags
3. xml tags
4. internationalization tags
5. functions tags
More details.
1. jsp:useBean
2. jsp:setProperty
3. jsp:getProperty
More details.
There are many implicit objects, operators and reserve words in EL.
pageScope it maps the given attribute name with the value set in the page scope
requestScope it maps the given attribute name with the value set in the request scope
sessionScope it maps the given attribute name with the value set in the session scope
applicationScope it maps the given attribute name with the value set in the application scope
param it maps the request parameter to the single value
1) What is Spring?
It is a lightweight, loosely coupled and integrated framework for developing
enterprise applications in java.
1. Predefined Templates
2. Loose Coupling
3. Easy to test
4. Lightweight
5. Fast Development
6. Powerful Abstraction
7. Declarative support
More details...
1. Test
2. Spring Core Container
3. AOP, Aspects and Instrumentation
4. Data Access/Integration
5. Web
More details...
More details...
1. BeanFactory
2. ApplicationContext
More details...
7) What is the difference between BeanFactory and
ApplicationContext?
BeanFactory is the basic container whereas ApplicationContext is
the advanced container. ApplicationContext extends the BeanFactory
interface. ApplicationContext provides more facilities than BeanFactory such
as integration with spring AOP, message resource handling for i18n etc.
2) Desn't override the setter property Overrides the constructor property if bot
defined.
3) Creates new instance if any modification Doesn't create new instance if you chang
occurs property value
2) byName injects the bean based on the property name. It uses setter method.
3) byType injects the bean based on the property type. It uses setter method.
1) singleton The bean instance will be only once and same instance will be returned
IOC container. It is the default scope.
2) prototype The bean instance will be created each time when requested.
5) globalsession The bean instance will be created per HTTP global session. It can be u
portlet context only.
More details...
1. JdbcTemplate
2. SimpleJdbcTemplate
3. NamedParameterJdbcTemplate
4. SimpleJdbcInsert
5. SimpleJdbcCall
More details...
1. ResultSetExtractor
2. RowMapper
16) What is the advantage of
NamedParameterJdbcTemplate?
NamedParameterJdbcTemplate class is used to pass value to the named
parameter. A named parameter is better than ? (question mark of
PreparedStatement).
It is better to remember.
More details...
More details...
More details...
1. Before Advice
2. After Advice
3. After Returning Advice
4. Throws Advice
5. Around Advice
1. Spring AOP
2. Apache AspectJ
3. JBoss AOP
1) What is hibernate?
Hibernate is an open-source and lightweight ORM tool that is used to store,
manipulate, and retrieve data from the database.
2) What is ORM?
ORM is an acronym for Object/Relational mapping. It is a programming
strategy to map object with the data stored in the database. It simplifies data
creation, data manipulation, and data access.
more
details...
o Configuration
o SessionFactory
o Session
o Query
o Criteria
o Transaction
o DB2
o MySQL
o Oracle
o Sybase SQL Server
o Informix Dynamic Server
o HSQL
o PostgreSQL
o FrontBase
8) List the key components of Hibernate.
Key components of Hibernate are:
o Configuration
o Session
o SessionFactory
o Criteria
o Query
o Transaction
Session.createSQLQuery
Session.createQuery
more details...
It provides methods to store, update, delete or fetch data from the database
such as persist(), update(), delete(), load(), get() etc.
more details...
1) returns the identifier (Serializable) of the Return nothing because its return type is
instance. void.
2) get() method always hit the database. load() method doesn't hit the database.
3) It returns the real object, not the proxy. It returns proxy object.
4) It should be used if you are not It should be used if you are sure that instance
sure about the existence of instance. exists.
The differences between get() and load() methods are given below.
2) update() should be used if the session doesn't contain merge() should be used if you don't
an already persistent state with the same id. It means know the state of the session, means
an update should be used inside the session only. After you want to make the modification at
closing the session, it will throw the error. any time.
The differences between update() and merge() methods are given below.
1. ...
2. SessionFactory factory = cfg.buildSessionFactory();
3. Session session1 = factory.openSession();
4.
5. Employee e1 = (Employee) session1.get(Employee.class, Integer.valueO
f(101));//passing id of employee
6. session1.close();
7.
8. e1.setSalary(70000);
9.
10. Session session2 = factory.openSession();
11. Employee e2 = (Employee) session1.get(Employee.class, Integer.valueO
f(101));//passing same id
12.
13. Transaction tx=session2.beginTransaction();
14. session2.merge(e1);
15.
16. tx.commit();
17. session2.close();
Then, we opened another session and loaded the same Employee instance. If
we call merge in session2, changes of e1 will be merged in e2.
more details...
1. ...
2. SessionFactory factory = cfg.buildSessionFactory();
3. Session session1 = factory.openSession();
4. Transaction tx=session2.beginTransaction();
5.
6. Employee e1 = (Employee) session1.get(Employee.class, Integer.valueO
f(101));
7.
8. e1.setSalary(70000);
9.
10. tx.commit();
11. session1.close();
Here, after getting employee instance e1 and we are changing the state of e1.
After changing the state, we are committing the transaction. In such a case,
the state will be updated automatically. This is known as dirty checking in
hibernate.
1. One to One
2. One to Many
3. Many to One
4. Many to Many
Formerly MySQL was initially owned by a for-profit firm MySQL AB, then Sun
Microsystems bought it, and then Oracle bought Sun Microsystems, so Oracle
currently owns MySQL.
The Lamp is a platform used for web development. The Lamp uses Linux,
Apache, MySQL, and PHP as an operating system, web server, database &
object-oriented scripting language. And hence abbreviated as LAMP.
o Flexible structure
o High performance
o Manageable and easy to use
o Replication and high availability
o Security and storage management
o Drivers
o Graphical Tools
o MySQL Enterprise Monitor
o MySQL Enterprise Security
o JSON Support
o Replication & High-Availability
o Manageability and Ease of Use
o OLTP and Transactions
o Geo-Spatial Support
A PHP script is required to store and retrieve the values inside the database.
MySQL has very stable versions available, as MySQL has been in the market
for a long time. All bugs arising in the previous builds have been continuously
removed, and a very stable version is provided after every update.
The MySQL database server is very fast, reliable, and easy to use. You can
easily use and modify the software. MySQL software can be downloaded free
of cost from the internet.
o MyISAM
o Heap
o Merge
o INNO DB
o ISAM
8) How to install MySQL?
Installing MySQL on our system allows us to safely create, drop, and test web
applications without affecting our live website's data. There are many ways to
use MySQL on our system, but the best way is to install it manually. The
manual installation allows us to learn more about the system and provides
more control over the database. To see the installation steps of MySQL in
Windows goes to the below link:
https://www.javatpoint.com/how-to-install-mysql
1. mysql -v
Following is the syntax to define a foreign key using CREATE TABLE OR ALTER
TABLE statement:
1. [CONSTRAINT constraint_name]
2. FOREIGN KEY [foreign_key_name] (col_name, ...)
3. REFERENCES parent_tbl_name (col_name,...)
We can find the command-line client tool in the bin directory of the MySQL's
installation folder. To invoke this program, we need to navigate the
installation folder's bin directory and type the below command:
1. mysql
Next, we need to run the below command to connect to the MySQL Server:
1. shell>mysql -u root -p
Finally, type the password for the selected user account root and press Enter:
After successful connection, we can use the below command to use the:
1. USE database_name;
Next, open a Command Prompt and navigate to the MySQL directory. Now,
copy the following folder and paste it in our DOS command and press the
Enter key.
1. mysqld --init-file=C:\\mysql-notepadfile.txt
Finally, we can log into the MySQL server as root using this new password.
After launches the MySQL server, it is to delete the C:\myswl-init.txt file to
ensure the password change.
If we want to change more than one table name, use the below syntax:
Now, use the below command to import the data into the newly created
database:
Suppose the column's current name is S_ID, but we want to change this with a
more appropriate title as Stud_ID. We will use the below statement to change
its name:
If we want to insert more than one rows into a table, use the below syntax:
It is noted that if we have not specified the WHERE clause with the syntax, this
statement will remove all the records from the given table.
o Inner Join
o Left Join
o Right Join
o Cross Join
Let's say Student has (stud_id, name) columns, Marks has (school_id, stud_id,
scores) columns, and Details has (school_id, address, email) columns.
This approach is similar to the way we join two tables. The following query
returns result from three tables:
It is another approach to join more than two tables. In the above tables, we
have to create a parent-child relationship. First, create column X as a primary
key in one table and as a foreign key in another table. Therefore, stud_id is the
primary key in the Student table and will be a foreign key in the Marks table.
Next, school_id is the primary key in the Marks table and will be a foreign key
in the Details table. The following query returns result from three tables:
1. SELECT name, scores, address, email
2. FROM Student s, Marks m, Details d
3. WHERE s.stud_id = m.stud_id AND m.school_id = d.school_id;
1. UPDATE table_name
2. SET field1=new-value1, field2=new-value2, ...
3. [WHERE Clause]
This statement can return one or more value through parameters or may not
return any result. The following example explains it more clearly:
1. DELIMITER $$
2. CREATE PROCEDURE get_student_info()
3. BEGIN
4. SELECT * FROM Student_table;
5. END$$
After the release of MySQL version 8, we can use the below command to clear
the command line screen:
1. mysql> SYSTEM CLS;
4. FROM information_schema.tables
5. WHERE table_schema = 'testdb'
6. GROUP BY table_schema;
If we want to check the size of the table in a specific database, use the
following statement:
3. FROM information_schema.TABLES
4. WHERE table_schema = 'testdb'
5. ORDER BY (data_length + index_length) DESC;
It will return the output as follows:
Suppose we have a book and want to get information about, say, searching.
Without indexing, it is required to go through all pages one by one, until the
specific topic was not found. On the other hand, an index contains a list of
keywords to find the topic mentioned on pages. Then, we can flip to those
pages directly without going through all pages.
1. SELECT salary
2. FROM (SELECT salary FROM employees ORDER BY salary DESC LIMIT
2) AS Emp ORDER BY salary LIMIT 1;
There are some other ways to find the second highest salary in MySQL, which
are given below:
This statement uses subquery and IN clause to get the second highest salary:
1. SELECT MAX(salary)
2. FROM employees
3. WHERE salary NOT IN ( SELECT Max(salary) FROM employees);
This query uses subquery and < operator to return the second highest salary:
1. Before Insert
2. After Insert
3. Before Update
4. After Update
5. Before Delete
6. After Delete
46) What is the heap table?
Tables that are present in memory is known as HEAP tables. When you create
a heap table in MySQL, you should need to specify the TYPE as HEAP. These
tables are commonly known as memory tables. They are used for high-speed
storage on a temporary basis. They do not allow BLOB or TEXT fields.
1. TINYBLOB
2. BLOB
3. MEDIUMBLOB
4. LONGBLOB
The differences among all these are the maximum length of values they can
hold.
1. TINYTEXT
2. TEXT
3. MEDIUMTEXT
4. LONGTEXT
Heap tables are found in memory that is used for high-speed storage
temporarily. They do not allow BLOB or TEXT fields.
Temporary tables:
The temporary tables are used to keep the transient data. Sometimes it is
beneficial in cases to hold temporary data. The temporary table is deleted
after the current client session terminates.
Main differences:
The heap tables are shared among clients, while temporary tables are not
shared.
Heap tables are just another storage engine, while for temporary tables, you
need a special privilege (create temporary table).
Mysql_pconnect:
1. SELECT CURRENT_DATE();
Change the root username and password Restrict or disable remote access.
58) How to change a password for an existing user via
mysqladmin?
Mysqladmin -u root -p password "newpassword".
SELECT NOW();
SELECT CURRENT_DATE();
ENUMs are used to limit the possible values that go in the table:
For example:
For example:
Example:
Example:
The following statement retrieves all rows where column employee_name
contains the text 1000 (example salary):
1. Select employee_name
2. From employee
3. Where employee_name REGEXP '1000'
4. Order by employee_name
1. mysql;
2. mysql mysql.out;
o PHP Driver
o JDBC Driver
o ODBC Driver
o C WRAPPER
o PYTHON Driver
o PERL Driver
o RUBY Driver
o CAP11PHP Driver
o Ado.net5.mxz
Data Control Languages (DCL) are related to the Grant and permissions. In
short, the authorization to access any part of the database is defined by these.
It is used to create stand alone spring based application that you can just run
because it needs very little spring configuration.
o Web Development
o SpringApplication
o Application events and listeners
o Admin features
It can be integrate with Spring Framework and ideal for HTML5 Java web
applications.
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
4. </dependency>
You should alert enough to answer this question. You should start with an
easy and confident tone and answer in a proper manner. It should not be
scripted. Always remember, you are not giving the interview to a robot so
your articulation, your pronunciation of each word should be clear and
confident.
A good way:
Analyze your interviewer interests.
Possible Answer 1
Possible Answer 2
Possible Answer 3
Before answering this question, take your own time an answer in the way that
convinces the interviewer. Explain your qualities according to the above-stated
points.
Possible Answer 1
Possible Answer 2
Possible Answer 1
Possible Answer 2
Possible Answer 3
"Work is more important for me. Working just for money may
not be fulfilled if I don't feel satisfied with my job. My work
makes me stay productive, and money would naturally come
along well."
Possible Answer 4
Possible Answer 1
Possible Answer 2
Sir, it's a career move. I have learned a lot from my last job,
but now I am looking for new challenges to broaden my
horizons and to gain a new skill-set.
7) Why should we hire you?
Tell your qualifications and highlight that points which makes you unique.
Possible Answer 1
Possible Answer 2
Possible Answer 3
Possible Answer 4
Possible Answer 1
Possible Answer 2
Possible Answer 3
Possible Answer 2
Possible Answer 3
Possible Answer 4
Possible Answer 1
Possible Answer 2
Possible Answer 3
"I experienced my greatest achievement when I worked as a
website manager for an entertainment outlet. My team was
under pressure and the website was struggling at the time,
and I was tasked with forming a strategy to increase traffic.
Possible Answer 1
Possible Answer 2
Possible Answer 1
Possible Answer 2
My greatest strengths would be
my intelligence and thoughtfulness . I believe that in every
work environment you need to process every step and be
detailed in your work.
Possible Answer 3
Possible Answer 4
Possible Answer 5
Possible Answer 6
Possible Answer 2
For Example:
Possible Answer 1
"To become an asset for an organization, we have to punctual,
dedicated, quickly adapt of the environment and positive
working attitude I have all of these qualities so I will prove an
asset for this company."
Possible Answer 2
Possible Answer 3
Possible Answer 1
Possible Answer 2
You should never claim that you did not apply to other company. Despite this,
you can say that -
For Example
These are some positive words. You can use it but be sure that you are
judging with the word.
Or you can say that: confidence is an internal belief that I am a right person
for this job and overconfidence is thought that I am only the right person for
this job.
Smart work and hard work are related to each other. Without
being a hard worker, we can't be a smart worker. Smart work
comes from the hard work. That means everyone has to specialize
in his work to become a smart worker. So, all of us have to do hard
work to achieve smart work.
25) Don't you think that you are overqualified for this
position?
This is trick of the interviewer to trap you and judge how boasting you are?
So, be alert to answer this question and don't even hint to the interviewer that
you are overqualified although you are.
For example:
"I would say everyone has blind spots and I would too that's
why I believe in teamwork because when you are a team, you
can point out the blind spots of other people, and they will
also do the same for you."
Note: "don't admit failure as a blind spot. Failure is not a blind spot."
Possible Answer 1
Possible Answer 2
Possible Answer 1:
Possible Answer 2: If you did not face any disappointment in your life
30) What was the most difficult decision you have made
in your past life?
This question is asked to judge your decision-making capabilities. The
interviewer wants to know, how you take a decision in tough times.
Possible Answer 1
Possible Answer 2
Possible Answer 3
Answer this question according to your sense, your knowledge about the
book. Only named the books you have really read. You should choose
something from a reputable author that your interviewer has probably heard
of.
Talk about the mistake, but it is also important to convince the interviewer
that you never make the same mistake again.
For example:
I think the worst mistake I ever made at work was in my first ever
job - five years ago now. A more senior member of the team
seemed to take an instant dislike to me from the start, and one day
she was particularly unpleasant to me in front of several
colleagues.
Rather than let the situation carry on, I chose to have a quiet word
with this lady to find out what her problem was with me and to see
if we could put it behind us. It turned out it was nothing personal;
she just resented the fact that a friend of hers had also been
interviewed for my position and had been turned down. Once we
had got matters out into the air, her behavior changed, and we got
on quite well after that. However, I certainly learned a lot from
experience. I learned that careful communication is vital in
managing interpersonal relationships and that if I have a problem
with someone, it's always best to talk it over with them rather than
with someone else.
I would try to find out exactly what the problem was, and
evaluate if there was something I could do to make it right.
Possible Answer 2
I would try to find out exactly what the problem was, and
evaluate if there was something I could do to make it right.
Possible Answer 2
Possible Answer 2
There is only one difference between the group and the team.
That is unity. Any set of people who stand together without
any purpose or goal can be called as Group. Whereas, when
more than 2 people work towards a common goal, can be
called as a Team. For example: If you assign work to a group,
then the work will be divided between the members and each
member will work out their part, without any coordination
with the other members of the group. On the other hand, if
you assign a project to a team, they will collectively take the
responsibility and work together with the goal to achieve the
desired result. In a team, the members will cooperate and
coordinate with each other at all times.
41) What will you do if you don't get this position?
Possible Answer 1
Possible Answer 2
Possible Answer 1
Possible Answer 2
Possible Answer 1
Possible Answer 2
Possible Answer 3
I have exceptional organizational skills. In my last job, I
created a project which was termed as quite creative by the
clients. I think my technical skills make me stand alone from
all other candidates.
46) Describe the three things that are most important for
you in a job?
Possible Answer 1
Possible Answer 2
For Example
Possible Answer 2
For Example
Possible Answer 1
Possible Answer 2
First of all thank you very much, for being so much polite &
friendly to me throughout the session, that I can express
myself so easily. Can you please tell me that what are the
qualities you are expecting from fresher like us & I want to
know, if am selected, then what should I improve before I join
your company, if I am not selected, your opinion will help me
to the upcoming interview.
o Python
o Java
o Go
o Dart
o C++
o C#
o Ruby
o Inheritance
o Encapsulation
o Polymorphism
o Data Abstraction
Disadvantages of OOP
It is based on objects rather than It provides a logical structure to a program in which the
functions and procedures. program is divided into functions.
It provides more security as it has a data It provides less security as it does not support the data
hiding feature. hiding feature.
o Encapsulation
o Inheritance
o Polymorphism
o Abstraction
o All predefined types are objects
o All user-defined types are objects
o All operations performed on objects must be only through methods
exposed to the objects.
Class Object
It is conceptual. It is real.
It binds data and methods together into a single It is just like a variable of a class.
unit.
It does not occupy space in the memory. It occupies space in the memory.
It uses the keyword class when declared. It uses the new keyword to create an object.
A class can exist without any object. Objects cannot exist without a class.
12) What are the key differences between class and
structure?
Class Structure
Class is a group of common objects that shares common The structure is a collection of different
properties. data types.
It deals with data members and member functions. It deals with data members only.
It's members are private by default. It's members are public by default.
The keyword class defines a class. The keyword struct defines a structure.
Useful while dealing with the complex data structure. Useful while dealing with the small data
structure.
Constructor Method
Constructor has the same name as the class name. The method name and class name are not the
same.
It is a special type of method that is used to It is a set of instructions that can be invoked at
initialize an object of its class. any point in a program.
It is invoked implicitly when we create an object of It gets executed when we explicitly called it.
the class.
It does not have any return type. It must have a return type.
Java compiler automatically provides a default Java compiler does not provide any method by
constructor. default.
It is less secure because there is no proper way to hide It provides more security.
data.
Modification and extension of code are not easy. We can easily modify and extend code.
Examples of POP are C, VB, FORTRAN, Pascal, etc. Examples of OOPs are C++, Java, C#, .NET,
etc.
Recoverable/ Exception can be recovered by using the try-catch An error cannot be recovered.
Irrecoverable block.
Type It can be classified into two categories i.e. checked All errors in Java are unchecked.
and unchecked.
Known or Only checked exceptions are known to the Errors will not be known to the
unknown compiler. compiler.
Runtime Polymorphism
It creates a new object as a copy of an It assigns the value of one object to another objec
existing object. of which already exist.
The copy constructor is used when a new It is used when we want to assign an existing obje
object is created with some existing object. new object.
Both the objects use separate memory Both objects share the same memory but use th
locations. different reference variables that point to the
location.
If no copy constructor is defined in the If the assignment operator is not overloaded the
class, the compiler provides one. bitwise copy will be made.
Inheritance Polymorphism
Inheritance is one in which a derived class Polymorphism is one that you can define in different
inherits the already existing class's forms.
features.
It refers to using the structure and It refers to changing the behavior of a superclass in the
behavior of a superclass in a subclass. subclass.
It can be single, hybrid, multiple, There are two types of polymorphism compile time and
hierarchical, multipath, and multilevel run time.
inheritance.
It supports code reusability and reduces It allows the object to decide which form of the function
lines of code. to be invoked at run-time (overriding) and compile-time
(overloading).
Objects that are independent of one another and do not directly modify the
state of other objects is called loosely coupled. Loose coupling makes the
code more flexible, changeable, and easier to work with.
Objects that depend on other objects and can modify the states of other
objects are called tightly coupled. It creates conditions where modifying the
code of one object also requires changing the code of other objects. The
reuse of code is difficult in tight coupling because we cannot separate the
code.
new: Hides the original method (which doesn't have to be virtual), providing
different functionality. This should only be used where it is absolutely
necessary.
When you hide a method, you can still access the original method by
upcasting to the base class. This is useful in some scenarios, but dangerous.
If a method with the same method signature is presented in both child and
parent class is known as method overriding. The methods must have the
same number of parameters and the same type of parameter. It overrides the
value of the parent class method. It is also known as runtime polymorphism.
For example, consider the following program.
1. class Dog
2. {
3. public void bark()
4. {
5. System.out.println("woof ");
6. }
7. }
8. class Hound extends Dog
9. {
10. public void sniff()
11. {
12. System.out.println("sniff ");
13. }
14. //overrides the method bark() of the Dog class
15. public void bark()
16. {
17. System.out.println("bowl");
18. }
19. }
20. public class OverridingExample
21. {
22. public static void main(String args[])
23. {
24. Dog dog = new Hound();
25. //invokes the bark() method of the Hound class
26. dog.bark();
27. }
28. }
High cohesion often associates with loose coupling and vice versa.
o At home a person can play the role of father, husband, and son.
o At the office the same person plays the role of boss or employee.
o In public transport, he plays the role of passenger.
o In the hospital, he can play the role of doctor or patient.
o At the shop, he plays the role of customer.
o Abstract class
o Abstract method
1. class OverloadMain
2. {
3. public static void main(int a) //overloaded main method
4. {
5. System.out.println(a);
6. }
7. public static void main(String args[])
8. {
9. System.out.println("main method invoked");
10. main(6);
11. }
12. }
~Navnath
THANK YOU !!!