UrbanPro
true

Take BA Tuition from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Learn Programming in JAVA with Free Lessons & Tips

Ask a Question

Post a Lesson

All

All

Lessons

Discussion

Lesson Posted on 31/10/2018 Learn Programming in JAVA +3 Java Java Programming Core Java

Class and Objects in Java

Asterix Solution

Asterix Solution is one of Mumbai's and Navi Mumbai's top leading IT Training Institute since 2104. We...

Class is a template or a blueprint which is used to describe an object. On other hand Object is a reference of a class which follows all the stuff written inside the class. How about taking the whole tour in the following video read more

Class is a template or a blueprint which is used to describe an object.

On other hand Object is a reference of a class which follows all the stuff written inside the class.

How about taking the whole tour in the following video

 

read less
Comments
Dislike Bookmark

Lesson Posted on 11/10/2018 Learn Programming in JAVA +4 Java Java Programming Core Java Advanced Java Programming

Java 8 Predicates

Shiva Kumar

I have completed Engineering in computer science in 2008. Since then,I have been working in IT industry...

In the previous lession, we have learnt how to use filters and collectors. In filter we have passed the condition to evaluate whether the object is eligible to be filtered or not. Code given below for reference and highlighted in bold. public class NowJava8 { public static void main(String args)... read more

In the previous lession, we have learnt how to use filters and collectors. In filter we have passed the condition to evaluate whether the object is eligible to be filtered or not. Code given below for reference and highlighted in bold.

public class NowJava8 {

public static void main(String[] args) {

List lines = Arrays.asList("abc", "xyz", "shiva");

List result = lines.stream() 
.filter(line -> !"shiva".equals(line)) 
.collect(Collectors.toList()); 

result.forEach(System.out::println); //output : abc,xyz

}

}

Now, what if I would like to same condition in different places to filter on different collections. We would end up repleating same piece of code.
What does it mean? we break DRY (Do not repeat yourself).

Here to solve this we can use predicates. Example given below.
 import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PredicatesExample
{
public static Predicate<String> isShiva() {
return s -> s.equalsIgnoreCase("shiva");
}


public static void main(String[] args) {
List<String> lines = Arrays.asList("abc", "xyz", "shiva");

List<String> result = lines.stream()
.filter(isShiva().negate())
.collect(Collectors.toList());

result.forEach(System.out::println); //output : abc,xyz
 
List<String> names = Arrays.asList("abc", "dhdh", "shiva","ddds","edsd");
 
 result =names.stream() 
.filter(isShiva().negate())
.collect(Collectors.toList()); 

result.forEach(System.out::println); //output : abc,dhdh,ddds,edsd
}
}  

As you see, we have used same predicate for two different collections.
read less
Comments
Dislike Bookmark

Lesson Posted on 26/09/2018 Learn Programming in JAVA +7 Java Java Script Training Java Programming Core Java JSP (Java Server Pages) Selenium with Java Advanced Java Programming

How can everyone prepare to clear any Java interview?

Bright Computer Education

Bright Computer Education is Vadodara based Institute, works on All India Computer Education Mission....

Java interview your java should be much strong then J2EE. core java and Advance java is the basic foundation for Interview. Some of the topic about which you should know before going for a java interview are mentioned below: 1-JRE, JDK & JVM 2-OOPS 3-Different scenarios related to oops like scenarios... read more

Java interview your java should be much strong then J2EE. core java and Advance java is the basic foundation for Interview. Some of the topic about which you should know before going for a java interview are mentioned below:

1-JRE, JDK & JVM

2-OOPS

3-Different scenarios related to oops like scenarios based on compile-time and runtime polymorphism, different type of inheritence

4-exception hierarchy, checked and unchecked exception, Different scenarios related to exceptions

5-Threads , their states and ways of creating threads.

6-Collection framework and difference between different collections.

7-Generics.

8-Hashcode and equals and their contract.

9-Difference between:

         String & StringBuffer

         equals and ==

         checked and unchecked exceptions

         interface and abstract class

          Thread class and runnable interface.

read less
Comments
Dislike Bookmark

Take BA Tuition from the Best Tutors

  • Affordable fees
  • Flexible Timings
  • Choose between 1-1 and Group class
  • Verified Tutors

Asked on 12/01/2018 Learn Programming in JAVA

Can you override a private or static method in Java?

Answer

Lesson Posted on 20/11/2017 Learn Programming in JAVA +5 Core Java Java Java Programming Java Programming Java Programming

Java: A Quick Overview

Vivek Ranjan Sahu

Experienced and qualified teachers are everywhere now-a-days. But along with that, I am also an analyser...

Not purely Object Oriented: It doesn't support multiple inheritence, it supports primitive data types and static members. Doesn’t support multiple inheritance: Reason is diamond problem i.e., if both parent classes have same method & not overridden by child, then at runtime ambiguity occurs. Platform... read more
  • Not purely Object Oriented: It doesn't support multiple inheritence, it supports primitive data types and static members.
  • Doesn’t support multiple inheritance: Reason is diamond problem i.e., if both parent classes have same method & not overridden by child, then at runtime ambiguity occurs.
  • Platform Independent: Compiled into platform independent bytecode.
  • Robust: Provides compile-time and runtime checks in order to eliminate error prone situations.
  • Multithreaded: Supports performing multiple tasks simultaneously.
  • Interpreted: Java bytecode is translated on the fly to native machine instructions and is not stored anywhere.
  • High Performance: Uses JIT compiler.
  • Secure.
  • Architectural neutral.
  • Portable.
  • Distributed.
  • Dynamic.
read less
Comments
Dislike Bookmark

Lesson Posted on 20/11/2017 Learn Programming in JAVA +5 Core Java Java Java Programming Java Programming Java Programming

Comparable vs Comparator

Vivek Ranjan Sahu

Experienced and qualified teachers are everywhere now-a-days. But along with that, I am also an analyser...

java.lang.Comparable java.util.Comparator For comparing some other object with its own object. Ex. I am comparing myself to some other employee. Method signature is: int compareTo (T object). For implementing Comparable, access to the original class is required. The class itself needs... read more
java.lang.Comparable java.util.Comparator
  1. For comparing some other object with its own object. Ex. I am comparing myself to some other employee.
  2. Method signature is: 
    int compareTo (T object).
  3. For implementing Comparable, access to the original class is required.
  4. The class itself needs to implement Comparable and hence it is inside java.lang package.
  5. It can be used to provide single way of sorting.
  1. For comparing two objects by a separate class. Ex. Manager is comparing two employees with each other.
  2. Method signature is:
    int compare (T object1, T object2).
  3. If the required class is not accessible i.e., present inside some jar, then a Comparator implementation can be used that just accepts the two objects and do the comparison.
  4. It is a utility that can be used by an external class to perform the required action and hence it is inside java.util package.
  5. It can be used to provide multiple sorting ways like NameComparator, SalaryComparator etc.
read less
Comments
Dislike Bookmark

Take BA Tuition from the Best Tutors

  • Affordable fees
  • Flexible Timings
  • Choose between 1-1 and Group class
  • Verified Tutors

Lesson Posted on 20/11/2017 Learn Programming in JAVA +5 Core Java Java Java Programming Java Programming Java Programming

ClassNotFoundException vs NoClassDefFoundError

Vivek Ranjan Sahu

Experienced and qualified teachers are everywhere now-a-days. But along with that, I am also an analyser...

ClassNotFoundException NoClassDefFoundError It is an exception and happens due to programmer’s mistake and can be recovered by updating the code. Thrown when an application tries to load a class through its String name using Class.forName or ClassLoader.findSystem or ClassLoader.loadClass... read more
ClassNotFoundException NoClassDefFoundError
  1. It is an exception and happens due to programmer’s mistake and can be recovered by updating the code.
  2. Thrown when an application tries to load a class through its String name using Class.forName or ClassLoader.findSystem or ClassLoader.loadClass methods.
  3. Thrown by application.
  1. It is an error and doesn’t happen due to programmer’s mistake and can’t be recovered by updating the code.
  2. Thrown if JVM is unable to find the class during runtime which was present at compile time. Ex. removing .class file just before running, will throw error.
  3. Thrown by JVM.
read less
Comments
Dislike Bookmark

Lesson Posted on 15/06/2017 Learn Programming in JAVA +4 Java Engineering Diploma Tuition Java Programming Core Java

Class, Object and Methods in JAVA

Debabrata Mandal

I am a B-tech in computer science and engineering (CSE). I have around 7 years of experience in many...

Lesson-1: Class, Object and Methods of Java can be compared with body, heart and brain. Without these 3 things, Java does not exist. If you Google the above 3 items, you will find many definitions. But be honest and think how many of you can really understand the actual concept. Let me explain it in... read more

Lesson-1:

Class, Object and Methods of Java can be compared with body, heart and brain. Without these 3 things, Java does not exist. If you Google the above 3 items, you will find many definitions. But be honest and think how many of you can really understand the actual concept. Let me explain it in my way:

Class: I would say a class is a community, like Human or Indian.

Object: Object belongs to a particular community/class and holds behaviours of that class. Like you, me, he, she etc who belong to or represent the human community.

Method: Method defines some specific functionality of the belonging class. As for example eating, speaking is some functionalities of human class. But the functionality many vary from object to object. Like you speaks English and I speaks the Hindi language. We both are objects of the Human class.

read less
Comments
Dislike Bookmark

Lesson Posted on 29/05/2017 Learn Programming in JAVA +11 Advanced Java coaching BA Tuition BCA Tuition Java Programming Big Data Hadoop BTech Tuition Java Programming Engineering Diploma Tuition Advanced Java Programming Java

Design Pattern

Paras Chawla

Working as a Senior Software Developer(R and D) in the following technologies. 1. Java 2. J2EE/J2ME 3....

Prototype Design Pattern: Ø Prototype pattern refers to creating duplicate object while keeping performance in mind. Ø This pattern involves implementing a prototype interface which tells to create a clone of the current object. Ø This pattern is used when creation of object directly... read more

Prototype Design Pattern:

Ø Prototype pattern refers to creating duplicate object while keeping performance in mind.

Ø This pattern involves implementing a prototype interface which tells to create a clone of the current object.

Ø This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation.

Ø We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

 Prototype DP involves cloning of object and thus object needs to:

 Ø Implement Cloneable interface

 Ø Override clone() of Object class

 public abstract class Payment implements Cloneable {

    

       protected double amount;

          

        public double getAmount() {

                return amount;

           }

 

           public void setAmount(double amount) {

                this.amount = amount;

           }

          

     public abstract void makePayment();

    

     public Object clone() {

                 Object clone = null;

                 try {

                    clone = super.clone();

                 } catch (CloneNotSupportedException e) {

                    e.printStackTrace();

                 }

                 return clone;

              }   

}

public class CreditCard extends Payment {

 

     public void makePayment() {

           System.out.println("Payment of "+amount+ " by Credit Card");

     }

 

}

 

public class CashPayment extends Payment {

 

     public void makePayment() {

           System.out.println("Payment of "+amount+" by Cash");

     }

    

}

 

public class PaymentCache {

 

     private Map<String, Payment> map = new HashMap();

 

     public Payment getPayment(String key) {

           Payment payment = map.get(key);

           return (Payment) payment.clone();

     }

 

     // Map of Objects which are frequently used...

     // Original objects are acting as template objects...

 

     public void loadCache() {

           CashPayment cash = new CashPayment();

           cash.setAmount(2000);

           map.put("cash", cash);

 

           CreditCard credit = new CreditCard();

           credit.setAmount(4000);

           map.put("credit", credit);

     }

}

 

public class Client {

 

     public static void main(String[] args) {

           PaymentCache cache= new PaymentCache();

           cache.loadCache();

          

           Payment payment=cache.getPayment("cash");

           payment.makePayment();

          

           Payment payment1=cache.getPayment("credit");

           payment1.makePayment();

          

     }

}

 

Output:

Payment of 2000.0 by Cash

Payment of 4000.0 by Credit Card

Application:

Session replication from one server to another server.

Generating the GUI having many numbers of similar controls.

Advantage of Prototype Pattern:

It reduces the need of subclassing.

It hides complexities of creating objects.

The clients can get new objects without knowing which type of object it will be.

It lets you add or remove objects at runtime.

Usage of Prototype Pattern:

When the classes are instantiated at runtime.

When the cost of creating an object is expensive or complicated.

When you want to keep the number of classes in an application minimum.

When the client application needs to be unaware of object creation and representation.

 

read less
Comments
Dislike Bookmark

Take BA Tuition from the Best Tutors

  • Affordable fees
  • Flexible Timings
  • Choose between 1-1 and Group class
  • Verified Tutors

Lesson Posted on 25/05/2017 Learn Programming in JAVA +5 Java Java Programming Advanced Java coaching Java Programming Core Java

How to create a Singleton class?

Gpcomptech

GPCompTech (GP Computer Technologies) is a software training institute located in Chandanagar Hyderabad,...

How to create a Singleton class: Q) What is a singleton class? A) In simple words, a singleton class is a class which can have only one instance at any point of time throughout the application and provides a global point of access to its instance. Q) How can you create a singleton class? A) class... read more

How to create a Singleton class:

Q) What is a singleton class?

A) In simple words, a singleton class is a class which can have only one instance at any point of time throughout the application and provides a global point of access to its instance.

 

Q) How can you create a singleton class?

A)

class Singleton {

       public static final Singleton INSTANCE = new Singleton();

       private Singleton() {

       }

}

                 This is a simple example for a singleton class where I used a public static final INSTANCE variable and initialized it with a Singleton object. Since INSTANCE is public static final, it can’t be reassigned and it is thread safe as well.

                 Singleton’s constructor is made private to prevent the instantiation of Singleton class from other classes. That means no other class can create an object for Singleton class with the new() operator and also no other class can extend this Singleton class with extends keyword. If any class wants to have an instance of Singleton it can have by accessing INSTANCE field of Singleton class like Singelton. INSTANCE as its static.

 

  1. Q) So here, Singleton instance will be created at the time of class loading that means when the Singleton class is loaded by JVM into memory. So it’s an early loading/instantiation of Singleton class and it occupies memory even when its not required yet, so what If we want this singleton instance to be created when it’s really required?

 

  1. A) I understand that you are interested in lazy loading/instantiation of Singleton. Here it is

 

class Singleton {

       private static Singleton INSTANCE;

       private Singleton() {

       }

       public static synchronized Singleton getInstance() {

              if (INSTANCE == null) {

                     INSTANCE = new Singleton();

              }

              return INSTANCE;

       }

}

 

  1. Q) You synchronized the whole method

       public static synchronized Singleton getInstance()

Don’t you see any performance overhead with this approach?

Only one thread can access the method getInstance at a time to get the Singleton instance and rest of all other threads need to wait even though INSTANCE is not null as its already created.

A) Let me create it using synchronized block instead of synchronized method, here how it goes

 

class Singleton {

       private static Singleton INSTANCE;

       private Singleton() {

       }

       public static Singleton getInstance() {

              if (INSTANCE == null) {             //----- 1st

                     synchronized (Singleton.class) {

                           if (INSTANCE == null) {   //----- 2nd

                                  INSTANCE = new Singleton();

                           }

                     }

              }

              return INSTANCE;

       }

}

 

  1. Q) Why do you use null check twice here?
  2. A) I think I don’t need to explain you why did I use first null check, as you know I am going to create Singleton instance in case INSTANCE is null otherwise I ll return the already created instance.

2nd null check is being used to ensure thread safety.

For suppose, 2 threads are concurrently trying to get the access for getInstance() and two threads are gone through the 1st null check and trying to enter into synchronized block, but only one thread(assume thread-1) got the lock on Singleton.class’s  object and enters the synchronized block while the other thread (assume thread-2)waiting for the lock. Once thread-1 went through 2nd null check then it creates a Singleton instance as INSTANCE is null and leaves the synchronized block and thus releases lock. Now, the waiting thread ( thread-2) holds the lock and enters the synchronized block.

 

If there is no 2nd null check there then there is a chance for the thread-2 to create another instance of Singleton class and thus it breaks the singleton here. For that reason we have 2nd null check here. So the thread-2 sees that INSTANCE is not null and comes out from the synchronized block without creating Singleton instance.

 

  1. Q) Ok. So double checking is for thread safety of a singleton.

 

 

  1. A) yes

 

Q) Do you think that, this Singleton class is still singleton?

I can break your singleton with the help of reflection like below

 

public class Test {

       public static void main(String args[]) {

              Singleton singleton1 = Singleton.getInstance();

              Singleton singleton2 = null;

              try {

                     // Test is package name contains Singleton class

                     Class singletonClass = Class.forName("Test.Singleton");

                     // as we know there is only one private constructor

                     Constructor cons = singletonClass.getDeclaredConstructor();

                     cons.setAccessible(true);

                     singleton2 = (Singleton) cons.newInstance();

                     System.out.println(singleton1 == singleton2 ? "Objects are equal" : "Objects are different");

              } catch (ClassNotFoundException | InstantiationException

                           | IllegalAccessException | IllegalArgumentException

                           | InvocationTargetException | NoSuchMethodException

                            | SecurityException e) {

                     e.printStackTrace();

              }

       }

}

 

  1. A) In that case I can implement Singleton like below for not to be broken with reflection

class Singleton {

       private static Singleton INSTANCE;

       private Singleton() {

              if (INSTANCE != null)

                     throw new RuntimeException(

                                  "Singleton can not be created more than once.");

       }

       public static Singleton getInstance() {

              if (INSTANCE == null) {

                     synchronized (Singleton.class) {

                           if (INSTANCE == null) {

                                  INSTANCE = new Singleton();

                           }

                     }

              }

              return INSTANCE;

       }

}

 

Private constructor will be called to instantiate the Singleton object through reflection. So we can throw some exception If INSTANCE field is not null (that means its already created).

 

  1. Q) So you think this implementation saves your Singleton from being broken from reflection. In my previous program, I am trying to create a Singleton object (singleton1) with the help of getInstance() and after that trying to create another object (singleton2) with the help of reflection. What happens If I do this in reverse like below

 

public class Test {

       public static void main(String args[]) {

//            Singleton singleton1 = Singleton.getInstance();

              Singleton singleton2 = null;

              try {

                     // Test is package name contains Singleton class

                     Class singletonClass = Class.forName("Test.Singleton");

                     // as we know there is only one private constructor

                     Constructor cons = singletonClass.getDeclaredConstructor();

                     cons.setAccessible(true);

                     singleton2 = (Singleton) cons.newInstance();

                     Singleton singleton1 = Singleton.getInstance();

                     System.out.println(singleton1 == singleton2 ? "Objects are equal" : "Objects are different");

              } catch (ClassNotFoundException | InstantiationException

                            | IllegalAccessException | IllegalArgumentException

                           | InvocationTargetException | NoSuchMethodException

                           | SecurityException e) {

                     e.printStackTrace();

              }

       }

}

 

Output:

 Objects are different

 

Here, If I try to create a Singleton object (singleton2) with the help of reflection first then it can proceed to create an Singleton object as the static field INSTANCE is still null at that time as getInstance() is not yet invoked. So we are allowed to create an many as objects we want for the Singleton using reflection before getInstance() is invoked and thus breaks the singleton. What do you say?

 

  1. A) Yeah, you are right. Let me come to you with slightly modified implementation of Singleton which protects itself from being broken with reflection.

 

class Singleton {

       private static Singleton INSTANCE;

       private static boolean instanceCreated = false;

       private Singleton() {

          & read less

Comments
Dislike Bookmark

About UrbanPro

UrbanPro.com helps you to connect with the best BA Tuition in India. Post Your Requirement today and get connected.

Overview

Lessons 20

Total Shares  

+ Follow 50,664 Followers

You can also Learn

Top Contributors

Connect with Expert Tutors & Institutes for Programming in JAVA

x

Ask a Question

Please enter your Question

Please select a Tag

X

Looking for BA Tuition Classes?

The best tutors for BA Tuition Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Take BA Tuition with the Best Tutors

The best Tutors for BA Tuition Classes are on UrbanPro

Book a Free Demo

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more