Home »
Android
Android | How to declare string in Java with Android?
In this code snippet/application, we will learn how to declare a string using different methods in Java under Android Studio?
In this example, we will declare three string variables using different methods and print them in an Android Toast using Toast.makeText () method.
Android Code Snippet - Declare a String using Java
MainActivity.java
package com.includehelp.stringexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Type 1 Using new Keyword
String s = new String("Android");
//Type 2 assigning a group of characters to a string
String s1 = "Java";
//Type 3 Using Character Array
char [] strArray={'D','E','L','H','I'};
String s2=new String(strArray);
// Printing String in Toast.
Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,s2,Toast.LENGTH_SHORT).show();
}
}