Calendar cal = Calendar.getInstance(); int daysBackToSat = cal.get(Calendar.DAY_OF_WEEK ); if(daysBackToSat<7) { daysBackToSat += 7; } cal.add(Calendar.DATE, daysBackToSat*-1); System.out.println(sdf.format(cal.getTime()));
Category Archives: Java
Check class extends other class
import java.util.List; public class ClassObj extends Mac { public static void main(String args[]) { Mac objMac = new Mac(); System.out.println(Mac.class.isAssignableFrom(ClassObj.class)); } } class Mac { }
Output
true
Inheritance vs Polymorphism
Inheritance refers to using the structure and behavior of a superclass in a subclass. Polymorphism refers to changing the behavior of a superclass in the subclass.v
Inheritance is more a static thing (one class extends another) while polymorphism is a dynamic/ runtime thing (an object behaves according to its dynamic/ runtime type not to its static/ declaration type).
Inheritance is when a ‘class’ derives from an existing ‘class’. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has.
Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person, which has a read method, and you have a Student which extends Person, which has its own implementation of read, which method gets called is determined for you by the runtime, depending if you have a Person or a Student
Person p = new Student();
p.read();
The read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p is Student.
The main difference is polymorphism is a specific result of inheritance. Polymorphism is where the method to be invoked is determined at runtime based on the type of the object. This is a situation that results when you have one class inheriting from another and overriding a particular method. However, in a normal inheritance tree, you don’t have to override any methods and therefore not all method calls have to be polymorphic
Creating Cookies in Servlets
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int lngCookieSet = 0; String strCookieVal = ""; String cookieName = "Name"; Cookie[] cookies = request.getCookies(); if(cookies != null && cookies.length > 0) { for(int i=0;i<cookies.length;i++) { if(cookieName.equals(cookies[i].getName())) { lngCookieSet = 1; strCookieVal = cookies[i].getValue(); } } } if(lngCookieSet == 1) { PrintWriter prw = response.getWriter(); prw.print(strCookieVal); } else { Cookie cook = new Cookie("Name", "Mugil"); cook.setMaxAge(24*60*60*365);//1 Year response.addCookie(cook); } }
1.We should check
cookies != null
otherwise the compiler will generate null pointer exception
2.The
new Cookie
constructor will take Cookie Name and Value as Parameter.
3.The addCookie Will add cookie to response Header to set cookie on Client Side
100% abstract Class vs Interface
You can define an abstract method to be protected, and hence not part of the public API of the class. However, that seems like an odd design.
Another thing – instance variables. You can have inheritable instance variables in the abstract class.
Abstract class Methods can be defined at various levels down the path.
In a 100% abstract class, you can also define non constant variables that can be herited. It is not possible with interfaces.
The one case where an “100% abstract class” may be advantageous over an interface is in places where API stability is a key concern.
If you write an API where other people are expected to implement your interface you have to stick to the interface. You can’t add any methods to the interface later on because that would break all clients (you would have to work around this by implement a second interface and let your code check againt the usage with instanceof checks and provide an fallback).
Threads Implementation – Using Runnable
Simple Thread implementing Runnable
Counter.java
public class Counter implements Runnable{ public void run(){ System.out.println("I am Counter Run Method"); } }
Main.java
public class Main { public static void main(String[] args) { Counter objCounter = new Counter(); Thread objThread = new Thread(objCounter); objThread.start(); } }
I am Counter Run Method
Main.java(Using Lambda Expression)
public class Main { public static void main(String[] args) { Thread objThread = new Thread(() -> { System.out.println("I am lambda Counter method"); }); objThread.start(); } }
I am lambda Counter method
new vs runnable vs terminated
- When you create thread using new Operator it would be in “new” state
- Once you call start method over thread it would Transend to “runnable” state
- When run method completed execution it would Transend to “terminated” state
start() vs run()
Thread can be invoked using start or run method. If you use the myThread.start() method it initiates execution of new thread, jvm takes care of execution and scheduling of run method in separate concurrent context. Calling the run method directly myThread.run() will not start a new thread; it will execute the run method in the current thread (ie main thread).
start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place
public class Main { public static void main(String[] args) { Thread objThread = new Thread(() -> { System.out.println(Thread.currentThread().getName()); }); objThread.start(); } }
Output
Thread-0
public class Main { public static void main(String[] args) { Thread objThread = new Thread(() -> { System.out.println(Thread.currentThread().getName()); }); objThread.run(); } }
Output
main
- start() – Initiates the execution of the thread, causing the run method to be called
myThread.start();
- run() – Contains the code that will be executed by the thread. This method needs to be
overridden when extending the Thread class or implementing the Runnable interface.
Usage: Defined by the user based on the specific task. - sleep(long milliseconds) – Causes the thread to sleep for the specified number of milliseconds,
pausing its execution.Thread.sleep(1000);
- join() Waits for the thread to complete its execution before the current thread continues. It
is often used for synchronization between threads.myThread.join();
- interrupt() Interrupts the thread, causing it to stop or throw an InterruptedException. The thread
must handle interruptions appropriately.myThread.interrupt();
- isAlive() Returns true if the thread has been started and has not yet completed its execution,
otherwise returns false.boolean alive = myThread.isAlive();
- setName(String name) Sets the name of the thread.
myThread.setName("MyThread");
- getName() Returns the name of the thread.
String threadName = myThread.getName();
- getName() Returns the name of the thread.
String threadName = myThread.getName();
- setPriority(int priority) Sets the priority of the thread. Priorities range from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY.
myThread.setPriority(Thread.MAX_PRIORITY);
- getPriority() Returns the priority of the thread.
int priority = myThread.getPriority();
- currentThread() Returns a reference to the currently executing thread object.
Thread currentThread = Thread.currentThread();
Thread Implementation Using Runnable Interface
public class Threads2 implements Runnable { public static void main(String[] args) { Threads2 objThreads2 = new Threads2(); Thread t1 = new Thread(new Threads2()); t1.start(); } public void run() { System.out.println("Thread Started"); for(int i=0;i<=5;i++) { System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Thread Stopped"); } }
There are Four Constructors we can use in Runnable Method of Implementation of Threads.
Thread() – Calls Thread Version of run Method
Thread(Runnable Target)
Thread(Runnable Target, String Name)
Thread(String Name)
If we dont Pass the Instance of Class To thread Constrctor then it will call its own Run Method
Thread t = new Thread(new MyThread());
Implementing Thread – Extending Thread Class
How to Extend Thread Class
public class Threads1 extends Thread { public static void main(String args[]) { Threads1 objThreads1 = new Threads1(); } Threads1() { start(); } public void run() { System.out.println("Thread Started"); for(int i=0;i<5;i++) { System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Thread Completed"); } }
Ananymous Inner Class – Class implementing another Class
/** * Anonymous Inner Classes */ public class Outer7 { public static void main(String[] args) { Outer8 objOuter8 = new Outer8(); objOuter8.act(); } public void eat() { System.out.println("I am Eat Method"); } } class Outer8 extends Outer7 { Outer7 objOuter7 = new Outer7(){ public void eat() { System.out.println("I am Overridden Eat Method"); } }; public void act() { objOuter7.eat(); } }
Output
I am Overridden Eat Method
Creating Static Method-Local Inner Class
/** * Referencing Method-Local Inner Class */ public class Outer6 { private static int x = 25; public static void main(String[] args) { invokeInnerClass(); } public static void invokeInnerClass() { class Inner6 { public void displayInnerMsg() { System.out.println(x); System.out.println("I am a Inner Class"); } } Inner6 objInner6 = new Inner6(); objInner6.displayInnerMsg(); } }
Output
25 I am a Inner Class
The Inner Class Defined with in static method has access to only static variables defined in the outer class
Referencing Method Local Inner Class
/** * Referencing Method-Local Inner Class */ public class Outer6 { public static void main(String[] args) { Outer6 objOuter6 = new Outer6(); objOuter6.invokeInnerClass(); } public void invokeInnerClass() { class Inner6 { public void displayInnerMsg() { System.out.println("I am a Inner Class"); } } Inner6 objInner6 = new Inner6(); objInner6.displayInnerMsg(); } }
Output
I am a Inner Class
You cannot Access local variable of the Method since variables are stored in Stack and object exists in Heap memory.The Stack memory will be blown away once the Method exits.
You can access a variable marked as Private in Outer Class.
You can access local variable marked as Final.
The class inside Method-Local Inner class can be either abstract or final.Other private, public and protected are not allowed