• We can get first  two character of a string in java by using subString() method in java
  • To get first N numbers of a string s.substring(0,n);
  • Lets see an example java program on how to get first two characters or first N characters.
In Java, you can use the charAt() method to get the first character of a string. The charAt() method takes an index as a parameter and returns the character at that index. 
To get the first character of a string, you can pass in the index 0 to the charAt() method.

Here's an example:


String str = "Hello, World!";
char firstChar = str.charAt(0);
System.out.println("First character: " + firstChar);

This will output:
First character: H



Program #1: Java Program to get first two characters of a String.



  1.  package StringInterviewprograms;
  2.  
  3. public class GetFirstTwoCharacters {
  4.  
  5. /**
  6. * How to get First N characters in java 
  7. * @author www.instanceofjava.com
  8. */
  9.  
  10. public static void main(String[] args) {
  11.         
  12.         String str="Get first two characters of a String";
  13.         
  14.         System.out.println(str.substring(0,2));
  15. }
  16.     
  17.     
  18. }
     
Output:

  1.  Ge

  Program #2:


  1. package StringInterviewprograms;
  2. import java.util.Scanner;
  3.  
  4. public class GetFirstTwoCharacters {
  5. /**
  6. * How to get First N characters in java 
  7. * @author www.instanceofjava.com
  8. */
  9. public static void main(String[] args) {
  10.         
  11.          Scanner sc= new Scanner(System.in);
  12.          
  13.          System.out.println("Please Enter a String");
  14.          
  15.          String str=sc.next();         
  16.         if(str.length()>=2){
  17.  
  18.             System.out.println(str.substring(0,2));
  19.         }else{
  20.             System.out.println("please enter a string with minimum length of 2.");
  21.         }
  22.         }
  23.  
  24.   }

 Output:


  1. Please Enter a String
  2. miss you
  3. mi


Get First Two characters String Java

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

2 comments for How to get first two characters of a string in java

Select Menu