Monday, August 29, 2022

Fix Scanner.nextLine() Skipping Input After Another next Methods

In this article we’ll see why do we have the issue of Scanner.nextLine() skipping the input if used just after any other next method of the java.util.Scanner class and how to fix this problem.

What is the problem

If you are here to look for a solution to this problem you might already have encountered a similar scenario. Here is a program where next() method of the Scanner class is used to get a word as input, then nextLine() is used, then nextInt() and again nextLine() is used.

import java.util.Scanner;

public class ScannerDemo {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a word: ");
		String s = sc.next();
		
		System.out.println("Enter name: ");
		String name = sc.nextLine();
		
		System.out.println("Enter a number: ");
		int i = sc.nextInt();
		
		System.out.println("Enter address: ");
		String addr = sc.nextLine();
		
		System.out.println("Entered word is- " + s);
		System.out.println("Entered name is- " + name);
		System.out.println("Entered number is- " + i);
		System.out.println("Entered address is- " + addr);
	}

}

Output

Enter a word: 
test
Enter name: 
Enter a number: 
1
Enter address: 
Entered word is- test
Entered name is- 
Entered number is- 1
Entered address is- 

As you can see both nextLine() methods are skipped here.

What is the reason of skipping

When you use any of the next method be it next(), nextInt() etc. The input is read till the content ends without reading the newline character which is also there because of pressing "enter".

If there is a nextLine() method just after any of the other next methods of the Scanner class, it ends up reading just the newline character (‘\n’) left by the previous next method usage.

As per the documentation of the nextLine() method in Scanner.

Advances this scanner past the current line and returns the input that was skipped.

In the scenario of using it after any other next method it advances past the left over newline character and returns just that input. So it seems, as if nextLine() is skipped.

How to fix this issue

Simple solution is to use an extra nextLine() method in such scenario to consume the left over new line character ('\n') so that the following nextLine() can take the actual input from the user. If we do that to the program used as example previously.

public class ScannerDemo {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a word: ");
		String s = sc.next();
		// extra nextLine
		sc.nextLine();
		System.out.println("Enter name: ");
		String name = sc.nextLine();
		
		System.out.println("Enter a number: ");
		int i = sc.nextInt();
		
		sc.nextLine();
		System.out.println("Enter address: ");
		String addr = sc.nextLine();
		
		System.out.println("Entered word is- " + s);
		System.out.println("Entered name is- " + name);
		System.out.println("Entered number is- " + i);
		System.out.println("Entered address is- " + addr);
	}
}

Output

Enter a word: 
test
Enter name: 
Ramesh Jaiswal
Enter a number: 
10
Enter address: 
1 VIP Road, New Delhi
Entered word is- test
Entered name is- Ramesh Jaiswal
Entered number is- 10
Entered address is- 1 VIP Road, New Delhi

As you can see with the inclusion of two extra sc.nextLine() methods problem of Scanner.nextLine() method skipping the input is solved.

That's all for this topic Fix Scanner.nextLine() Skipping Input After Another next Methods. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  2. Buffered Streams in Java IO
  3. How to Read Input From Console in Java
  4. Read File Asynchronously Java Program
  5. Java Program to Delete File And Directory Recursively

You may also like-

  1. Difference Between StackOverflowError and OutOfMemoryError in Java
  2. How to Get The Inserted ID (Generated ID) in JDBC
  3. Java Concurrency Interview Questions And Answers
  4. Static Synchronization in Java Multi-Threading
  5. Spring MVC Generate Response as JSON Example
  6. registerShutdownHook() Method in Spring Framework
  7. Global Keyword in Python With Examples
  8. Angular One-Way Data Binding Using String Interpolation

Sunday, August 28, 2022

Navigate to a Route Programmatically in Angular

In this post we’ll see how to navigate to a route programmatically or dynamically using router.navigate() or router.navigateByUrl() methods in Angular.

Navigating to a route dynamically Angular example

You may have a scenario where you would like to navigate to a route based on an event like click of a button, clicking a link. Here is a simple example which uses router.navigate() method to navigate to a route on a click of a button.

Note that while navigating to a route you can use both absolute as well as relative path. In this post we'll see examples of both.

There is a menu as shown below and you have to show the corresponding component on click of the menu option.

1. Creating routing module

We’ll create a separate routing file app-routing.module.ts with routes array to define route paths and component they map to.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountsComponent } from './accounts/accounts.component';
import { AccountComponent } from './accounts/account/account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';


const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2. Import the AppRoutingModule into AppModule (app.module.ts) and add it to the imports array.

import { AppRoutingModule } from './app-routing.module';
imports: [
  BrowserModule,
  AppRoutingModule
],

3. Adding the configured routes to the application.

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
          <a class="nav-link" routerLink="/">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

Creating components

Now as per our route mapping there are 3 components HomeComponent, AccountsComponent and ServiceComponent.

Home Component (home.component.ts)

From the home page you want to provide a button to take to AccountsComponent. That route navigation will be done programmatically.

import { OnInit, Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  userId = 'UID0023';
  constructor(private router: Router) { }

  ngOnInit() {
  }

  navigateToAccount(){
    this.router.navigate(['/account']);
  }
}

To use Router.navigate method first you need to inject the Router class in your component. That is done in the constructor.

In the method navigateToAccount(), router.navigate() method is used to navigate to a route. In navigate method you pass an array of elements that are joined together to create a path. For example router.navigate(‘account’, 1) resolves to a path /account/1.

If you want to use router.navigateByUrl() method then you can also use this.router.navigateByUrl('/account'); With router.navigateByUrl() you can pass an absolute path, for example router.navigateByUrl(‘/account/1’).

Note that in this example path passed in this.router.navigate(['/account']); is an absolute path (not relative).

home.component.html

<h4>Welcome to XYZ Bank</h4>
<p>{{ userId }} logged in.</p>
<div>
    <button type="button" class="btn btn-primary" (click)="navigateToAccount()">My Accounts</button>
</div>

Account Component (account.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
}

accounts.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <!-- [routerLink]="" 
    (click)="onAccountClick(account)" -->
    <div class="list-group">
      <a class="list-group-item"   
        *ngFor="let account of accounts">
        {{ account }}
      </a>
    </div>
  </div>
</div>

Service Component (service.component.ts)

import { Component } from "@angular/core";

@Component({
  selector: 'app-service',
  templateUrl:'./service.component.html'
})
export class ServiceComponent{
  services = [
    'Deposit Money',
    'Open FD',
    'Mail Customer Care'
  ]; 
}

service.component.html

<h2>Services Offered</h2>
<div class="row">
  <div class="col-xs-12 col-sm-6">
    <div class="list-group">
      <a
        href="#"
        class="list-group-item"
        *ngFor="let service of services">
        {{ service }}
      </a>
    </div>
  </div>
</div>

Add these components in the declarations array of the AppModule before running the example.

You will have a button in the HomeComponent which navigates you to the AccountsComponent when clicked.

Navigate to a Route Programmatically in Angular

Dynamic route Navigation using relative path in Angular

In the previous example we used absolute path with navigate() method but you can also pass a relative path but in that case you need to specify path is relative to which existing path.

Let’s change the previous example to have one more component AccountComponent that shows the details for the account selected in AccountsComponent.

For that routes array will have to be changed in the following way-

const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'account/:acctno', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

As you can see a new route definition is added- {path: 'account/:acctno', component: AccountComponent}, here :acctno is a placeholder that matches any account number so URL like account/A001 or account/A002 both will match this route.

Accounts component is also changed-

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
  constructor(private router: Router, private route: ActivatedRoute) {}
  onAccountClick(account: string){
    this.router.navigate([account], {relativeTo:this.route});
  }
}

Along with Router class now ActivatedRoute class is also injected into the component. ActivatedRoute class provides access to information about a route associated with a component that is loaded in router outlet.

In router.navigate() method you can also pass a second argument of type navigationExtras. One of the NavigationExtras is relativeTo which specifies a root URI to use for relative navigation.

In the example navigate method is now like this-

this.router.navigate([account], {relativeTo:this.route});

Here this.route specifies the route associated with the component, in our case it will be /account so relative path is http://localhost:4200/account

[account] specifies the account number that is clicked which can be either A1001 or A1002. Thus the navigation route is derived as either http://localhost:4200/account/A1001 or http://localhost:4200/account/A1002 which matches the route definition {path: 'account/:acctno', component: AccountComponent}.

AccountComponent (account.component.ts)

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    this.acctNo = this.route.snapshot.params['acctno'];
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }
}

Here we have defined an account type- account: {accountnumber: string, type: string, balance: number};

There is also an array with values for account.

In ngOnInit() using the passed account number we find the related object in the array using the find() method.

Account number parameter is extracted from the route using the current snapshot of the route.

this.route.snapshot.params['acctno'];

account.component.html

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>

Accounts Component

Account Component

navigating route dynamically angular

Recommendations for learning (Udemy Courses)

  1. Angular - The Complete Guide
  2. Angular & NodeJS - The MEAN Stack Guide
  3. React - The Complete Guide Course
  4. Python for Data Science and Machine Learning
  5. Java Programming Masterclass Course

That's all for this topic Navigate to a Route Programmatically in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Highlight Currently Selected Menu Item Angular Routing Example
  3. Setting and Fetching Route Parameters in Angular
  4. Setting Wild Card Route in Angular
  5. Nested Route (Child Route) in Angular

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. How to Create a Custom Observable in Angular
  3. Angular Event Binding With Examples
  4. Angular ngFor Directive With Examples
  5. Java Lambda Expression And Variable Scope
  6. Serialization and Deserialization in Java
  7. String Slicing in Python
  8. How to Untar a File - Java Program

Saturday, August 27, 2022

Angular Route Parameters - Setting and Fetching

In this post we’ll see how to pass and retrieve route parameters in Angular routing.


Route parameters in Angular

In our web apps we do need to navigate to a specific resource. For example we want the details of a specific account number then we can navigate to that account number by using URL- /account/A1001 or to another account by using URL- /account/A1002.

It is not practical to hardcode the path segment for each account number, you will use a route parameter instead that acts as a placeholder. Value passed for the placeholder becomes the value of the route parameter.

In a route that takes a parameter, route parameter is specified by prefixing it with a colon. So the route definition will be like- /route/:routeparam

You can pass more than one route parameter too- /route/:param1/:param2/:param3

For example if you have to a give route definition for a route- /account/A1001 where /A1001 part represents an account number and should be passed as a route parameter.

{path: 'account/:acctno', component: COMPONENT_NAME}

Passing Route parameters in Angular

1. You can pass route parameters with RouterLink directive. For a dynamic link, pass an array of path segments (which includes path and route parameters). For example

[routerLink]="['/account', accountnumber]"     

generates a link to /account/A1001 or to /account/A1002 based on what is passed as value for the string variable accountnumber.

2. You can also pass route parameters programmatically using Router.navigate() method. For example onAccountClick() method is called with account number as argument and then it creates a URL with route parameter using navigate() method. Here account number gets added as a route parameter to the current route.

onAccountClick(accountNo: string){
  this.router.navigate([accountNo], {relativeTo:this.route});
}

Retrieving route parameters in Angular

To extract the parameter, params observable of the ActivatedRoute interface is used and we subscribe to it so that when ever there is a change in the route parameter it is extracted into a variable.

this.route.params.subscribe((params: Params)=> this.acctNo = params['acctno']);

Here value passed in acctno route parameter is assigned to acctNo variable. You can also extract parameter from the route using the current snapshot of the route.

this.acctNo = this.route.snapshot.params['acctno'];

Route parameters in Angular example

In the example we show user a list of account numbers. Then the details of the account number, that is clicked, are showed using a separate component. In this scenario you can pass the clicked account number as route parameter.

Here are the route definitions for the routes. Here AccountsComponent displays all the account numbers for a user and AccountComponent shows details for the selected account number.

const routes: Routes = [
                        {path: 'home', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'account/:acctno', component: AccountComponent},
                        {path: 'service', component: ServiceComponent},
                        {path: '', redirectTo:'/home', pathMatch: 'full'}                  
];

As you can see there is a route with route parameter- {path: 'account/:acctno', component: AccountComponent}

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/home">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

Components

We’ll concentrate here on AccountsComponent and AccountComponent for the code of other components please refer- Angular Routing Concepts With Example.

AccountsComponent (accounts.component.ts)

In the component we have an array to show account numbers and a method onAccountClick() to navigate programmatically to a route.

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
  constructor(private router: Router, private route: ActivatedRoute) {}
  onAccountClick(account: string){
    this.router.navigate([account], {relativeTo:this.route});
  }
}

Two classes Router class and ActivatedRoute class are injected into the component.

  • Router class has navigate() method using which we navigate to a URL dynamically.
  • ActivatedRoute class provides access to information about the current route.

This line of code instructs Angular to navigate to the path which is relative to current route (localhost:4200/account in our example) and adds the value of account to it making it a route in this format- http://localhost:4200/account/ACCOUNT_NUMBER

this.router.navigate([account], {relativeTo:this.route});

Since we already have a route definition with a route parameter {path: 'account/:acctno', component: AccountComponent} which matches any route in this format http://localhost:4200/account/ACCOUNT_NUMBER so that’s how AccountComponent gets called.

accounts.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <div class="list-group">
      <a [routerLink]="" 
        (click)="onAccountClick(account)" 
        class="list-group-item"   
        *ngFor="let account of accounts">
        {{ account }}
      </a>
    </div>
  </div>
</div>

If you want to use RouterLink directive then your template can be written as-

  <div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <div class="list-group">
      <a [routerLink]="['/account', account]" class="list-group-item"  
        *ngFor="let account of accounts">
        
        {{ account }}
      </a>
    </div>
  </div>
</div>
  

In this case onAccountClick() method can be removed from typescript code as navigation is configured in the template itself.

AccountComponent (account.component.ts)

In this component we simulate a scenario where we have details for all the account numbers and we have to get the details for the account number which is sent as route parameter.

To extract the parameter route.params observable is used and we subscribe to it so that when ever there is a change the parameter is extracted into a acctNo variable. Using the fetched account number we find the related object in the array using the find() method.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    //this.acctNo = this.route.snapshot.params['acctno'];
    this.route.params.subscribe((params: Params)=> this.acctNo = params['acctno']);
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }
}

Note that you can also extract parameter from the route using the current snapshot of the route. But route.params observable is preferred.

this.acctNo = this.route.snapshot.params['acctno'];

account.component.html

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>

Accounts Component

Account Component

That's all for this topic Angular Route Parameters - Setting and Fetching. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Passing Query Parameters in Angular Routing
  2. Path Redirection in Angular Routing
  3. Navigate to a Route Programmatically in Angular
  4. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  5. Angular CanActivateChild Guard to protect Child Routes

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular ngSwitch Directive With Examples
  3. Angular @Input and @Output Example
  4. How to Add Bootstrap to Angular Application
  5. PriorityBlockingQueue in Java Concurrency
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Predefined Mapper And Reducer Classes in Hadoop
  8. Passing Arguments to getBean() Method in Spring

Wednesday, August 10, 2022

Java String substring() Method - Getting Substring

If you are trying to get substring of a String in Java then substring() method can be used, there is also a subSequence() method in Java String class that returns a CharSequence.

Java substring() method

In String class there are two variants of substring() method.

  • String substring(int beginIndex)- Returns a string that is a substring of this string. The substring begins with the character at the beginIndex and extends to the end of this string.
  • String substring(int beginIndex, int endIndex)- Returns a string that is a substring of this string. The substring that is returned begins at specified beginIndex and extends to the character at index endIndex – 1.

Few things to note here are-

  1. beginIndex is inclusive.
  2. endIndex is not inclusive so characters in the substring are from beginIndex..endIndex-1.
  3. If the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex then IndexOutOfBoundsException is thrown.

Java subSequence() method

  • CharSequence subSequence(int beginIndex, int endIndex)- Returns a character sequence that is a subsequence of this sequence. This method is similar to substring method difference is that CharSequence is returned in this method. Note that CharSequence is an interface which is implemented by String, StringBuffer, StringBuilder classes.

Java substring() method examples

1. Using substring method to get substring of a string by specifying only beginIndex or by specifying both beginIndex and endIndex.

public class SubStringDemo {
 public static void main(String[] args) {
  String str = "Example String";
  
  System.out.println("Value - " + str.substring(0, 7));
  
  System.out.println("Value - " + str.substring(8));
  
  System.out.println("Value - " + str.substring(14)); 
 }
}

Output

Value - Example
Value - String
Value - 

0

1

2

3

4

5

6

7

8

9

10

11

12

13

E

x

a

m

p

l

e


S

t

r

i

n

g

String in Java

It’ll be easy to understand with the image, when substring method is called with indexes 0 and 7, returned subString would be “Example” which is index 0-6 as starting index is inclusive and endIndex is not inclusive.

Same way when substring method is called with startIndex as 8 then returned string would be from index 8 till end that’s why String is returned.

If substring() method is called with the length of the string (14 in this case) then empty space is returned. Passing any argument beyond that (more than 14) will result in IndexOutOfBoundsException.

2. Using substring method with an index that is out of range, resulting in IndexOutOfBoundsException.

public class SubStringDemo {
 public static void main(String[] args) {
  String str = "Example String";
  // endIndex out of range
  System.out.println("Value - " + str.substring(9, 17));
 }
}

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 9, end 17, length 14
 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3410)
 at java.base/java.lang.String.substring(String.java:1883)
 at org.netjs.prgrm.SubStringDemo.main(SubStringDemo.java:7)

3. Rather than passing precise index manually most of the times you will use substring() method with other methods like indexOf(), lastIndexOf() where these methods are used to pass the index. For example if you have a date in mm-dd-yyyy format and you want to get the date part.

public class SubStringDemo {

 public static void main(String[] args) {
  String date = "06-17-2019";
  String day = date.substring(date.indexOf('-') + 1, date.lastIndexOf('-'));
  System.out.println("day is- " + day);
 }
}

Output

day is- 17

Java subSequence() method example

public class SubStringDemo {

 public static void main(String[] args) {
  String str = "Example String";
  String s = str.subSequence(0, 7).toString();
  System.out.println("Value - " + str.substring(0, 7));
 }
}

Output

Value - Example

That's all for this topic Java String substring() Method - Getting Substring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  2. StringBuffer Class in Java With Examples
  3. StringBuilder Class in Java With Examples
  4. If Given String Sub-Sequence of Another String in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Format Date in Java Using SimpleDateFormat
  2. super Keyword in Java With Examples
  3. final Keyword in Java With Examples
  4. Lambda Expressions in Java 8
  5. Effectively Final in Java 8
  6. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  7. Busy Spinning in Multi-Threading
  8. Bean Definition Inheritance in Spring

Tuesday, August 9, 2022

StringJoiner Class in Java With Examples

In Java 8 StringJoiner class is added that can be used for joining the Strings separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Constructors in StringJoiner class

Java StringJoiner class has two constructors.

  • StringJoiner(CharSequence delimiter)- Constructs a StringJoiner with no characters in it, with no prefix or suffix, and a copy of the supplied delimiter.
  • StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)- Constructs a StringJoiner with no characters in it using copies of the supplied prefix, delimiter and suffix.

Java StringJoiner class examples

Let us see few examples to understand how StringJoiner class is used to join Strings using a delimiter.

1. If you have three strings which you want to join and delimiter is ':' then it can be done using StringJoiner class as follows-

import java.util.StringJoiner;

public class StringJoinerDemo {
 public static void main(String[] args) {
  String str1 = "An";
  String str2 = "example";
  String str3 = "string";
  // providing delimiter
  StringJoiner sj = new StringJoiner(":");
  // adding strings that are to be joined
  sj.add(str1).add(str2).add(str3);
  System.out.println(sj.toString());
 }
}

Output

An:example:string

2. If you want to get the joined strings with suffix and prefix so that the end string looks like this - (An,example,string)

import java.util.StringJoiner;

public class StringJoinerDemo {
 public static void main(String[] args) {
  String str1 = "An";
  String str2 = "example";
  String str3 = "string";
  // providing delimiter and suffix, prefix
  StringJoiner sj = new StringJoiner(",", "(", ")");
  // adding strings that are to be joined
  sj.add(str1).add(str2).add(str3);
  System.out.println(sj.toString());
 }
}

Java StringJoiner class methods

  1. add(CharSequence newElement)- Adds a copy of the given CharSequence value as the next element of the StringJoiner value.
  2. length()- Returns the length of the String representation of this StringJoiner.
  3. merge(StringJoiner other)- Adds the contents of the passed StringJoiner object without prefix and suffix as the next element of the StringJoiner if it is non-empty.
  4. setEmptyValue(CharSequence emptyValue)- Sets the default sequence of characters to be used when StringJoiner is empty.
  5. toString()- Returns the current value as String, consisting of the prefix, the values added so far separated by the delimiter, and the suffix

Java StringJoiner setEmptyValue() method example

import java.util.StringJoiner;

public class StringJoinerDemo {
 public static void main(String[] args) {
  StringJoiner sj = new StringJoiner(":", "[", "]");
  System.out.println("StringJoiner- " + sj.toString());
  sj.setEmptyValue("No element is added yet");
  System.out.println("StringJoiner- " + sj.toString());
  sj.add("Adding").add("Values").add("Now");
  System.out.println("StringJoiner- " + sj.toString());
 }
}

Output

StringJoiner- []
StringJoiner- No element is added yet
StringJoiner- [Adding:Values:Now]

As you can see when default sequence is added using setEmptyValue() method that is displayed when no element is added. When elements are added then those elements are displayed as a joined string.

Java StringJoiner merge() method example

public class StringJoinerDemo {
 public static void main(String[] args) {
  StringJoiner sj1 = new StringJoiner(":", "[", "]");
  sj1.add("This").add("is").add("First").add("String");
  System.out.println("Length of sj1- " + sj1.length());
  StringJoiner sj2 = new StringJoiner("-", "{", "}");
  sj2.add("Second").add("String");
  System.out.println("Length of sj2- " + sj2.length());
  sj1 = sj1.merge(sj2);
  System.out.println("Merged String- " + sj1.toString());
  System.out.println("Length of Merged String- " + sj1.length());
 }
}

Output

Length of sj1- 22
Length of sj2- 15
Merged String- [This:is:First:String:Second-String]
Length of Merged String- 36

As you can see contents of the second StringJoiner is added without prefix and suffix. Delimiter of the second StringJoiner is retained.

That's all for this topic StringJoiner Class in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String in Java Tutorial
  2. Why Java String is Immutable
  3. String Comparison in Java equals(), compareTo(), startsWith() Methods
  4. Converting Char to String And String to Char in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Association, Aggregation And Composition in Java
  2. Private Methods in Java Interface
  3. LinkedHashSet in Java With Examples
  4. Phaser in Java Concurrency
  5. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  6. Spring Expression Language (SpEL) With Examples
  7. Spring Integration With Quartz Scheduler
  8. Magic Methods in Python With Examples

Monday, August 8, 2022

How to Display Time in AM-PM Format in Java

In this post we'll see how to display time in 12 hours format with AM-PM in Java.

In order to display time with AM-PM in Java, in the pattern you are creating for the format either with SimpleDateFormat (if you are not using Java 8) or with DateFormatter (if you are using Java 8) just add the pattern letter ‘a’ which denotes AM-PM of the day.

Displaying time in AM-PM format - Java SimpleDateFormat Example

If you are using the java.util.Date and SimpleDateFormat then the format you need to use to show time in AM-PM format is as following.

Date date = new Date();
// Pattern 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
System.out.println("TIME - " + sdf.format(date));

Output

TIME - 13:09:55 PM

Displaying time with AM-PM format - Java DateFormatter Example

If you are using the new Date and Time API in Java 8, then you can use the DateFormatter class, pattern remains the same as used above for showing time in AM-PM format in Java.

//Getting time
LocalTime t2 = LocalTime.now();
// Pattern
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t2.format(df);
System.out.println("Time - " + text);

Output

Time - 13:11:15 PM

Another example – Showing AM

LocalTime t1 = LocalTime.of(5, 30, 56);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t1.format(df);
System.out.println("Time - " + text);

Output

Time - 05:30:56 AM

That's all for this topic How to Display Time in AM-PM Format in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Format Date in Java Using SimpleDateFormat
  2. How to Convert String to Date in Java
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. How to Find Last Modified Date of a File in Java
  5. Convert int to String in Java

You may also like-

  1. Connection Pooling Using Apache DBCP in Java
  2. Producer-Consumer Java Program Using ArrayBlockingQueue
  3. Convert String to Byte Array Java Program
  4. Java Object Cloning - clone() Method
  5. Java Nested Class And Inner Class
  6. Java Reflection API Tutorial
  7. How to Resolve Local Variable Defined in an Enclosing Scope Must be Final or Effectively Final Error
  8. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example

Sunday, August 7, 2022

Unmodifiable or Immutable List in Java

A List is considered unmodifiable if elements cannot be added, removed, or replaced from the list once the unmodifiable instance of a List is created. In this post we’ll see how Unmodifiable list was created before Java 9 and how it can be created Java 9 onward using Immutable List Static Factory Methods.


Creating Unmodifiable list before Java 9

Before Java 8, in order to create unmodifiable list Collections.unmodifiableList() method was used.

  • Collections.unmodifiableList(List<? extends T> list)- Returns an unmodifiable view of the specified list. Note that the list underneath can still be modified.
public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = new ArrayList<>();
    alphaList.add("a");
    alphaList.add("b");
    alphaList.add("c");
    alphaList.add("d");
    //List<String> alphaList = Arrays.asList("a", "b", "c", "d");
    List<String> aList = Collections.unmodifiableList(alphaList);
    alphaList.add("e");
    System.out.println("alphaList- " + alphaList);
    aList.add("f");
  }
}

Output

alphaList- [a, b, c, d, e]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1058)
 at org.netjs.Programs.UnmodifiedList.main(UnmodifiedList.java:20)

As you can see alphaList which is used to create unmodifiable list can still be modified though changing the unmodifiable list results in UnsupportedOperationException.

By using Arrays.asList to create list you can ensure that methods that change the size of the list can’t be called on the returned list.

public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = Arrays.asList("a", "b", "c", "d");
    List<String> aList = Collections.unmodifiableList(alphaList);
    alphaList.add("e");
    System.out.println("alphaList- " + alphaList);
    aList.add("f");
  }
}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.AbstractList.add(AbstractList.java:153)
 at java.base/java.util.AbstractList.add(AbstractList.java:111)
 at org.netjs.Programs.UnmodifiedList.main(UnmodifiedList.java:13)

As you can see now the original list itself can’t call any size changing operation.

Creating Unmodifiable list in Java 9

The List.of (added in Java 9) and List.copyOf (added in Java 10) static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics-

  1. The collections returned by the convenience factory methods added in JDK 9 are conventionally immutable. Elements cannot be added, removed, or replaced from such a list. Elements cannot be added, removed, or replaced from such a list. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown.
  2. If the elements with in the list themselves are mutable, this may cause the List's contents to appear to change.
  3. Such lists can't be created with null elements any such attempt result in NullPointerException.
  4. Unmodifiable lists are serializable if all elements are serializable.
  5. The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.

List.of() method in Java

List.of() method static factory method is a convenient way to create unmodifiable lists Java 9 onward. This method has both fixed-argument form and varargs form. Fixed-argument form overloads up to 10 elements and the form of these method is as follows.

List.of(E e1)- Returns an unmodifiable list containing one element.

..

..

List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)- Returns an unmodifiable list containing nine elements. 

List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)- Returns an unmodifiable list containing ten elements.

varargs form

  • List.of(E... elements)- Returns an unmodifiable list containing an arbitrary number of elements.

List.of() method Java example

public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = List.of("a", "b", "c", "d");
    System.out.println("alphaList- " + alphaList);
    // raises error
    alphaList.add("e");
  }
}

Output

alphaList- [a, b, c, d]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
 at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:76)
 at org.netjs.Programs.UnmodifiedList.main(UnmodifiedList.java:10)

List.copyOf() method in Java

If you want to create an unmodifiable List using an existing collection then you can use copyOf() method.

  • List.copyOf(Collection<? extends E> coll)- Returns an unmodifiable List containing the elements of the given Collection, in its iteration order. The given Collection must not be null, and it must not contain any null elements. If the given Collection is subsequently modified, the returned List will not reflect such modifications.

List.copyOf() method Java example

public class UnmodifiedList {
  public static void main(String[] args) {
    List<String> alphaList = new ArrayList<>();
    alphaList.add("a");
    alphaList.add("b");
    alphaList.add("c");
    alphaList.add("d");
    List<String> aList = List.copyOf(alphaList);
    alphaList.add("e");
    System.out.println("alphaList- " + alphaList);
    System.out.println("aList- " + aList);
  }
}

Output

alphaList- [a, b, c, d, e]
aList- [a, b, c, d]

As you can see even if the original collection is modified the returned unmodifiable list doesn’t reflect such modification.

That's all for this topic Unmodifiable or Immutable List in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Duplicate Elements From an ArrayList in Java
  2. How to Sort a HashMap in Java
  3. HashSet in Java With Examples
  4. CopyOnWriteArrayList in Java With Examples
  5. Java Collections Interview Questions And Answers

You may also like-

  1. AtomicInteger in Java With Examples
  2. Java ScheduledThreadPoolExecutor - Task Scheduling in Java
  3. Livelock in Java Multi-Threading
  4. Reflection in Java - Getting Constructor Information
  5. Java Pass by Value or Pass by Reference
  6. Difference Between Encapsulation And Abstraction in Java
  7. String Slicing in Python
  8. Difference Between @Controller And @RestController Annotations in Spring