- 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.
- package StringInterviewprograms;
 - public class GetFirstTwoCharacters {
 - /**
 - * How to get First N characters in java
 - * @author www.instanceofjava.com
 - */
 - public static void main(String[] args) {
 - String str="Get first two characters of a String";
 - System.out.println(str.substring(0,2));
 - }
 - }
 
Output:
-  Ge
 
Program #2:
- package StringInterviewprograms;
 - import java.util.Scanner;
 - public class GetFirstTwoCharacters {
 - /**
 - * How to get First N characters in java
 - * @author www.instanceofjava.com
 - */
 - public static void main(String[] args) {
 - Scanner sc= new Scanner(System.in);
 - System.out.println("Please Enter a String");
 - String str=sc.next();
 - if(str.length()>=2){
 - System.out.println(str.substring(0,2));
 - }else{
 - System.out.println("please enter a string with minimum length of 2.");
 - }
 - }
 - }
 
Output:
- Please Enter a String
 - miss you
 - mi
 

how to take 3 character from a string
ReplyDeletestr.substring(0,3);
Delete