Java string touppercase first letter

Capitalize last letter and Lowercase first letter of a word in Java

String is a sequence of character values. In Java, Strings are considered as objects. We have a String class provided by Java for creating and manipulating strings.

We have to convert the first letter of the word to lowercase and last letter of the word to uppercase.

In this article we will see how the first and last letter can be converted into lower and upper case respectively. Let’s explore.

Читайте также:  Левая кавычка html елочка

To Show You Some Instances

Instance-1

Suppose the input string is “Hello”

After converting the first letter to lower and last letter to capital, the new string will be “hellO”

Instance-2

Suppose the input string is “Java”

After converting the first letter to lower and last letter to capital, the new string will be “javA”

Instance-3

Suppose the input string is “Programming”

After converting the first letter to lower and last letter to capital, the new string will be “programminG”

Syntax

To get the length of the String Java String class provides a length() method.

Below is the syntax for that −

Where, str is the string variable.

To get a substring of the original string Java String class provides a substring() method.

Syntax

Below is the syntax for that −

str.substring(int startIndex); str.substring(int startIndex, int endIndex);

Where, startIndex is inclusive and endIndex is exclusive.

To get a character at a specified index Java String class provides the charAt() method.

Syntax

Below is the syntax for that −

Where, index refers to the index of the character that you need.

To convert different types of values to String value Java String class provides valueOf() method.

Syntax

Below is the syntax for that −

Algorithm

Note − This problem can be solved with the Array concept also. But here we have tried to solve the problem without using the array concept. Also we have used only inbuilt methods of String Class.

Algorithm-1

  • Step 1 − Get the string/word either by initialization or by user input.
  • Step 2 − Get the first and last letter by using the substring() method. Then convert it to lower and upper case by using toLowerCase() method and toUpperCase() method respectively.
  • Step 3 − Get the middle characters (except first and last character) with the help of substring() method.
  • Step 4 − Combine first, middle and last value and get the final string/word.

Algorithm-2

  • Step 1 − Get the string/word either by initialization or by user input.
  • Step 2 − Get the first and last letter by using charAt() method. Then convert it to lower and upper case by using toLowerCase() method and toUpperCase() method respectively.
  • Step 3 − Get the middle characters (except first and last character) with the help of charAt() method and a for loop.
  • Step 4 − Then combine first, middle and last value and get the final string/word.

Multiple Approaches

We have provided the solution in different approaches.

Let’s see the program along with its output one by one.

Approach-1: By Using Inbuilt substring Method

Example

In this approach, we will make use of Algorithm-1

import java.util.Scanner; public class Main < public static void main(String[] args) < //input string String str = "Java"; System.out.println("Original string is: "+str); //get size of the string int size = str.length(); //get last character and convert it to upper case String last = str.substring(size-1,size); String lastinUpper = last.toUpperCase(); //get first character and convert it to lower case String first = str.substring(0,1); String firstinLower = first.toLowerCase(); //get middle parts of the word, except first and last character String middle = str.substring(1,size-1); //combine everything and get the final string String result = firstinLower+middle+lastinUpper; //print result System.out.println("Updated string is: "+result); >>

Output

Original string is: Java Updated string is: javA

Approach-2: By Using Inbuilt charAt() Method

Example

In this approach, we will make use of Algorithm-2

public class Main < public static void main(String[] args) < //input String String str = "Python"; System.out.println("Original string: "+str); //get length of string int size = str.length(); //find last character and convert it to upper case char last = str.charAt(size-1); String finalLast = (String.valueOf(last)).toUpperCase(); //find first character and convert it to lowercase char first = str.charAt(0); String finalFirst = (String.valueOf(first)).toLowerCase(); //find middle characters String middle=""; for(int i=1; i//find the updated string String result = finalFirst+middle+finalLast; System.out.println("Updated string: "+result); > >

Output

Original string: Python Updated string: pythoN

In this article, we explored how to convert the first letter of a word to lowercase and last letter of the word to upper case in Java by using different approaches.

Источник

Java string touppercase first letter

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Capitalize the First Letter of a String in Java

Capitalize the First Letter of a String in Java

  1. Capitalize the First Letter of a String Using upperCaseFirst() Associated With toCharArray() Method
  2. Capitalize the First Letter of a String Using toUpperCase() and appendTail() Methods
  3. Capitalize the First Letter of a String Using String.substring()
  4. Capitalize the First Letter of a String Using String.substring() Method With Function capitalize()

This tutorial article will introduce how to capitalize the first letter of a string using Java. There are some common methods which are used to convert the first letter of a given string value to upper case. The different methods are upperCaseFirst() along with toCharArray() , toUpperCase() and appendTail() methods, String.substring() method and capitalize() function along with String.substring() method. Let us discuss each method implementations through examples.

Capitalize the First Letter of a String Using upperCaseFirst() Associated With toCharArray() Method

In this process, we introduce the upperCaseFirst() method that receives a string value and converts it into an array of characters. Then, we use the Character class and toUpperCase() method to capitalize the first element in the character array. In conclusion, we convert the updated character array into a string using the String Constructor . Let us follow the below example.

import java.util.*; import java.lang.*; import java.io.*;  public class Main   public static String upperCaseFirst(String val)   char[] arr = val.toCharArray();  arr[0] = Character.toUpperCase(arr[0]);  return new String(arr);  >   public static void main(String[] args)   String val1 = "java";  String val2 = "advanced java";   String output = upperCaseFirst(val1);  System.out.println(val1);  System.out.println(output);   output = upperCaseFirst(val2);  System.out.println(val2);  System.out.println(output);  > > 
java Java advanced java Advanced java 

Capitalize the First Letter of a String Using toUpperCase() and appendTail() Methods

In the way out, 2 different methods come into picture which are toUpperCase() and appendTail() . For implementing these 2 methods within a single application, regex.Matcher and regex.Pattern packages are imported. The below example will explain these in detail.

import java.util.regex.Matcher; import java.util.regex.Pattern;  public class Main   public static void main(String[] args)   String str = "hello world!";  System.out.println(str);  StringBuffer strbf = new StringBuffer();  Matcher match = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(str);  while(match.find())    match.appendReplacement(strbf, match.group(1).toUpperCase() + match.group(2).toLowerCase());  >  System.out.println(match.appendTail(strbf).toString())  > > 

Capitalize the First Letter of a String Using String.substring()

The simplest and easiest trick to capitalize the first letter of a given string is using the String.substring() method. Let us discuss in the below example.

import java.util.*;  public class Main   public static void main(String[] args)   String str = "java";  String firstLtr = str.substring(0, 1);  String restLtrs = str.substring(1, str.length());   firstLtr = firstLtr.toUpperCase();  str = firstLtr + restLtrs;  System.out.println("The modified string is: "+str);  > > 
The modified string is: Java 

In the above example, we created one string variable — str . Then we formed two substrings from str , where the firstLtr represents the first letter of the string and the restLtrs represent the remaining letters of the string. In the concluding part, we converted the firstLtr to upper case using the toUpperCase() method and joined the two substrings forming the string itself.

Capitalize the First Letter of a String Using String.substring() Method With Function capitalize()

In this last example, we will use a functional capitalize() to ensure that the given string has at least one character before using the String.substring() method.

import java.util.*;  public class Main   public static String capitalize(String str)  if(str == null || str.isEmpty())   return str;  >  return str.substring(0, 1).toUpperCase() + str.substring(1);  >   public static void main(String[] args)   String str = "hello world!";  String firstLtr = str.substring(0, 1);  String restLtrs = str.substring(1, str.length());   firstLtr = firstLtr.toUpperCase();  str = firstLtr + restLtrs;  System.out.println("The modified string is: "+str);  > > 
The modified string is: Hello world! 

Related Article — Java String

Источник

How to capitalize first letter in java

Here are the steps to capitalize first letter of each word.

  • Split String by space and assign it String array words
  • Iterate over the String array words and do following:
    • Get first letter of String firstLetter using str.substring(0,1) .
    • Get remaining String remainingLetters using str.substring(1) .
    • Convert first letter of String firstLetter to upper Case using toUpperCase() method.
    • Concatenate both the String firstLetter and remainingLetters .

    That’s all about How to capitalize first letter in java.

    Further reading:

    Count occurrences of Character in String in Java
    Count number of words in a String

    Was this post helpful?

    Share this

    Author

    Count the Number of Occurrences of a Character in a String in Java

    Count occurrences of Character in String

    Table of Contents1. Using String Library Methods2. Using Recursion3. Using Hashing ConceptUsing ArraysUsing Collections (Map)4. Using Java 8 Features In this article, we will look at a problem: Given an Input String and a Character, we have to Count Occurrences Of character in String. For Example, If the Given String is : «Java2Blog» and we […]

    Find first and last digit of a number

    Table of ContentsAlgorithmUsing while loopUsing log() and pow() methodsUsing while loop and pow() method In this article, we are going to find first and last digit of a number. To find first and last digit of any number, we can have several ways like using modulo operator or pow() and log() methods of Math class […]

    Happy Number program in Java

    Table of ContentsWhat is a Happy Number?Using HashsetAlgorithmExampleUsing slow and fast pointersAlgorithmExample In this article, we are going to learn to find Happy Number using Java. Let’s first understand, what is Happy Number? What is a Happy Number? A number which leaves 1 as a result after a sequence of steps and in each step […]

    Find Perfect Number in Java

    Table of ContentsIterative approachRecursive approach In this article, we are going to find whether a number is perfect or not using Java. A number is called a perfect number if the sum of its divisors is equal to the number. The sum of divisors excludes the number. There may be several approaches to find the […]

    How to find Magic Number in Java

    Table of ContentsWhat is a Magic Number?Algorithm for Magic NumberExample to find Magic NumberAnother Example To find Magic Number In this article, we are going to learn to find Magic Number using Java. Let’s first understand, what is Magic Number? What is a Magic Number? A number which leaves 1 as a result after a […]

    Number guessing game in java

    Table of ContentsNumber guessing game RulesAlgorithm for Number guessing game In this article, we will implement Number guessing game in java. The number guessing game is based on a concept where player guesses a number between a range. If player guesses the exact number then player wins else player looses the game. Since this game […]

    Источник

Оцените статью