Skip to main content

Posts

Java - How to escape % in String.format?

Introduction In this tutorial, we will learn how to skip or display % in a String using String.format MyStringFormatter .java  public class MyStringFormatter { public static void main(String[] args) { System.out.println(String.format( "Your score is %d % " ,65) ); } } Output Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ' ' at java.base/java.util.Formatter.checkText(Formatter.java:2732) at java.base/java.util.Formatter.parse(Formatter.java:2718) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2897) at MyStringFormatter.main(MyStringFormatter.java:4) Solution To display a % in String when using String.format , you have to escape a % with % i.e. %% public class MyStringFormatter { public static void main(String[] args) { System.out.println(String.fo

spark-submit java.lang.NoClassDefFoundError: scala/runtime/java8/JFunction1$mcII$sp

Exception  Exception in thread "main" java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: scala/runtime/java8/JFunction1$mcII$sp         at SparkPi$.main(SparkPi.scala:14)         at SparkPi.main(SparkPi.scala)         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) Problem: It seems that you have compiled and generated your jar file with an upper version of the Scala compiler than the one spark is using. Solution Step 1 Run the following command from spark-installed-directory\bin spark-shell.cmd (or.sh) and note the Scala version, My Spark version was 2.4.3 and Scala version 2.11.12 Step 2 Change the scala version into your build.sbt to 2.11.12 (per your configuration). My build.sbt is name := "SparkPi Project" version := "1.0" scalaVersion := "2.11.12" val sparkVersion = "2.4.5&qu

Set default JAVA_HOME path for Apache Spark

Introduction  Currently, Apache Spark does not support JAVA 11 and later versions. When you try to run the Spark application, you may get the following exception Exception pyspark.sql.utils.IllegalArgumentException: 'Unsupported class file major version 55' Solution There are different ways to fix this exception like Set environmental variable for JAVA_HOME Modify Apache spark environment configuration file i.e. spark-env.sh or spark-env.cmd In this post, I will help you to set JAVA_HOME using Spark's configuration file Windows Environment  Go to the spark-directory\ conf Create a file by the name of spark-env.cmd  Paste the following line spark-env.cmd                   set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_201 Linux and Mac Go to the spark-directory\ conf Open spark-env.sh Paste the following line spark-env.cmd        export JAVA_HOME=$(user/Java/jdk1.8.0_201 -v 1.8) Note : Change the installed Java directory accordingly.

JDBC – PreparedStatement– How to Set Null value?

Introduction Java Database Connection (JDBC) API allows the Java programmers to access different relational and NoSQL databases like Oracle, MySQL, SQL Server, etc. It helps to store, access and manipulate the data stored in these databases. In this post, we will explore how to set the NULL values in PreparedStatement. Null String data type For String data type, it does not matter if the value to be set as a parameter in the SQL query is NULL.   Other data types like Integer, Float, Double, Date, etc. For data types like Integer , Float , Double , Date we have to explicitly call the setNull method. Example String name = null ; Long id = null ; PreparedStatement ps = connection.prepareStatement("select * from person where first_name = ? and id = ?");  ps.setString(1,name); The above line will execute without throwing any exception ps.setLong(2, id); In the above line of code, since id is null, it will throw java.lang.NullPoi

Apache Maven - How to set network proxy settings?

In the following post, we learned how to install Apache Maven on Windows 10 How to install Apache Maven on Windows? If your development PC is behind a proxy network, you will not be able to add Java dependencies through Maven. Luckily Maven provides us with proxy settings. Add your network proxy to Maven's proxy settings STEP 1:  Navigate to your maven's directory and open conf folder E:\apache-maven-3.6.2\conf STEP 2:  Open settings.xml in your favorite text editor STEP 3: Uncomment the proxy tag inside proxies tag and add the values according to your network's proxy settings. <proxy>       <active>true</active>       <protocol>http</protocol>       <username>proxyuser</username>       <password>proxypass</password>       <host>proxy.host.net</host>       <port>80</port>       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>     </proxy>

How to install Apache Maven on Windows 10?

Apache Maven is a Java tool that helps in building and managing the Java project. It is based on the concept of Project Object Modle(POM). It helps the Java developers to manage the project's JAR files in a central repository and those JAR files can be shared across the project. Maven project has the following objectives makes the build process easy provides a uniform build system  and many more In this post, we will learn how to install the Apache Maven on Windows (10). STEP 1: Download and install Java Download Java from  https://www.java.com/en/download/ . and install it. STEP 2: Download Apache Maven Download Apache Maven from  https://maven.apache.org/download.cgi  and extract it on your local machine like I have unzipped it to  E:\apache-maven-3.6.2 STEP 3: Set the JAVA_HOME environmental variable Right Click This PC ->  Properties -> Advanced system settings -> Environmental Variables Open Environmental Variables Click on N

How to convert a String to int in Java?

Introduction In this post, we will learn to convert String to int primitive data type. Java provides the Integer wrapper class to convert a String to int. Integer.parseInt(String) String numberString = "134"; int number = Integer.parseInt(numberString ); System.out.println(number); Output : 134 Integer.valueOf(String) String numberString = "134"; int number = Integer.valueOf(numberString ); System.out.println(number); Output : 134 The following code will throw NumberFormatException //134a cannot be converted to Integer String numberString = "134a"; int number = Integer.valueOf(numberString ); System.out.println(number); Exception in thread "main" java.lang.NumberFormatException: For input string: "134a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.valueOf(Unknown Source) at StringExample.main(StringExample

Top 10 mostly asked Java String Interview Questions

Introduction String is the most widely used class in any language. In this post, we will explore String in Java context. This post will help you to understand the String in-depth and to answer String related questions in a Job interview. 1. What is String? String is a final class in Java and not a primitive data type like int, float, etc. It is defined in java.lang package and therefore available by default. 2. How to create objects of String? There are two ways to create String a. String literals String str = "abc"; b. Using new operator String str = new String("abc"); 3. Where is String stored in memory? String literals are stored in the String constant pool. A string is called immutable or constant i.e. once created then it can not be changed. Whenever we create a String using double quotes (String literal), Java looks into the String constant pool if an object with the same value is present, it returns the reference to that object

Prime Anagrams - Comparing Anagrams using Prime Numbers

Introduction In this post, we will use prime numbers to compare anagrams. We will assign the prime number to each character in a string and then multiply them. Two strings will be equal if their product is the same. Implementation in Java public class PrimeAnagram { static int [] alphaPrime = {5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107}; static String alphabets = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { System.out.println(isPrimeAnagram("parse", "spare")); } private static boolean isPrimeAnagram(String value1,String value2) { return getPrime(value1) == getPrime(value2); } private static int getPrime(String value) { value = value.toLowerCase(); int productValue = 1; for(int index = 0; index < value.length(); index++) { productValue *= alphaPrime[ alphabets.indexOf(value.charAt(index)) ]; } return productValue; } } Conclusion We

Often asked interview question to write code of Singleton Pattern?

Introduction I have been often asked this question in an interview to write a code of Singleton pattern. I have noticed that developers have the knowledge of what is Singleton pattern but often they forget the key points regarding its implementation. In this post, I will highlight the key points to remember for your upcoming interview. Implementation public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } Key Points to remember a) instance is declared as private and static  b) The constructor is declared as private c) getInstance method is static and synchronized to make it thread free Conclusion In this post, we learned how to implement the Singleton pattern using Java language. We have also noted down the key points to remember.Please leave your comments in the comments box.