Oops With Java (1)
Oops With Java (1)
Interview important
The range of values that can be represented by a float or double is much larger than
the range that can be represented by a long. Although one might lose significant
digits when converting from a long to a float, it is still a "widening" operation
because the range is wider.
1. Automatic conversions(widening ) ---Automatic promotions (done implicitly by
javac)
eg : byte short int long float double
Unicode – 16 bits
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit by bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns the one’s
compliment representation of the input value, i.e. with all bits inversed.
How to explicitly request for GC ?
API of System class
public static void gc()
static --- keyword in java
Usages
1. static data members --- Memory allocated only once at the class loading time ---
not saved on object heap --- but in special memory area -- method area (meta
space) . -- shared across all objects of the same class.
Initialized to their default values(eg --double --0.0,char -0, boolean -false,ref -null)
How to refer? -- className.memberName
Rules -- 1. Can static methods access other static members directly(w/o instance) --
YES
2. Can static methods access other non-static members directly(w/o instance) --NO
3. Can non static methods access static members directly ? -- YES
eg : class A
{
private int i;
private static int j;
public static void show()
{
sop(i);
sop(j);
}
}
They appear -- within class definition & can access only static members directly.(w/o
instance)
A class can have multiple static init blocks(legal BUT not recommended)
eg --
class Outer {
// static & non-static members
static class Nested
{
//can access ONLY static members of the outer class DIRECTLY(w/o inst)
}
}
Important statement
Java compiler resolves method binding by type of the reference & JVM
resolves it by the type of the obejct, reference is referring to.
Annotations are compile time , internally written as interface, removed from .class
file
Downcast needed whne you are accesing subclass function using superclass
Rules :
Any time a class has one or multilple abstract methods ---- class must be declared
as abstract class.
eg. public abstract class BoundedShape {....}
Abstract classes can't be instantiated BUT can create the reference of abstract class
type to refer to concrete sub-class instances.
eg : BoundedShape shape=new Rectangle(....);//legal
BoundedShape shape2=new BoundedShape();//javac err : RHS
Abstract classes CAN HAVE concrete(non-abstract) methods.
Abstract classes MUST provide constructor/s to init its own private data members.
(for creating concrete sub class instance)
eg : Emp : empId, dept...: private : abstract
Mgr extends Emp : to init empId, dept ... : MUST supply a constr in Emp class.
Usages
}
eg : public class Circle extends Shape implements Computable,Runnable {...}
if try aborted and no matching catch block is present then code is aborted but
finally if present will be executed
5.3 try {...} finally {....}
try-with-resources block
From Java SE 7 onwards --- Java has introduced java.lang.AutoCloseable -- i/f
It represents --- resources that must be closed -- when no longer required.
Autocloesable i/f method
Strings
Important String class constructors
1.String(byte[] bytes) --- byte[] ----> String converter
2.String(char[] chars) --- char[] ---> String converter
3.String (byte[] bytes,int offset,int len) ---byte[] ----> String converter from the
specified offset , specified len no of bytes will be converted.
eg . String s=new String(bytes,3,4); --- String will contain bytes[3]----bytes[6]
Yeah, so that doesn't really explain what the pool is, or what it's for, does it? Well,
because String objects are immutable, it's safe for multiple references to "share"
the same String object. Take a look at this example:
Var args
Legal ---
void doStuff(int... x) {
//B.L
} Illegal: javac error
void doStuff4(int x...) {....} // bad syntax : javac err
void doStuff5(int... x, char... y) {...} // too many var-args
void doStuff6(String... s, byte b) { } // var-arg must be last
syso(“%d”, 23) //err as no object, if string was this then as string is object then
works
Enum
enum Direction {
// Enum types
EAST(0), WEST(180), NORTH(90), SOUTH(270);
// Constructor
private Direction(final int angle) {
this.angle = angle;
}
// Internal state
private int angle;
public int getAngle() {
return angle;
}
}
BUT u can't instantiate enums using these constructors , since they are implicitely
private.
You can override toString BUT you can't override equals since it's declared as final
method in enum.
Generics
Advantages
Adds Type Safety to the code @ compile time
Meaning :
1. Can add type safe code where type-mismatch errors(i.e ClassCastExceptions) are
detected at compile time.
2. No need of explicit type casting, as all casts are automatic and implicit.
Illegal: javac error
void doStuff4(int x...) {....} // bad syntax : javac err
void doStuff5(int... x, char... y) {...} // too many var-args
void doStuff6(String... s, byte b) { } // var-arg must be last
ArrayList() -- default constructor. -- creates EMPTY array list object , with init
capacity=10,size=0;
public ArrayList(int capacity) -- -- creates EMPTY array list object , with init
capacity=capacity,size=0;
2. add methods
boolean add(E e) --- append
void add(int index,E e) --- insert
void addAll(Collection<E> e) -- bulk append operation
eg : l1 --- AL<Emp>
l1.addAll(.....);
AL,LL,Vector --- legal
HS,TS,LHS --legal
HM,LHM,TM --illegal --javac error
2.5 Retrieve elem from list
E get(int index)
5.5
E set(int index,E e)
Replaces old elem at spepcified index by new elem.
Returns old elem
6. remove methods
E remove(int index) ---removes elem at specified index & returns removed elem.
Natural Sorting
Steps for Natural ordering
Natural Ordering is specified in generic i/f
java.lang.Comparable<T>
T -- UDT , class type of the object to be compared.
eg -- Emp,Account , Customer
I/f method
int compareTo(T o)
Steps
1. UDT must implement Comparable<T>
eg : public class Account implements Comparable<Account>
2. Must override method
public int compareTo(T o)
{
use sorting criteria to ret
< 0 if this < o,
=0 if this = o
> 0 if this > o
}
3.Use java.util.Collections class API
Method
public static void sort(List<T> l1)
l1 -- List of type T.
Custom Ordering
What is Hashing?
Hashing is defined as the process of transforming one value into another based on a
particular key.
OR
It can be also defined as transforming arbitrary sized data to a fixed size , typically
an int value.
Why there is a guarantee that a duplicate ref can't exist in yet another bucket ?
Answer is thanks to the contract between overriding of hashCode & equals methods
If two elements are the same (via equals() returns true when you compare them), their hashCode()
method must return the same number. If element type violate this, then elems that are equal might be
stored in different buckets, and the hashset would not be able to find elements (because it's going to
look in the same bucket).
If two elements are different(i.e equals method rets false) , then it doesn't matter if their hash codes are
the same or not. They will be stored in the same bucket if their hash codes are the same, and in this
case, the hashset will use equals() to tell them apart.
map
1. Generic Method
What is it ? A Method which has it's own type parameter.
Can it exist in a non generic class? : Yes
i/p : T... a : This method can accept : no args or T[] or T t1,T t2....(var-args of type T)
o/p : FIXED size list
How will you use it for getting a fixed size List<Integer> ?
eg : List<Integer> list=Arrays.asList(10,20,30,40,50);
Generic syntax :
? : wild card in generic syntax (it can be replaced by ANY type) : un bounded wild
card
extends : Represents upper bound
super : Represents lower bound
? extends E : ANY type E or its sub type
? super E : E or its super type
eg : ? extends Emp => Emp or it's sub type(Mgr,Worker.....)
? super Mgr => Mgr or it's super type (Emp , Object)
More Details
extends => upper bound (type of the upper bound super class / interface)
If your collection(list/set/map) is acting as a producer (of data) i.e while
using retrieve operation, use upper bound
eg : ? extends Number => Number or it's subtype (Byte,Short.....Double)
get : type of the data that you get Number or it's subtype, BUT you can't
add Integer , if it's collection of Double
Can be accessed using Number type of the ref.
(Producer extends)
super : lower bound
? super T => T or it's super type
Use it whenever your collection is acting as a consumer (data sink) : i.e
wheneve you want to add data , to a collection.
(Consumer super)
Simple Rule
During the type erasure process, the Java compiler erases all type parameters and
replaces each with its first bound if the type parameter is bounded, or Object if the
type parameter is unbounded.
If there are multiple bounds , then Compiler will replace it by the 1st bound
Eg public class Node<T extends Comparable & Serializable> comparable used
Producer consumer
Now answer this :
public static double sumOfSalaries(List<? extends Emp> list) {
double sum=0;
for (Emp e : list)
sum += e.computeSalary();
list.add(...);//what can be the legal replacement ?
return sum;
}
1. Emp
2. Mgr
3. SalesMgr
4. Object
5. Worker
6. HRMgr
7. TempWorker
8. Date
9. LocalDate
10. PermanentWorker
Why ? : Since the method arg : List<? extends Emp> => caller can pass ANY List of
Emp or any of it's sub types (eg : arg : List<Mgr> : u can't add a worker, Emp ,
Object to this list
List<PermanentWorker> " u can't pass Emp , Mgr , Worker....
Consumer(Writer) => Collection acting as a consumer of data ,i.e you can only add
elems
super
eg : Java API eg :
Collections.addAll
public static <T> boolean addAll(Collection<? super T> c, T... elements)
=> Collection : consumer (super)
T : Orange
boolean addAll(Collection<? super Orange> c, Orange... elements)
Legal method arg : Any Collection(any List / any Set) of generic type : Orange | Fruit
| Object
To such a Collection : what all can u add ? Orange or it's subtypes (eg : Mandarine)
4. Lambda
1st language to use lambda LISP
(written by mote ->) Java compiler compiles lambda expressions and convert them
into private method of the class. and hence in lambda if we write a method or
something which has checked exception then it gives error even if we have out big
try catch block. to solve this we have to include another inner try catch to handle
that exc.
Streams (java.util.stream)
Streams are wrappers (abstraction) around a data source(eg : array ,
collection ,lines from a text file....) .
A stream represents sequence of elements from a data source .
It supports : 2 different type of streams
Streams holding primitive types : IntStream , LongStream , DoubleStream
(interfaces)
Streams holding referece types(T) : Stream<T> (interface)
Important Facts of Java 8 Streams:
1. Streams are implicitely closed , after terminal operation (i.e they can't be re used
after terminal operation)
Otherwise throws --IllegalStateException (reason :stream has already been operated
upon or closed)
Where as , collections are re-usable.
Adv. of Scanner over above chain ----- contains ready-made parsing methods(eg ---
nextInt,nextDouble.....)
But Scanner is not Buffered Stream
Can combine both approaches.(new Scanner(br.readLine())
java.io.PrintWriter --- char oriented buffered o/p stream --- which can wrap any
device.(Binary o/p stream or Char o/p stream)
Constructors---
PrintWriter(Writer w) --- no auto flushing,no conversion, only buffering
PrintWriter(Writer w, boolean flushOnNewLine)--- automatically flush buffer contents
on to the writer stream --upon new line
PrintWriter(OutputStream w) --- can wrap binary o/p stream -- buffering
+conversion(char-->binary),no auto-flush option
PrintWriter(OutputStream w , boolean flushOnNewLine) ---
API Methods----print/println/printf same as in PrintStream class(same type as
System.out)
Stream class which represents --- Char o/p stream connected to Text file. ---
java.io.FileWriter
Constructor
FileWriter(String fileName) throws IOException -- new file will be created & data will
be written in char format.
FileWriter(String fileName,boolean append) --- if append is true , data will be
appended to existing text file.
Serialization
serialization= extracting state of object & converting it in binary form.
state of object = non-static & non-transient data members
If super-class is NOT serializable --- super class must have a default constructor
(otherwise InvalidClassException is thrown by JVM during de serilaization)
sub-class developer has to explicitely write the state of super-class.
Constructor of serializable class does not get called during de-serialization. Why?
Think -- what is the need of constructor?
Constructor initializes the object variables with either default values or values which
is assigned inside constructor. BUT we want to initialize the state of the object from
binary stream.
Transient and static fields are ignored in serialization. After de-serialization transient
fields and non-final static fields will be inited to default values. Final static fields still
have values since they are part of the class data.
If you need to serialize a Serializable class Employee, but one of its super classes is
not Serializable, can Employee class still be serialized and de-serialized?
The answer is yes, provided that the non-serializable super-class has a no-arg
constructor, which is invoked at de-serialization to initialize that super-class.
What will be the state of data members?
Sub class (serializable) data members will have the restored state & super class(non
serializable) data members will have def initiated state
Serializable Externalizable
If you implement Serializable interface , if u implement Externalizable i/f -- you
automatically state of the object gets have to explicitly mention which fields
serialized. you want to serialize.
Serializable is marker interface without Externalizable interface contains two
any methods. methods: writeExternal() and
readExternal().
Default Serialization process will take Programmer defined Serialization
place for classes implementing process for classes implementing
Serializable interface. Externalizable interface.
Serializable i/f uses java reflection to re Externalizable requires public no-arg
construct object during de-serialization constructor.
and does not require no-arg constructor.
eg :
If your lambda expression is like this:
list.forEach(System.out::println);
The :: operator is used in method reference to separate the class or object from the
method name
4 types
1. Method reference to an instance method of an object – object::instanceMethod
2. Method reference to a static method of a class – Class::staticMethod
3. Method reference to an instance method of an arbitrary object of a particular
type – Class::instanceMethod
4. Method reference to a constructor – Class::new
Java Reflection
It What is Java reflection ?
Java API for (java.lang.Class<T> , java.lang.reflect)
1. Inspecting classes,interfaces,fields, methods w/o knowing their names at compile
time
2. Instantiating new objects , arrays
3. Invoking private methods and get/set field values .
4. Dynamic method invocation provides ability to inspect and modify the runtime
behavior of application.
How to get access to loaded class(java.lang.Class) ?
1.Through static variable : class
eg : Emp.class ---loaded class info --Class<Emp>
eg : Student.class => Class<Student>
OR
2.Using getClass() method of Object
public final Class<?> getClass()
OR
3.Method of java.lang.Class
public static Class<?> forName(String fullyQualifiedName) throws
ClassNotFoundException
code egs in : test_reflection project
Starting from page 19 – 7th mcq
Sanfoundry mcq’s started from here
https://www.sanfoundry.com/java-questions-answers-freshers-experienced/#java-
chapters
https://www.sanfoundry.com/java-questions-answers-concepts-oops/
QP
b
https://www.examtray.com/java-questions/java-abstract-class-interview-mcq-
questions-and-answers
https://www.examtray.com/java-questions/java-command-line-arguments-interview-
mcq-questions-answers
Error if initliazed and accesed, no error if only initialized
https://www.geeksforgeeks.org/50-java-language-mcqs-with-answers-2/
Play with it
class Base extends Exception {}
class Derived extends Base {}
catch(Derived d) {
System.out.println("Caught derived class exception");
}
catch(Base b) {
System.out.println("Caught base class exception");
}
}
}
Red flagggg
https://www.examtray.com/java-questions/java-enum-interview-mcq-questions-
answers
https://javaconceptoftheday.com/java-practice-coding-questions-on-nested-classes/
https://javaconceptoftheday.com/java-exception-handling-quiz/
Done till 18 here tak
https://www.sanfoundry.com/java-assessment-questions-answers/
threads
Answer : sleep()