Java Notes
Java Notes
Content :
Inheritance – Inheritance hierarchies super and sub classes, Member access rules, super
keyword, preventing inheritance: final classes and methods, the Object class and its methods.
Polymorphism – dynamic binding, method overriding, abstract classes and methods. Interfaces-
Interfaces Vs Abstract classes, defining an interface, implement interfaces, accessing
implementations through interface references, extending interface. Inner classes- Uses of inner
classes, local inner classes, anonymous inner classes, static inner classes, examples. Packages-
Defining, creating and accessing a package, Understanding CLASSPATH, importing packages
Exception handling- Dealing with errors, benefits of exception handling, the classification of
exceptions- exception hierarchy, checked exceptions and unchecked exceptions, usage of try,
catch, throw, throws and finally, rethrowing exceptions, exception specification, built in
exceptions, creating own exception sub classes. Multithreading – Differences between multiple
processes and multiple threads, thread states, creating threads, interrupting threads, thread
priorities, synchronizing threads, inter-thread communication, producer consumer
pattern,Exploring [Link] and [Link].
GUI Programming with Java- The AWT class hierarchy, Introduction to Swing, Swing Vs AWT,
Hierarchy for Swing components, Containers – Jframe, JApplet, JDialog, JPanel, Overview of
some Swing components – Jbutton, JLabel, JTextField, JTextArea, simple Swing applications,
Layout management – Layout manager types – border, grid and flow Event Handling- Events,
Event sources, Event classes, Event Listeners, Relationship between Event sources and
Listeners, Delegation event model, Examples: Handling a button click, Handling Mouse events,
Adapter classes. Applets – Inheritance hierarchy for applets, differences between applets and
applications, Life cycle of an applet, Passing parameters to applets, applet security issues.
JAVA OOP Concepts : - Object Oriented Programming is a paradigm that provides many concepts
such as inheritance, data binding, polymorphism etc. Simula is considered as the first object-oriented
programming language. The programming paradigm where everything is represented as an object is
known as truly object-oriented programming language. Smalltalk is considered as the first truly
object-oriented programming language.
Object :- Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Inheritance:- When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism:- When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle etc. In java, we
use method overloading and method overriding to achieve polymorphism.
Abstraction:- Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve
abstraction.
Encapsulation :- Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines. A java class is the example
of encapsulation. Java bean is the fully encapsulated class because all the data members are private
here.
History of java :-
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
[Link]
Data Types :-
Data types represent the different values to be stored in the variable. In java, there are two types of data
types:
o Primitive data types
o Non-primitive data types
Constants in Java :- A constant is a variable which cannot have its value changed after declaration. It
uses the 'final'
Java Type casting and Type conversion :- Widening conversion takes place when two data types are
automatically converted. This happens when:
● The two data types are compatible.
● When we assign value of a smaller data type to a bigger data type.
Java Enum :- Enum in java is a data type that contains fixed set of constants. Enum does not have a
public constructor. Enums are type-safe as they have own name-space.
What is the range of short data type in Java?
a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
Explanation: Short occupies 16 bits in memory. Its range is from -32768 to 32767.
Explanation: Byte occupies 8 bits in memory. Its range is from -128 to 127.
Explanation: Char occupies 16-bit in memory, so it supports 216 i:e from 0 to 65535.
Explanation: getEnumConstants() returns the elements of this enum class or null if this
Class object does not represent an enum type.
If an expression contains double, int, float, long, then the whole expression will be
promoted into which of these data types?
a) long
b) int
c) double
d) float
Explanation: Operator new allocates a block of memory specified by the size of an array,
and gives the reference of memory allocated to the array variable.
Which of these is an incorrect array declaration?
a) int arr[] = new int[5]
b) int [] arr = new int[5]
c) int arr[] = new int[5]
d) int arr[] = int [5] new
Explanation: Operator new must be succeeded by array type and array size.
Explanation: Array can be initialized using both new and comma separated expressions
surrounded by curly braces example : int arr[5] = new int[5]; and int arr[] = { 0, 1, 2, 3, 4};
Explanation: Array is stored in heap space. Whenever an object is created, it’s always
stored in the Heap space and stack memory contains the reference to it.
Explanation: Switch statements checks for equality between the controlling variable and its
constant cases.
What is true about a break?
a) Break stops the execution of entire program
b) Break halts the execution and forces the control out of the loop
c) Break forces the control out of the loop and starts the execution of next iteration
d) Break halts the execution of the loop for certain time frame
Explanation: Do statement checks the condition at the end of the loop. Hence, code gets
executed at least once.
Explanation: Break is used with a switch statement to shift control out of switch.
JVM (Java virtual machine):- JVM is responsible to converting bytecode to the machine
specific code. JVM is also platform dependent and provides core java functions like garbage
collection, memory management, security etc.
JRE:- JRE is the implementation of JVM, it provides platform to execute java programs.
JIT:- JIT optimizes bytecode to machine specific language code by compiling similar
bytecodes at the same time. This reduces overall time taken for compilation of bytecode to
machine specific language.
● Java is called ‘Platform Independent Language’ as it primarily works on the
principle of ‘compile once, run everywhere’.
Explanation: Interpreters read high level language (interprets it) and execute the program.
Interpreters are normally not passing through byte-code and jit compilation.
Explanation: Every class does not need to have a main() method, there can be only one main()
method which is made public. Applets do not require a main() method at all.
Which of the following is a method having same name as that of it’s class?
a) finalize
b) delete
c) class
d) constructor
Explanation: All object of class share a single copy of methods defined in a class,
Methods are allotted memory only once. All the objects of the class have access to
methods of that class are allotted memory only for the variables not for the methods.
Which keyword is used by the method to refer to the object that invoked it?
a) import
b) catch
c) abstract
d) this
Explanation: this keyword can be used inside any method to refer to the current object. this
is always a reference to the object on which the method was invoked.
Explanation: finalize() method is called just prior to garbage collection. it is not called when
object goes out of scope.
● Object of private constructor can only be created within class. Private constructor is
used in singleton pattern.
● The constructor cannot have a return type. It should create and return new
objects.
● Constructor can take any number of parameters.
Explanation: JVM is the super set which contains heap, stack, objects, pointers, etc.
Garbage collection consists of two phases, the mark phase and the sweep phase. I
mark phase all the objects reachable by java threads, native handles and other root sources
are marked alive and others are garbage.
In sweep phase, the heap is traversed to find gaps between live objects and the gaps are
marked free list used for allocating memory to new objects.
What is the process of defining two or more methods within same class that have same
name but different parameters declaration?
a) method overloading
b) method overriding
c) method hiding
d) none of the mentioned
Explanation: Two or more methods can have same name as long as their parameters
declaration is different, the methods are said to be overloaded and process is called method
overloading. Method overloading is a way by which Java implements polymorphism.
When we pass an argument by call-by-value a copy of argument is made into the formal
parameter of the subroutine and changes made on parameters of subroutine have no effect
on original argument, they remain the same.
What is the process of defining a method in terms of itself, that is a method that calls itself?
a) Polymorphism
b) Abstraction
c) Encapsulation
d) Recursion
Explanation: main() method must be specified public as it called by Java run time system,
outside of the program. If no access specifier is used then by default member is public
within its own package & cannot be accessed by Java run time system.
Which of these is used to access a member of class before object of that class is created?
a) public
b) private
c) static
d) protected
Which of these is used as a default for a member of a class if no access specifier is used for
it?
a) private
b) public
c) public, within its own package
d) protected
What is the process by which we can control what parts of a program can access the
members of a class?
a) Polymorphism
b) Abstraction
c) Encapsulation
d) Recursion
Which of the following statements are incorrect?
a) public members of class can be accessed by any code in the program
b) private members of class can only be accessed by other members of the class
c) private members of class can be inherited by a subclass, and become protected
members in subclass
d) protected members of a class can be inherited by a subclass, and become private
members of the subclass
Which of these access specifier must be used for class so that it can be inherited by
another subclass?
a) public
b) private
c) protected
d) none of the mentioned
● The variables should be private and should be accessed with get and set methods.
● Private variables are accessible only within the class.
● Default is the access modifier when none is defined explicitly. It means the member
(method or variable) can be accessed within the same package.
Explanation: The protected access modifier is accessible within package and outside the
package but only through inheritance. The protected access modifier can be used with data
member, method and constructor. It cannot be applied in the class.
Explanation: Variables of an interface are public, static and final by default because the
interfaces cannot be instantiated, final ensures the value assigned cannot be changed with
the implementing class and public for it to be accessible by all the implementing classes.
Protected class member (method or variable) is like package-private (default visibility),
except that it also can be accessed from subclasses. Since there is no such concept as
‘subpackage’ or ‘package-inheritance’ in Java, declaring class protected or package-private
would be the same thing.
Which of these keywords is used to prevent content of a variable from being modified?
a) final
b) last
c) constant
d) static
Explanation: A variable can be declared final, doing so prevents its content from being
modified. Final variables must be initialized when it is declared.
Explanation: All objects of class share same static variable, when object of a class are
declared, all the objects share same copy of static members, no copy of static variables are
made.
Explanation: main() method must be declared static, main() method is called by Java
runtime system before any object of any class exists.
Which of these keywords is used to refer to member of base class from a subclass?
a) upper
b) super
c) this
d) none of the mentioned
Explanation: Whenever a subclass needs to refer to its immediate superclass, it can do so
by use of the keyword super.
Explanation: Strings in Java are immutable that is they can not be modified.
Which of these is the method which is executed first before execution of any other thing
takes place in a program?
a) main method
b) finalize method
c) static method
d) private method
Explanation: If a static method is present in the program then it will be executed first, then
main will be executed.
Which of these data type can be used for a method having a return statement in it?
a) void
b) int
c) float
d) both int and float
Recursion
Recursion is the process of defining something in terms of itself. It allows us to define a
method that calls itself. Recursions are always managed by using stack.
Explanation: To disallow a method from being overridden, specify final as a modifier at the
start of its declaration. Methods declared as final cannot be overridden.
Which of these keywords cannot be used for a class which has been declared final?
a) abstract
b) extends
c) abstract and extends
d) none of the mentioned
Explanation: A abstract class is incomplete by itself and relies upon its subclasses to
provide a complete implementation. If we declare a class final then no class can inherit that
class, an abstract class needs its subclasses hence both final and abstract cannot be used
for a same class.
Explanation: All classes in java are inherited from Object class. Interfaces are not inherited
from Object Class.
Which of this method of class StringBuffer is used to concatenate the string representation
to the end of invoking string?
a) concat()
b) append()
c) join()
d) concatenate()
a) Hell
b) ello
c) Hel
d) llo
Explanation: deleteCharAt() method deletes the character at the specified index location
and returns the resulting StringBuffer object.
Serialization
Serialization is the process of writing the state of an object to a byte stream. This is used when you
want to save the state of your program to a persistent storage area. Serialization and
deserialization occur automatically by java runtime system, Garbage collection also occur
automatically but is done by CPU or the operating system not by the java runtime system
Deserialization is a process by which the data written in the stream can be extracted out
from the stream.
Which of these is a method of ObjectOutput interface used to finalize the output state so
that any buffers are cleared?
a) clear()
b) flush()
c) fflush()
d) close()
What is serialization?
a) Turning object in memory into stream of bytes
b) Turning stream of bytes into an object in memory
c) Turning object in memory into stream of bits
d) Turning stream of bits into an object in memory
Explanation: Serialization in Java is the process of turning object in memory into stream of
bytes.
What is deserialization?
a) Turning object in memory into stream of bytes
b) Turning stream of bytes into an object in memory
c) Turning object in memory into stream of bits
d) Turning stream of bits into an object in memory
Which of the following operators is used to generate instance of an exception which can be
thrown using throw?
a) thrown
b) alloc
c) malloc
d) new
Explanation: new operator is used to create instance of an exception. Exceptions may have
parameter as a String or have no parameter.
Which of the following keyword is used by calling function to handle exception thrown by
called function?
a) throws
b) throw
c) try
d) catch
Explanation: Finally block of the code gets executed regardless exception is caught or not.
File close, database connection close, etc are usually done in finally.
Explanation: try block can be followed by any of finally or catch block, try block checks for
exceptions and work is performed by finally and catch block as per the exception.
Which of these exceptions will occur if we try to access the index of an array beyond its
length?
a) ArithmeticException
b) ArrayException
c) ArrayIndexException
d) ArrayIndexOutOfBoundsException
● try is used for the block that needs to checked for exception
Which of these statements is incorrect?
a) try block need not to be followed by catch block
b) try block can be followed by finally block instead of catch block
c) try can be followed by both catch and finally block
d) try need not to be followed by anything
Which of this method can be used to make the main thread to be executed last among all
the threads?
a) stop()
b) sleep()
c) join()
d) call()
Explanation: By calling sleep() within main(), with long enough delay to ensure that all child
threads terminate prior to the main thread.
Which of this method is used to find out that a thread is still running or not?
a) run()
b) Alive()
c) isAlive()
d) checkRun()
Explanation: The isAlive( ) method returns true if the thread upon which it is called is still
running. It returns false otherwise.
Which of these method of Thread class is used to find out the priority given to a thread?
a) get()
b) ThreadPriority()
c) getPriority()
d) getThreadPriority()
Which of these functions is called to display the output of an applet?
a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
Explanation: Whenever the applet requires to redraw its output, it is done by using method
paint().
● drawString() method is defined in Graphics class, it is used to output a string in an
applet.
Packages are both naming and visibility control mechanism. We can define a class
inside a package which is not accessible by code outside the package.
Explanation: A package can be renamed only after renaming the directory in which the
classes are stored.
Explanation: All methods and variables are implicitly public if interface is declared public.
Interface can have either public access specifier or no specifier. The reason is they need
to be implemented by other classes.
What type of variable can be defined in an interface?
a) public static
b) private final
c) public final
d) static final
Explanation: variable defined in an interface is implicitly final and static. They are usually
written in capital letters
Explanation: By default, interface contains abstract methods. The abstract methods need to
be implemented by concrete classes.
Key points:-
● Generics add stability to your code by making more of your bugs detectable at
compile time. Generics provide type safety by shifting more type checking
responsibilities to the compiler. Generics and parameterized types eliminate the
need for down casts when using Java Collections
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server. For example, using JDBC drivers enable you to open database
connections and to interact with it by sending SQL or database commands then
receiving results with Java.
The [Link] package that ships with JDK, contains various classes with their
behaviours defined and their actual implementaions are done in third-party drivers.
Third party vendors implements the [Link] interface in their database driver.
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation
types into four categories, Types 1, 2, 3, and 4, which is explained below −
Type 1: JDBC-ODBC Bridge Driver :- In a Type 1 driver, a JDBC bridge is used to access
ODBC drivers installed on each client machine. Using ODBC, requires configuring on your
system a Data Source Name (DSN) that represents the target database.
Type 2: JDBC-Native API :- In a Type 2 driver, JDBC API calls are converted into native C/C++
API calls, which are unique to the database. These drivers are typically provided by the
database vendors and used in the same manner as the JDBC-ODBC Bridge. The
vendor-specific driver must be installed on each client machine.
Type 3: JDBC-Net pure Java :- In a Type 3 driver, a three-tier approach is used to access
databases. The JDBC clients use standard network sockets to communicate with a
middleware application server. The socket information is then translated by the middleware
application server into the call format required by the DBMS, and forwarded to the database
server
Type 4: 100% Pure Java :- In a Type 4 driver, a pure Java-based driver communicates directly
with the vendor's database through socket connection. This is the highest performance driver
available for the database and is usually provided by the vendor itself.
● If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
driver type is 4.
● If your Java application is accessing multiple types of databases at the same time, type 3 is
the preferred driver.
● Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
● The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.