Found 9321 Articles for Object Oriented Programming

How to swap or exchange objects in Java?

George John
Updated on 23-Jun-2020 15:05:26

324 Views

Java uses call by value while passing parameters to a function. To swap objects, we need to use their wrappers. See the example below −Example Live Demopublic class Tester{    public static void main(String[] args) {       A a = new A();       A b = new A();       a.value = 1;       b.value = 2;       //swap using objects       swap(a, b);       System.out.println(a.value +", " + b.value);       Wrapper wA = new Wrapper(a);       Wrapper wB = new ... Read More

How to prevent Serialization to break a Singleton Class Pattern?

Arjun Thakur
Updated on 23-Jun-2020 14:38:06

499 Views

A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using serialization, we can still create multiple instance of a class. See the example below −Example - Breaking Singleton Live Demoimport java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Tester{    public static void main(String[] args)    throws ClassNotFoundException, IOException{       A a = A.getInstance();       A b ... Read More

How to prevent Reflection to break a Singleton Class Pattern?

Chandu yadav
Updated on 23-Jun-2020 14:43:37

681 Views

A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using reflection, we can still create multiple instance of a class by modifying the constructor scope. See the example below −Example - Breaking Singleton Live Demoimport java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Tester {    public static void main(String[] args) throws    InstantiationException, IllegalAccessException,    IllegalArgumentException, InvocationTargetException{       A a = A.getInstance();     ... Read More

How to prevent Cloning to break a Singleton Class Pattern?

George John
Updated on 23-Jun-2020 14:27:50

1K+ Views

A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −Example - Breaking Singletonpublic class Tester{    public static void main(String[] args)    throws CloneNotSupportedException {       A a = A.getInstance();       A b = (A)a.clone();       System.out.println(a.hashCode());       System.out.println(b.hashCode());    } } ... Read More

How to prevent object of a class from garbage collection in Java?

Ankith Reddy
Updated on 23-Jun-2020 14:30:45

209 Views

If a object is no more referenced by a live reference then it becomes eligible for garbage collection. See the example below −Examplepublic class Tester{    public static void main(String[] args) {       test();    }    public static void test(){       A a = new A();    } } class A {}When test() method complete execution, the a object is no more referenced and is eligible for garbage collection. Java garbage collector will deallocate the object when it runs.To prevent garbage collection, we can create a static reference to an object and then ... Read More

Java program to check occurrence of each character in String

Chandu yadav
Updated on 18-Jun-2024 15:18:37

18K+ Views

In order to find occurence of each character in a string we can use Map utility of Java. In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before. Now when a character repeats during insertion as key in Map increase its value by one. Continue this for each character untill all characters of string get inserted.Examplepublic class occurenceOfCharacter {    public static void main(String[] args) {       String str = "SSDRRRTTYYTYTR"; ... Read More

How to parse JSON in Java?

Arushi
Updated on 22-Jun-2020 11:30:03

3K+ Views

This articles covers how to encode and decode JSON objects using Java programming language. Let's start with preparing the environment to start our programming with Java for JSON.EnvironmentBefore you start with encoding and decoding JSON using Java, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed JSON.simple and have added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH.Mapping between JSON and Java entitiesJSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding.JSONJavastringjava.lang.Stringnumberjava.lang.Numbertrue|falsejava.lang.Booleannullnullarrayjava.util.Listobjectjava.util.MapOn decoding, ... Read More

How to measure the time taken by a function in Java?

Arushi
Updated on 22-Jun-2020 11:30:52

258 Views

java.lang.System.currentTimeMillis() method can be used to compute the time taken by a function in java. Trick is simple. Get the before time and after time using currentTimeMillis() where before time is the time when method is invoked and after time is when method has executed. See the example below −Example Live Demopublic class Tester{    public static void main(String[] args) {       long startTime = System.currentTimeMillis();       longRunningMethod();       long endTime = System.currentTimeMillis();       System.out.println("Time taken: " + (endTime -startTime) + " ms");    }    private static void longRunningMethod() {       try {          Thread.sleep(1000);       } catch (InterruptedException e) {          e.printStackTrace();       }    } }OutputTime taken: 1000 ms

How to compare two arrays in Java?

Paul Richard
Updated on 22-Jun-2020 11:31:37

13K+ Views

Arrays can be compared using following ways in JavaUsing Arrays.equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method.Using Arrays.deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.Using == on array will not give the desired result and it will compare them as objects. See the example below for each of the comparison way.Example Live Demoimport java.util.Arrays; public class Tester{    public static void main(String[] args) {       int[] array1 = {1, 2, 3};       int[] ... Read More

How to make an object eligible for garbage collection in Java?

Fendadis John
Updated on 30-Jul-2019 22:30:23

154 Views

Java Garbage collector tracks the live object and objects which are no more need are marked for garbage collection. It relieves developers to think of memory allocation/deallocation issues. JVM uses the heap, for dynamic allocation. In most of the cases, the operating systems allocate the heap in advance which is then to be managed by the JVM while the program is running. It helps in following ways:  Faster object creation as Operating system level synchronization is no more needed for each object. Object Allocation takes some memory and increases the offset. When an object is not required, garbage collector ... Read More

Advertisements