Skip to main content

Posts

Showing posts with the label Java Program

Arrays : Finding the Element in array where next element is +1, +0 or -1

Problem Statement You are given an array where each element follows the rule that given any index, the number at that index will either be  +1 of the number at that index. +0 of the number at that index. -1 of the number at that index. Suppose the array is  Sample Input arr       = {1,2,3,2,3,4,5,6,7,6,5,4,5,6,4,4,4,4}; search = 5 Sample Output 6  (First occurrence of search ) Sample Input arr       = {1,2,1,2,1,2,1,2,1,2}; search = 5 Sample Output 1  ( Element is not found in the array) Algorithm Star iterating from start of the array. Check if the value at the index is same as the search value if yes, then return the index if no, then increment the index counter by modulus of difference of value to search and value at index return -1 if value to search does not exist in the array. Java Program view plain copy to clipboard print ? package  com.ekiras.arrays;      public   class  SearchEl...

Java : How to generate a random number between two given numbers

How to find a Random Number Between two given Numbers Suppose we want to generate a number between two given numbers X and Y then we can use the following two approaches. Approach 1 Generate a random number between 0 to (Y - X ) just add this to X. i.e X+N For, example if we have to calculate a random number between 100 and 150, then in that case X = 100 , Y = 150, Then we calculate a number between 0 to (150-100)  i.e  0 to 50. Thus, we just need to add this to 100 to get a number in range of 100 to 150. Approach 2 Generate a number N using the Math.random() method such that ( N < X< Y ) If N <= Y - X  then result is X+N else, we add the difference of N from the difference of X and Y i.e X + ( N - ( Y - X )) For, example if we have to calculate a random number between 100 and 150, then in that case X = 100 , Y = 150, Case 1 : N = 24 ( less than Y- X) In this case result will be X + N that is 24 + 100 = 124 Case 2 : N = 88 ( greater than Y-X ) In this case resul...

Java : How to write a File in Java using FileWriter

Write a File in Java using FileWriter You can write a file using FileWriter as shown in the code below. package com.ekiras.demo; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; class FileDemo { public static void main(String args[]) { readFile(); } public static void readFile() { System.out.println(" Start :: writing file"); try { File file = new File("/home/ekansh/myFile.txt"); FileWriter fileWriter = new FileWriter(file); fileWriter.write("hello, this file is created at :: " + new Date()); fileWriter.flush(); fileWriter.close(); System.out.println(" End :: writing file"); } catch (IOException e) { e.printStackTrace(); } } } You can write the data using the write() method and then call the flush() method to force the os to write to the file, finally close() method to close the file writer object, so that it can be garbage collected.

How to find all Permutations and Combinations of a String

Algorithm Used We will be using the following algorithm to find all the permutations of a string Take the first letter as a prefix and find all the permutations of the remaining string. Each of the prefix will also be a permutation itself. If you want to find all the permutations of string with same length as the original string then skip the prefix's as the combination. public class Permute { static String codes = "eki"; static int count; public static void main(String args[]) { permute("", codes); System.out.println(">>>>>>>" + count); } public static void permute(String prefix, String str) { System.out.println(prefix); count++; int n = str.length(); if (n == 0) { System.out.println(prefix); } else { for (int i = 0; i < n; i++) permute(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); } } } The above code will give the following output e ek eki eki ei eik eik k ke kei kei ki...

Exception in thread java.util.ConcurrentModificationException

Points To Remember ConcurrentModificationException  occurs when the you you try to modify the collection you are using or iterating. It can be prevented if you create a new object of that collection and do operations on that and then assign it back to the original object. java.util.ConcurrentModificationException In the following code we will be iterating on the list and trying to remove the null objects from the list. import java.util.*; public class Demo { public static void main(String args[]) { // create an array of string objs String init[] = { "One", "Two", null, null, "One", "Two", null, "Three", "Four", "Two", null }; // create two lists List<String> list = new ArrayList(Arrays.asList(init)); for (String str: list) { if (str == null) list.remove(str); } System.out.println("List value: " + list); } } The above code will throw the following Exception Exception in thread ...

How to remove all nulls from a Collection in Java

How to remove nulls from a List in Java One way is to iterate the objects from the Collection ( like List, Array, Map etc) and remove null objects. Remove a particular object from List, Array or Map by searching the object and then removing it. Using the Collections.singleton(T o)  method from the java.util  package and then it will remove all the objects from the collection. Removing Objects in Traditional Way. We will be taking the following list of String for all our Examples String init[] = { "One", "Two", "One", "Three", "One", "Two", "Three","Four", "Two" }; Here we will remove the objects by finding it from the Collection. List list = new ArrayList(Arrays.asList(init)); list.remove("One"); System.out.println("List value: "+list); list.remove("Two"); System.out.println("List value: "+list); list.remove("Three"); System.out.println("List ...

How to delete a Folder in Java

Points To Remember Before deleting the file you need to check if you have permission to delete file using method canWrite() file specified exists exists() Deleting the file in Java Test.java import java.io.*; class Test{ public static void main(String args[]){ File file = new File("/home/ekansh/test"); if(file.isDirectory()){ if(file.delete()) System.out.println("Success ! Folder deleted."); else System.out.println("Failure ! Folder not deleted."); }else System.out.println("FOLDER DOES NOT EXIST"); } } Success ! Folder deleted.

How to create Nested folders in Java

Points To Remember You need to check the following things fro creating the nested folders If it is a directory by method isDirectory() If it exists by method exists() You might need to check if you have write permissions to create folder by method  canWrite() How to create Nested Folders/Directories in Java This is how yo can create the nested folders in java. CreateNestedFolders.java import java.io.*; class CreateNestedFolders{ public static void main(String args[]){ File file = new File("/home/ekansh/test/1/2/3/abc"); if(!file.canWrite()){ // check if user have write permissions if(!(file.exists() && file.isDirectory())){ if(file.mkdirs()) System.out.println("Success ! Folders created."); else System.out.println("Failure ! Folders not created."); } }else{ System.out.println("PERMISSION DENIED"); } } } Success ! Folders created.

How to convert the Base of a Decimal Number in Java

Points To Remember You can convert the number from decimal to any base by dividing the number by the base till the number is either 0 or less than the base it self and counting the remainders in a reverse order. Program : Convert the base of a Decimal Number import java.util.Scanner; class ConvertBase{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the Original NUmber"); int originalNumber = sc.nextInt(); System.out.println("Enter the base for conversion"); int base = sc.nextInt(); String convertedNumber = new ConvertBase().convert(originalNumber,base); System.out.println("Original Number = "+originalNumber); System.out.println("Converted NUmber = "+convertedNumber); } public String convert(int original, int base){ String number = ""; String converted =""; while(original != 0){ int digit = original % base; original /= bas...

How to create a Custom Annotation in Java

Points To Remember An annotation can be used as a replacement of interfaces. You can make both empty/marker annotations and annotations with methods. You can define the retention policy for the annotation and where the annotation can be used. Program : Create A Custom Annotation The following program creates a custom empty annotation. import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Table { public String name() default "table"; } The above class can be used as a custom annotation with only one method name with a default value. This annotation can be applied only to the class i.e it is class level annotation and can not be applied to any member of a class. The following program creates a custom annotation with methods defined. import java.lang.annotation.ElementType; import java.lang.ann...

How to find all the packages in a Project with a Prefix

Points To Remember You to need to add the Reflections jar in the class path.  You will not be able to load the packages other than the current package using Package.getPackages()  since current class loader will not be able to reach them. Program : Scan all packages with a Prefix You can use  Package.getPackages()  approach to find all the packages that are in the current class loader. But you will not be able to get the packages that are not in the class path of the current class loader. So you need to include the jar "Reflections"  to do this for you. All the dependency to the project via pom.xml  or you can add the jar in the class path of the project. The following code will list all the packages in the project that start with the prefix in the project. public static Set<String> findAllPackagesStartingWith(String prefix) { List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(Classpat...

How to make a Class Singleton

Points To Remember To make a class Singleton the class must satisfy the following points No class should be able to make the object of this class. Only one object of this class must me there that is used by all the other classes. The class must have a private constructor so that no class should be able to make object of this class. Class should make a final object of the class itself and return it whenever asked for. Class should have a static method that returns the object of this class. Demo : Create a Singleton Class Class : Singleton.java public class Singleton{ private String name = "Singleton Object"; private static final Singleton object = new Singleton(); private Singleton(){ } public static Singleton getObject(){ return object; } public String getName(){ return name; } } Class : SingletonTest.java class SingletonTest{ public static void main(String args[]){ Singleton obj = Singleton.getObject(); System.out.println(obj.getName()); } } T...

How to flatten a Nested List in Java

Points To Remember See  How to create a Nested List from a String input.  We use this class to create a nested list and then we try to flatten this list. Program : Flatten a Nested List  Here we write a Java function that will accept a nested ist upto any level of nesting and flatten this list. import java.util.List; import java.util.LinkedList; import java.util.Scanner; class FlattenList{ public static void main(String args[]){ CreateList obj = new CreateList(); // Get the nested list sample List<Object> nestedList = obj.createNestedList(); System.out.println("-----------------------------------"); // Print the nested list System.out.println("Nested List = " + nestedList); // Print the sample nested list after flattening the list System.out.println("Flatten List = " + new FlattenList().flattenList(nestedList)); } public List<Integer> flattenList(List<Object> nestedList){ List<Integer> ...

How to create a Nested List upto any level of nesting

Points To Remember The Correct Datatype for creating a Nested List will be List<Object>,  because we have to store either a integer number or a list inside the list. We can not have a nested list like  List<List<Integer>>  because it will not be able to hold the integer values. It can only hold a list. The List we create can be nested to any level. Program : Create A nested list upto any level Here we suppose that we get a String input of the list that we have to create. The following program accepts the list as a String and returns after converting the list to a nested list up to any level. import java.util.*; import java.util.LinkedList; import java.util.Scanner; public class CreateList{ public static void main(String args[]){ CreateList obj = new CreateList(); System.out.println(obj.createNestedList()); } public List<Object> createNestedList(){ Scanner sc = new Scanner(System.in); System.out.println("Enter the Nested List")...

Test CAS Rest API from Java Code

Points To Remember Make sure that your CAS Server is up and running. How to set up CAS Rest api with JDBC Authentication. You have created a database and have dummy data in it. Program : Test CAS Rest Api from a Java Code You can use the following piece of code to test the CAS Rest API. You need to follow the following points for Authentication a user on CAS You need to make a GET or POST call depending on your CAS server setup. If the Username and Password are correct then you will get a TGT (Ticket Granting Token) Now we will make a call to the service url of our application to get the Service Ticket. On success you will get a Service Ticket If you have service the Service Token,  then you have successfully authenticated the user. Save this service ticket in a cookie or session, since a service ticket can be used only once You will get the following type of response if everything is working fine. string s = username=admin%40gmail.com&password=igdefault 201 https://ekansh:84...

How to make Thread by extending Thread class

Points To Remember We can implement Runnable interface or extend Thread class to create threads. We have to override the run()  method to define the functionality of thread. We should call start()  method to start execution of a thread as a new entity, if we call run() method on a thread then it will not start a new thread. We cannot guarantee which thread will execute first even if we prioritize the threads. A thread whose run() method is executed completely reaches the dead state and cannot be invoked again. Program : Making 3 Threads using Thread Class In the following example we are making three different threads in the class Test which extends the Thread class. We just pass a parameter name to each object of Test thread to distinguish between them. class Test extends Thread{ String name; public Test(String name){ this.name = name; } public static void main(String args[]){ System.out.println("main started"); Thread t1 = new Thread(new Test("Th...

Find the word with maximum occurrences in a line

Question : Count the number of occurrences of each word in a String Write a program to accept a string from the user and print the number of times each word of the string occurs in the input string. e.g If the input is "Tinkle Twinkle little star" then the output should be Twinkle  - 2 little        -1 star         -1 Program  import java.util.HashMap; import java.util.Scanner; class CountOccurances{ public static void main(String args[]){ CountOccurances obj = new CountOccurances(); System.out.println("Enter the line of String"); String max = obj.maxOccurances(new Scanner(System.in).nextLine().split(" ")); System.out.println("Word with maximum occurances = " + max); } public String maxOccurances(String[] str){ HashMap<String,Integer> map = new HashMap<String,Integer>(); for(int itr=0;itr<str.length;itr++){ if(map.containsKey(str[itr])){ map...

Program to print Numbers in Words

Question : Print a given number in Words Write a program to print a number and convert it into words. Suppose we enter a number 132 the output should be "one hundred thirty two" 5234 the output should be "five thousand two hundred thirty four" 90 the output should be "ninety" Program : Print Numbers in Words import java.util.Scanner; class NumberInWords{ String once[] = {"zero","one","two","three","four","five","six","seven","eight","nine"}; String tens[] = {"ten","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninty"}; public static void main(String args[]){ NumberInWords obj = new NumberInWords(); System.out.println("Enter the number to be converted to words"); Scanner sc = new Scanner(System.in); System.out.println(obj.get...

How to Iterate over HashMap Collection in Java

Points To Remember A HashMap contains objects in key-value pair. We can use enumeration, iterator , for loop (jdk v1.5 onwards) and lamda expression ( jdk v1.8) We can add values to HashMap using put(key,value). We can get all keys by . keySet()  and value of a key using .get(key) Method 1: Traverse A HashMap using "for" loop The below example shows how we can traverse a HashMap in java using advanced for loop. import java.util.HashMap; class Test{ public static void main(String args[]){ HashMap<String, String> map = new HashMap<String, String>(); map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key 3","value 3"); map.put("key 4","value 4"); map.put("key 5","value 5"); // Iterating Map using advanced for loop available from jdk v1.5 onwards // Iterating over Values for(String value : map.values()){ System.out.p...

How to get all Declared Fields in a Class

Points To Remember We can use reflection to find all the fields available within a class. We can get all the declared fields in a class by getDeclaredFields() . We can search for any field in a class by using getField().  It throws  NoSuchFieldException  if the field does not exist in the class. Program : Get all the declared fields in a class import java.lang.reflect.Field; class SampleClass{ String s1 = "Class variable"; int a = 123; } class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass"); Field feilds[] = obj.getDeclaredFields(clazz); for(Field feild : feilds){ System.out.println(feild); } }catch(Exception e){ e.printStackTrace(); } } public Field[] getDeclaredFields(Class clazz){ return clazz.getDeclaredFields(); } } java.lang.String SampleClass.s1 int SampleClass.a Program : Get a particular field declared in a class. import java.la...