Constructor: You Need To Save Your Java Program by The Name of The Class Containing
Constructor: You Need To Save Your Java Program by The Name of The Class Containing
What does it mean that object is immutable? Immutable means that once the constructor for an object has completed
execution that in- stance can't be altered. This is useful as it means you can pass references to the object around,
without worrying that someone else is going to change its contents. Especially when dealing with concurrency, there
are no locking issues with objects that never change.
Is String type immutable in java? Yes
•If you have mutable fields in your class, like List or Date, making them final won't
suffice.
You should return a defensive copy (deep copy) from their getters, so that their state isn't mutated by calling methods.
Example:
public Date getDate() {
return new Date(this.date.getTime());
}
Abstraction – contract - - Information Hiding - You can achieve abstraction in two ways in Java:
1. Encapsulation - data hiding - concept to create and define the permissions הרשאות- is implemented using four
types of access level modifiers: public, protected, no modifier (default) and private.
Encapsulation provides the security that keeps data and methods safe from inadvertent changes.
Casting - Casting means converting one data type to another data type.
There is to kind of casting
o primitive casting – casting on primitive variable.
o Reference casting – casting on reference variable.
primitive casting
1. Implicit Type Casting or Widening Casting (automatically)
2. Explicit Type Casting or Narrowing Casting (manually)
This reference can access all the methods and variables of parent class but only those methods of child class which is
overridden.
הוא,)(Child אבל לשיטות שיש אותם ב, Child אוparent הוא יכול לממש כל פונקציה שנמצאת אצל, הוא אף פעם לא עף לשגיאה,במילים אחרות
.parent יממשו ב, )(Child ואלה שאין אותם בoverriden ממש אותם כי
Down casting : Assigning parent class reference (which is pointing to child class object) to child class reference .
When subclass reference refers to super class object, it is called narrowing or Just because E extends C,
downcasting in java. In other words, when sub class type is converted into super class
type, it is called downcasting. C doesn't become an E...
Here p is pointing to the object of child class as we saw earlier and now, we casted
this parent reference p to child class reference c. Now this child class reference c can access all the methods and
variables of child class as well as parent class.
For example, if we have two classes, say Machine and Laptop which extends Machine class.
but for downcasting, every machine may not be a laptop because there may be some machines which can be CPU,
Mobile, etc.
Hence downcasting is not safe, and we explicitly write the class names before doing downcasting. So, it won’t give an
error at compile time but it may throw ClassCastExcpetion at run time if the parent class reference is not pointing to the
appropriate child class.
Laptop laptop = machine; //compilation error because machine here is type Shape i.e. parent
//laptop is a reference of Laptop class and machine is a reference of Machine class and Pointing to Machine class
Object .So logically assigning machine reference to laptop reference is invalid because when laptop ref try to access
methods from Laptop class which are not be visible to laptop reference.And hence throws ClassCastException at run
time .
To get rid of ClassCastException we can use instanceof operator to check right type of class reference in case of down
casting .
Machine machine = new Machine(); //machine3 points to object of Ma-chine class.
Laptop laptop = (Laptop) machine; //here reference laptop2 points to object of Machine class
//This won't give compilation error but it will fail at run time giving an exception for classCastException
//Remember that all machines won't be laptops , they can be CPU or Mo-bile etc.
So, Casting comes into picture when we need to narrow the scope i.e. we move from general type (parent) to more
specific type (child).
Using casting in below statement you tell compiler that i know reference ‘machine’ is of type Machine but it is actually
holding the object of laptop hence knowing that i am casting it and holding it in Laptop reference.
Finally, you can try to downcast. If it’s the correct type, it will be successful. Otherwise, you’ll get a ClassCastException.
recursion.
A recursive method calls itself (contains a call to the method from inside of the method).
A recursive method should have at least one way to stop the recursion. This is called a base
case.
base case - A way to stop the recursive calls. This is a return without a recursive
call.
call stack - A class defines what all objects of that class know (fields) and can do
(methods). You can also have data and behaviour in the object that represents the class
(class fields and methods). All objects of a class have access to class fields and class
methods, but these can also be accessed using className.field or className.method().
recursive method - A method that contains at least one call to itself inside the
method.
Object − Objects have states and behaviours. Example: A dog has states - colour,
name, breed as well as behaviour such as wagging their tail, barking, eating. An
object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the
behaviour/state that the object of its type supports.
Methods − A method is basically a behaviour. A class can contain many methods.
It is in methods where the logics are written, data is manipulated and all the
actions are executed.
Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
Instance Method
Instance method are methods which require an object of its class to be created before it can be called
שרשור
System.out.printIn(“hello”+5+3) – output – hello53
-due for hello is string and the default in + in strings is שרשור
So that it be accessible to the JVM which begins to execute the program from outside of the class.
Java Virtual Machine(JVM) is an engine that provides a run time environment to drive the java code. It converts the java
byte code into machine language.
1. It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle.
2. It manages and optimizes program memory.
The JVM memory manager creates memory pools during the runtime of the program.
There are two types of memory pools namely the stack memory and the heap memory.
The main difference between stack memory and the heap memory is that the stack is used to store only the small
datatypes whereas heap stores all the instances of the class.
Access to this memory is in Last-In-First-Out (LIFO) order. It's automatically allocated and deallocated
when method finishes execution
Whenever a new method is called, a new block on top of the
stack is created which contains values specific to that method, If this memory is full, Java throws
like primitive variables and references to object java.lang.StackOverFlowError
is used for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always
created in heap space and the references to this objects are stored in stack memory.
These objects have global access and can be accessed from anywhere in the application.
This memory model is further broken into smaller parts called generations,
these are:
1. Young Generation – this is where all new objects are allocated and aged. A minor Garbage collection occurs
when this fills up
2. Old or Tenured Generation – this is where long surviving objects are stored. When objects are stored in the
Young Generation, a threshold for the object's age is set and when that threshold is reached, the object is
moved to the old generation
3. Permanent Generation – this consists of JVM metadata for the runtime classes and application methods
What is
the difference between stack and heap?
Stack is used to store local variables and function calls while heap memory is used to
store objects in Java.
Each thread has their own stack.
If there is no memory left in the stack JVM will throw java.lang.StackOverFlowError,
while if there is no heap space JVM will throw java.lang.OutOfMemoryError: Java Heap Space.
Size of stack memory is a lot lesser than the size of heap memory.
Variables stored in stacks are only visible to the owner thread while objects created in
.the heap are visible to all threads
.How many stack memories are there in java? One stack per thread
עותק. הוא לא שומר ערך מחוץ לבלוקיים שהוא מוגד- בעיקרון – הוא חיי רק בתוך הפונקציה שהוא מוגדר בה- Call by value
. אין לו עותק, שינוי באיזה מקום שינוי בערך עצמו- – שומר ערך –כל שינוי נשמרCall by refference
int x = 10;
int y = 20;
System.out.println("value of x:" + x);
System.out.println("value of y:" + y);
System.out.println("After swapping");
x = x + y; //30
y = x - y; //30-20 = 10
x = x - y; //30 – 20 = 20
2) Local Inner Class // we access the inner class throught the method
The inner class could be used only by outer class. Inner classes represent a special type of relationship that
allows access to all members (data members and methods) of the outer class, including the private class.
Inner classes are used to develop a more readable and maintainable code because they logically group classes
and interfaces in one place.
Easy access, as the inner object, is implicitly available inside an outer Code optimization requires less code to
write. It can avoid having a separate class.
The second type is : Static nested classes
Once a final variable has been assigned, the variable cannot be changed.
Therefore, the user tries to change the value using the setter or the constructor, and then the errors are entered into
the program.
Final variable : If you make a variable as final, you cannot change the value of the final variable.
A variable with the final keyword cannot be modified so it becomes constant. The variable has to be initialized to be
used in any java program.
Final variable doesn’t accept set method due for it can’t be change.
Final method :
If we marked method as final , can’t be overriding it in inheritance ((ירושה.
not allowed !
because if you overriding method that’s mean that you update it or change it like you want and final keyword don’t
allow to change it .
Final class : if we marked class as final then we won’t be able to use the class as parent class . we can’t inheritance
from it , we won’t be able to build a sub class for this final class .
Throw/throws
The keyword “throw” is used to throw an exception from any method or static block, while the keyword “throws”, used
in a method declaration, indicates what exception can be thrown with this method. They are not interchangeable.
כי כאשר היא מתבצעת היא זורקת אקספטש ויוצאת ולא ממשיכה למטה לכן אם יש מתחתה כל שורה,היא חייבת להיות השורה האחרונה בשיטה
! גאווה צועק שגיאה
Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as
autoboxing.
For example — conversion of int to Integer, long to Long, double to Double, etc.
Primitives and Wrapper classes:
boolean - Boolean
byte - Byte
char - Character
short - Short
int - Integer
long - Long
float - Float
double - Double
When a method is expecting a wrapper class object but the value that is passed as parameter is a primitive type.
arrayList.add(11); //Autoboxing - int primitive to Integer
Threads
Threads perform a single task that belongs to a single process.
A thread is a mini process within a process that can execute or perform operations independently. A thread is a
lightweight process. Unlike many other computer languages, Java provides integrated support for multi-threaded
programming. A multi-process program contains two or more parts
that can be executed simultaneously.
There are two ways for creating threads and associate them with the required code.
Synchronization under
concurrency control
Java synchronization is a concept where errors can appear in the code if the same entity is shared by two or more
threads. Therefore, it can cause different results
each time the execution takes place.
1. Synchronized method
2. Synchronized block
3. Static synchronization
Synchronized method
Again, synchronized is do the job but in all the method, if there is another loop that I don’t want to synchronized I can’t
with this case.
So; the solution is to make block for the specific loop that I need to synchronized
Synchronized block
synchronized (this) {
// synchronized block loop
}
Static synchronization
If we want to be multi-
threading/multi-processing thing we
should use static cuz static don’t share
memory.
When the thread is dependent on the variable always use the volatile keyword. It means this variable will not be cached
by the thread.
This that value of the volatile variable will always be read from main memory and not from Thread’s local cache.
how he know which wait() ? it’s depends on the priority of the threads
Remember wait() and notify() method is defined in the object class, and they must be called inside the
synchronized block.
When notify() method is called the lock on the wait method would be released. We would be able to perform
the operation.
Interrupt
The basic concepts of interrupt is that it stops the thread that is in an idle state by showing the interrupted exception.
Therefore, it can be given a chance to execute in case of a long wait or sleep functions.
Suppose there are two threads and If one of the threads is blocked in an invocation of the wait() method of this class,
then its interrupt status will be cleared and it will receive an Interrupt Exception, which gives the chance to another
thread to execute the corresponding run() method of another thread which results into high performance and reduces
the waiting time of the threads.
Sometimes there can be a situation where the thread should not work continuously, but it can go in wait state
once a while, to give other threads a chance to do their work. But when a thread is waiting it can’t check actively
whether it should terminate. Then we need to use interrupt() method. We can call the interrupt() method
directly from the run() method.
Join overview
1. join () method
will put the current thread on wait until
the thread in which it is called is dead.
If the thread is interrupted,
InterruptedException will be thrown.
2. join (long millis) method will put the
current thread on wait until the thread
in which it is called is dead or wait for
the specified time (milliseconds).
3. join (long millis, int nanos) method
will put the current thread on wait until the thread in which it is called is dead or wait for the specified time
(milliseconds + nanos).
Thread pools
a thread pool that is a software design pattern for achieving concurrency of execution in a computer program. Often,
also called a replicated workers or worker-crew model, a thread pool maintains several threads waiting for tasks to be
allocated for concurrent execution by the supervising program.
In the following program, we have SomeThread class which extend Thread. Inside the App class, we are creating fixed
thread pool from Executors framework. Then we pass the object of thread type for executing threads. And shut down
the Executor pool. shutdown() method helps us to finish execution of all the submitted tasks and terminate the thread
pool.
countdown latch
The basic use of this is that we can place the thread that we want to execute after a certain number of threads. This can
be done by setting the countdown number to the number of threads after which we want the specific thread to be
executed.
So, CountDownLatch, it’s used when a thread needs to wait for other threads before starting its work.
As we have seen above program, where we create a task that is going to wait for four threads before it starts. Then we
create four threads and start them.
Here we call the latch.await() method. This method will force the main thread waits for four threads until the lock is
released.
In order to release the lock, we use latch.countDown() method. It reduces the count of the latch and released all
waiting threads.
The blocking queue
is used as a container for objects when the threads are inserting the objects and other threads are taking the objects
out of it. The threads can only continue inserting the objects until a specific limit and take out or use the resources until
a specific limit. Therefore, any limit reached the blocking queue will immediately block the threads.
The following program will demonstrate the capability of blocking queue. In order to understand the concept of
blocking queue, we will start with the producer and consumer. As the name suggests producer thread add the element
in the queue and consumer thread consumes the element from the queue. These two threads works simultaneously on
blocking queue collection.
We have created a producer class which implements the Runnable interface. Producer class will use the put() method to
add elements in the queue and before putting new element the thread will wait for one second.
Once the element in blocking queue reached to the maximum limit, instead of terminating the program blocking queue
will force the thread to wait until there is an empty space.
Here we show how to use ReentrantLock in Java. Reentrant locking is an alternative form of locking apart from the
implicit locking provided by keyword
synchronized in Java.
The deadlock
‘thread1’ prints “Inside thread1 on lock 1” and ‘thread2’ prints “Inside thread2 on lock 2”. ‘thread1’ tries to acquire the
lock on object lock2 but as it is already holed by thread1.
Same happens with thread2. It tries to acquire the lock on object lock1 but it is already holed by thread1, so it waits till it
becomes free. Hence, both threads are in a wait state, waiting for each other to release locks. But none of them is
ready to release the lock. This intersection causes the deadlock to occur.
https://www.csie.ntu.edu.tw/~d00922011/java2/multithreading/JavaThreads.pdf
Lambda expression
The stream is a sequence of data. It could be a sequence of input, output or error stream. As the name suggest input
and output. It is used for the purpose of input and output respectively.
In Java streams are automatically created for us. All these streams are attached with console.
But BufferedWriter writes text to a character stream with efficiency and provides a convenient method for writing a line
separator: newLine().
Reading into a file
In Java as seen above not only we can read files with the
help of File Reader but also scanner class by using some
functions like the hasnext. Therefore, we can read the file
statements by the same class.
What is resource leak in java? A resource leak occurs when you don't close a reader, scanner, buffer, or another
process that uses resources and needs to clean them up out of memory.
File deletion
The concept of file deletion is shown here. This is done by a simple command of file.delete() method.
The Java File delete() method can be used to delete files, it will return a boolean value. It returns true if the file is
deleted; false if failed.
The try with resources is a command that whenever we allocate some resources, for example, assigning a resource to
take input from the Scanner class. If the user fails to close the resource, then it leads to a resource leak which could
prove dangerous to the execution of a program. Hence after implementing the same in a try block, we can avoid the
resource leak.
The debugging is used in java to rectify the code by setting breakpoints in the code. By setting breakpoints we can verify
the variables and methods current state.
Debug Perspective
The Debug perspective offers additional views that can be used to troubleshoot an application such as breakpoints,
variables, debugging, console, etc. When a Java program is started in debug mode, users are prompted to switch to the
debug perspective.
Marker Interfaces in Java have special significance because of the fact that they have no methods declared
in them which means that the classes implementing these interfaces don't have to override any of
the methods.
A few of the marker interfaces already exist in the JDK like Serializable and Cloneable
They are used to provide some essential information to the JVM so that JVM may perform some
useful operation.
Marker interface is an empty interface where in doesn't have any fields or methods in it. It is used to
give some kind of command to jvm or a compiler. Example are Serializable, Clonnable etc.. When we
implement empty interface, it tells compiler to do some operations. if the class is serializable then
perform serialize operation and same way if the class is clonnable then it perform clone operation.
They are used because we are telling to JVM that that class have special behaviour.
eg. by serilizable we are telling to JVM class is Seriliazable.
by Cloneable we are telling to JVM class is Cloneable.
we can't create marker interface as you can't instruct JVM to add special behaviour to all classes
implementing special interface. Now a days we do not use Marker Interface, all it's work is done by
annotations.
31. How to force Garbage Collector (GC) to run? It’s not possible to force it. You can call System.gc(); but you cannot
be sure that GC will be run.
2. What finalize() method is for? finalize() method is called by the garbage collector on an object when garbage
collector deter- mines that there are no more references to the object. A subclass overrides the finalize method to
clean system resources or to perform other cleanup. The finalize method may take any action, including making this
object available again to other threads; However the usual purpose of finalize is to perform cleanup actions before the
object is irrevocably discarded. For example, the finalize method for an object that represents an input/output
connection might perform explicit I/O transactions to break the connection be- fore the object is permanently
discarded. The Java programming language does not guarantee which thread will invoke the finalize method for any
given object. It is guaranteed that the thread that invokes finalize will not be holding any user-visible synchronization
locks when finalize is invoked. If an uncaught excep- tion is thrown by the finalize method, the exception is ignored and
finalization of that object terminates. The finalize method is never invoked more than once by a Java virtual machine
for any given object.
https://studyeasy.org/category/java/
Static
Abstraction
package
Serialization
Garbage Collector
101. Why Java provides Garbage
Collector?
In Java, there are no pointers. Memory management and allocation
is done by JVM. Since memory allocation is automated, after some
time JVM may go low on memory. At that time, JVM has to free
memory from unused objects. To help with the process of
reclaiming memory, Java provides an automated process called
Garbage Collector.
String
Exception Handling
135. What is a finally block in Java?
Java provides a finally block with a try block. This is an optional
block. But finally block is always executed after the execution of try
block.
Java Collection