Pages

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, November 17, 2021

Java ArrayList Add() - How to add values to ArrayList?

How to add values to ArrayList?

In this post, we will learn how to add elements to ArrayList using java inbuilt methods. ArrayList class in java has been implemented based on the growable array which will be resized size automatically. Maintains the order of insertion of values added to it and permits adding all kinds of values including primitives, user-defined classes, wrapper classes and null values.

java arraylist add


Java ArrayList add methods:

Java ArrayList add method is overloaded and the following are the methods defined in it.

1) public boolean add(E e)
2) public void add(int index, E element)

Tuesday, November 16, 2021

Java String toCharArray() - How to convert string to char array?

Java String toCharArray():


The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.

Returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.


Java String toCharArray() with example - Convert string to char - Internal


Syntax:
public char[] toCharArray​()

Sunday, November 14, 2021

Java - How To Compare Two Strings Lexicographically | String compareTo method works internally

Java - How To Compare Two Strings Lexicographically


Today, we will learn about comparing two strings lexicographically in Java. Many of you might be aware of how to compare two strings in java but not in a manner lexicographically. Lexicographically word looks somewhat new and weird. Do not worry, we will go step by step easily understandable way and how it works internally.

First, We will go through examples of how to compare two string values are the same/equal or not.

Compare Two Strings Lexicographicall

Saturday, November 13, 2021

Java String format() Examples

Java String format​() method

String format method is used to format the string in the specified format. This method can be used as String output format by passing multiple arguments because the second parameter is the variable-arguments(Var-Args). Recommend to read in-depth usage of Var-Args in Java. We can pass any type of object here such as String, Float, Double etc together. You will find the examples on each in this course.

This format method is introduced in java 1.5 version and it is overloaded and static methods

Java String format() Examples

Java String format​() method Syntax: 

// Takes default locale 
public static String format​(String format, Object... args)
//Takes passed locale instead of default locale value
public static String format​(Locale l, String format, Object... args)

Sunday, November 7, 2021

Java String to Float & Float to String Examples

1. Overview

In this tutorial, We'll learn how to convert String to Float value and Float to String value in java programming.

This can be done in several ways by using simple java api methods and also using third party api methods.

Java String to Float & Float to String Examples


2. Java String to Float Conversion


Converting string to float is done in mainly three ways using following methods.

All of these methods works for negative values alos.

  • Float.parseFloat()
  • Float.valueOf()
  • Float(String) constructor

2.1 Java String to Float Using Float.parseFloat()


Float.parseFloat() method is a static method from Float class and parseFloat() method returns primitive float value.

Look at the below example.
package com.javaprogramto.programs.strings.tofloat;

public class StringToFloatExample1 {

	public static void main(String[] args) {

		String floatValueInString1 = "789.123F";

		float floatValue1 = Float.parseFloat(floatValueInString1);

		System.out.println("Float value in String : " + floatValueInString1);
		System.out.println("String to Float value : " + floatValue1);

		String floatValueInString2 = "123.45";

		float floatValue2 = Float.parseFloat(floatValueInString2);

		System.out.println("Float value in String : " + floatValueInString2);
		System.out.println("String to Float value : " + floatValue2);
	}
}

Output
Float value in String : 789.123F
String to Float value : 789.123
Float value in String : 123.45
String to Float value : 123.45

String value can take the F value at the end of the string to denote the value is float. If F is present in the middle of the string or any other alphabet then it will throw NumberFormatException.

2.2 Java String to Float Using Float.valueOf()


Float.valueOf() method takes the String as input and returns Float wrapper instance.

Below is the example.
package com.javaprogramto.programs.strings.tofloat;

public class StringToFloatExample2 {

	public static void main(String[] args) {

		String floatValueInString1 = "789.123F";

		Float floatValue1 = Float.valueOf(floatValueInString1);

		System.out.println("Float value in String : " + floatValueInString1);
		System.out.println("String to Wrapper Float value : " + floatValue1);

		String floatValueInString2 = "123.45";

		Float floatValue2 = Float.valueOf(floatValueInString2);

		System.out.println("Float value in String : " + floatValueInString2);
		System.out.println("String to Wrapper Float value : " + floatValue2);
	}
}

Output is same as above the section.

valueOf() method internally calls parseFloat() method.


2.3 Java String to Float Using Float Constructor


Float constructor takes argument type of String. But this way is deprecated and suggested to use parseFloat() method.

But using of constructor will produce the same results.
package com.javaprogramto.programs.strings.tofloat;

public class StringToFloatExample3 {

	public static void main(String[] args) {

		String floatValueInString1 = "789.123F";

		Float floatValue1 = new Float(floatValueInString1);

		System.out.println("Float value in String : " + floatValueInString1);
		System.out.println("String to Float value using constructor: " + floatValue1);

		String floatValueInString2 = "123.45";

		Float floatValue2 = new Float(floatValueInString2);

		System.out.println("Float value in String : " + floatValueInString2);
		System.out.println("String to Float value using constructor: " + floatValue2);
	}
}


3. Java Float To String Conversion


Next, Let us see how to convert the Float to String value.

Float to String conversions part is already discussed in detail here.

Complete example of float to string conversion with primitive and wrapper objects.
package com.javaprogramto.programs.strings.tofloat;

public class FloatToStringExample {

	public static void main(String[] args) {

		// example 1 - valueOf()
		float primitiveFloat1 = 456.78f;

		String floatInString = String.valueOf(primitiveFloat1);

		System.out.println("Pritive float value 1 : " + primitiveFloat1);
		System.out.println("Float to String 1 : " + floatInString);

		// example 2 - valueOf()

		Float primitiveFloat2 = 456.78F;

		String floatInString2 = String.valueOf(primitiveFloat2);

		System.out.println("Pritive float value 2 : " + primitiveFloat2);
		System.out.println("Float to String 2 : " + floatInString2);

		// Example 3 - toString()

		float primitiveFloat3 = new Float(12367.987);

		String floatInString3 = Float.toString(primitiveFloat3);

		System.out.println("Pritive float value 3 : " + primitiveFloat3);
		System.out.println("Float to String 3 : " + floatInString3);
	}
}


Output:
Pritive float value 1 : 456.78
Float to String 1 : 456.78
Pritive float value 2 : 456.78
Float to String 2 : 456.78
Pritive float value 3 : 12367.987
Float to String 3 : 12367.987

4. Conclusion


In this article, we've seen how to convert String to Float and vice versa with examples.

When a String cannot be converted successfully then java throws runtime NumberFormatException.

Additionally, you can use apache commons beans utils FloatConverter class to convert String to Float.


Saturday, November 6, 2021

Java Format Double - Double With 2 Decimal Points Examples

1. Overview

In this tutorial, We'll learn how to convert the String into double and display double with 2 decimal points or 2 decimal places in java programming.

In the previous article, we have already discussed about how to convert String to Double value in 3 ways.

Getting the double with 2 decimal points can be done in many ways. we'll learn all the possible ways with example programs.
Java Format Double - Double With 2 Decimal Points Examples



2. Double With 2 Decimal Points Using DecimalFormat Class


First, convert the string into double using Double.parseDouble() method.
Next, create the instance of DecimalFormat class as new DecimalFormat("0.00") and then call the format() method which returns the double value in string with 2 decimal places.

Below is the example program.
package com.javaprogramto.programs.strings.todouble.decimal;

import java.text.DecimalFormat;

public class StringToDoubleDecimalsPlaces1 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		// decimalformat class
		DecimalFormat decimalFormat = new DecimalFormat("0.00");
		
		System.out.println("Double with decimal places "+decimalFormat.format(doubleDecimalValue));
	}
}

Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Double with decimal places 9.14

And also this DecimalFormat class provides the additional functionality to rounding up and down the decimal values using setRoundingMode() method as follows.
decimalFormat.setRoundingMode(RoundingMode.UP);
System.out.println("Double with decimal places with rounding up :  "+decimalFormat.format(doubleDecimalValue));

decimalFormat.setRoundingMode(RoundingMode.DOWN);
System.out.println("Double with decimal places with rounding down :  "+decimalFormat.format(doubleDecimalValue));		
Output:
Double with decimal places with rounding up :  9.15
Double with decimal places with rounding down :  9.14	

3. Double With 2 Decimal Points Using String.format()


Next approach is using String.format() method which is simple and does not provide rounding up options as DecimalFormat or BigDecimal classes.

let us write the example program on format() method.
public class StringToDoubleDecimalsPlaces2 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		String strDoubleDecimals = String.format("%.2f", doubleDecimalValue);
		
		System.out.println("Double with 2 decimal values : "+strDoubleDecimals);
		
	}
}

Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Double with 2 decimal values : 9.14

4. Double With 2 Decimal Points Using BigDecimal class


Last way is using BigDecimal class. You need to pass the double number to the BigDecimal constructor and then call setScale() method with a number which is how many decimal points are needed and with the rounding mode.

And also setScale() method can take rounding mode also.

Look at the below example to get the more details about the BigDecimal for decimal places.
package com.javaprogramto.programs.strings.todouble.decimal;

import java.math.BigDecimal;

public class StringToDoubleDecimalsPlaces3 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		// BigDecimal
		BigDecimal bigDecimal = new BigDecimal(doubleDecimalValue);
		bigDecimal.setScale(2);
		System.out.println(""+bigDecimal.doubleValue());
		
	}
}

Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Exception in thread "main" java.lang.ArithmeticException: Rounding necessary
	at java.base/java.math.BigDecimal.commonNeedIncrement(BigDecimal.java:4628)
	at java.base/java.math.BigDecimal.needIncrement(BigDecimal.java:4835)
	at java.base/java.math.BigDecimal.divideAndRound(BigDecimal.java:4810)
	at java.base/java.math.BigDecimal.setScale(BigDecimal.java:2910)
	at java.base/java.math.BigDecimal.setScale(BigDecimal.java:2952)
	at com.javaprogramto.programs.strings.todouble.decimal.StringToDoubleDecimalsPlaces3.main(StringToDoubleDecimalsPlaces3.java:20)

Program execution is failed because of Rounding mode was not provided to the big decimal object. So, Rounding mode is mandatory to work with the setScale() method.

Added now RoundingMode.DOWN value to the setScale() method.
package com.javaprogramto.programs.strings.todouble.decimal;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class StringToDoubleDecimalsPlaces3 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		// BigDecimal
		BigDecimal bigDecimal = new BigDecimal(doubleDecimalValue).setScale(2, RoundingMode.DOWN);
		//bigDecimal.setScale(0, RoundingMode.HALF_UP);
		System.out.println("Two decimals : "+bigDecimal.doubleValue());
		
	}
}

Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Two decimals : 9.14

5. Double With 2 Decimal Points Using Formatter, NumberFormat, printf()


There are many other ways alos. Few of them are shown in the below example.

package com.javaprogramto.programs.strings.todouble.decimal;

import java.text.NumberFormat;
import java.util.Formatter;

public class StringToDoubleDecimalsPlaces4 {

	public static void main(String[] args) {

		double doubleDecimalValue = 9.144678376262;

		System.out.println("Double value : " + doubleDecimalValue);

		// 1. NumberFormat
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(2);

		System.out.println("Number format : " + nf.format(doubleDecimalValue));

		// 2. Formatter
		Formatter formatter = new Formatter();
		formatter.format("%.2f", doubleDecimalValue);

		System.out.println("Formatter : " + formatter.toString());

		// 3. Printf
		System.out.printf("printf : Double upto 2 decimal places: %.2f", doubleDecimalValue);

	}
}

Output:
Double value : 9.144678376262
Number format : 9.14
Formatter : 9.14
printf : Double upto 2 decimal places: 9.14

6. Conclusion


In this article, we've seen how to display and format the double value to double 2 decimal places using many methods. 

And also we can use the apache commons math api method Precision.round(2, doubleValue).




Saturday, October 3, 2020

Java String to String Array Conversion Examples

1. Overview

In this article, you'll learn how to convert String to String Array in java with example programs.

Let us learn the different ways to do the conversion into a string array. from a string value.

Java String to String Array Conversion Examples

Thursday, July 16, 2020

Java String codePointCount()

1. Overview


In this String API Series, You'll learn how to get the count of the codepoints in the string for a given text range.

In the previous article, we have discussed codePointAt() method which is to get the codepoint at the given index.

codePointCount() returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.

Let us jump into codePointCount() method syntax and example programs.

Java String codePointCount()

Wednesday, June 10, 2020

Java String regionMatches​() Method Example

1. Java String regionMatches​() Overview


In this tutorial, We'll learn about Java String API regionMatches​() method to compare two substrings. In other words, comparing regions of two strings.

This method is very handy when we want to compare portions of two strings. Instead of comparing all contents of Strings.

In previous article, We've discussed on String matches() method.

Java String API regionMatches​() Method Example


1.1 regionMatches() Syntax


public boolean regionMatches​(int toffset, String other, int ooffset, int len)
public boolean regionMatches​(boolean ignoreCase, int toffset, String other, int ooffset, int len)


Fist variant does case sensitive comparison
Second variant has option to ignore the case. If true, it ignores case when comparing.

Java String API regionMatches​()


Friday, May 29, 2020

Java String offsetByCodePoints​() Method Example

1. Java String offsetByCodePoints​() Method Overview

offsetByCodePoints​() method returns the index within this String that is offset from the given index by codePointOffset code points.
Unpaired surrogates within the text range given by index and codePointOffset count as one code point each.

Java String API offsetByCodePoints​() Method Example

1.1 Syntax


Here is the full syntax for this method and part of java.lang package.

public int offsetByCodePoints​(int index, int codePointOffset)

Article on Java Package

Wednesday, April 8, 2020

Java String charAt() Method examples (Find Char At a Given Index)

1. Introduction

In this article, We'll learn how to find the character at an index with String charAt in java.

The Java String charAt(int index) method returns the character at the specified index in a string. The index value should be between 0 and (length of string-1). For example, s.charAt(0) would return the first character of the string represented by instance s. Java String charAt method throws IndexOutOfBoundsException if the index value passed in the charAt() method is a negative number or less than zero or greater than or equal to the length of the string (index<0|| index>=length()). IndexOutOfBoundsException means index if out of its range and it occurs at runtime.

Java String charAt() Examples 

Syntax:

public char charAt​(int index)


Java String charAt() Method example (Find Char At a Given Index)


We will show the example programs on the following use cases. 

1: Finding first, mid and last index of the given string.
2: IndexOutOfBoundsException when using charAt() method.
3: Printing String char by char using charAt() method.
4: Printing even numbers of index characters.
5: Printing odd number index characters
6: Counting number of occurrences of a character

Tuesday, April 7, 2020

How to Create An Immutable Class in java?

1. Immutable Class in Java


This is a common nterview question for 2-4 years java experienced developer. In this tutorial, We'll learn "How to Create Immutable Class in java?" You'll learn why we need to create Immutable class and what are the advantages and as well the disadvantages of it.

Immutable class means it cannot be modified once it is created. If any modification on an immutable object then the result will give another immutable object.

How to Create An Immutable Class in java?

Builtin API immutable classes:

String, StringBuffer, and all wrapper classes, etc.

Monday, June 3, 2019

Java String API replaceAll() Method Example

1. String replaceAll() Overview


In this tutorial, We'll learn about Java String API replaceAll() Method with Example (String.replaceAll).

As name "replaceAll" suggests, It replaces each substring of this string that matches the given regular expression with the given replacement. Refer the below syntax, it takes regex which is a regular expression pattern.

This method is a instance method which should be invoked on a string. If this string has a pattern then it replaces all matched pattern's with the second parameter value.

In the previous article,  discussed on String replace() method with examples.

Java String API replaceAll() Method Example


1.1 Syntax


public String replaceAll​(String regex, String replacement)

Friday, May 31, 2019

Java String API replace() Method Example

1. Java String replace() Overview


In tutorial, We'll learn about Java String replace() method and explanation with examples. replace() method is used to replace a character with another character in a String and this method returns a new string after replacing characters.

In previous tutorial, We've seen How to use Java 11 String API repeat() method.

Java String API replace() Method Example

1.1 Syntax


public String replace​(char oldChar, char newChar)
public String replace​(CharSequence target, CharSequence replacement)

replace() method is available in two variants. First variant takes two char's as input and replace a char by a new char. Where as in second variant, It takes two CharSequence as arguments and replace one CharSequence by new CharSequence.

Here, CharSequence means String, StringBuffer, StringBuilder. Any one of these can be passed as arguments to the second variant of replace().

Tuesday, May 28, 2019

Java String API matches​() Method Example

1. Java String API matches​(String regex) Overview

In this tutorial, We'll learn about Java String API matches​() Method with Example programs. And also will explain how this method works internally.

matches() method tells whether or not this string matches the given regular expression.

In simple words, First regular expression is a pattern which tells string should have only alphabetic's or numbers. This pattern can be anything or specified character set.

If the string fits into the specified regular expression pattern then matches() method returns true. Otherwise returns false.



Java String API matches​() Method Example

Java String API length() Method Example

1. Java String length() Overview

In this tutorial, We'll learn how to find the length of the String using Java String API Length() Method. In other words, Counting the number of characters in String.

Knowing the string length is very important in iterating the string.

Note: All the blank spaces in string are counted as character.

Java String API length() Method Example

Monday, May 27, 2019

Java String indexOf() Method Example

1. Overview

In this tutorial, We will learn about String indexOf() method with example on how to check whether the specified character is present in the input string or not.

Java String indexOf() Method Example

Java String getChars()​ Method Example

1. Overview

In this quick tutorial, We'll learn about String getChars​ method with examples. As well will take a look at internally how getChars​ method implemented and works.

Java String getChars​ Method Example


2. getChars​

This method copies the characters from this string into the destination character array. Also getChars​() method copies only a specified range of characters into new char array.
Source String start index, end index and destination array start index can be configured.

Monday, May 13, 2019

Guide To Check Char Is In String In Java - indexOf(), lastIndexOf​()

1. Overview

In this tutorial, We will check the possible ways to check the given char or string in the given string. If the char is present then need to return it's index.

Throughout this post, we will be writing the examples on below string.

Check Char Is In String

String string = "find string";


indexof() and lastIndexOf methods return int value as index of the found character.

Please go through the previous post, how String contains() method works in java with examples. This post will give you understanding how indexof method is used internally.

Saturday, May 4, 2019

Guide on Java String getBytes​

1. Overview:

Encodes the current String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

This method has 4 overloaded methods.

public byte[] getBytes()
public void getBytes​(int srcBegin, int srcEnd, byte[] dst, int dstBegin) --> This is @Deprecated
public byte[] getBytes​(String charsetName) throws UnsupportedEncodingException
public byte[] getBytes​(Charset charset)



Java String getBytes