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();
    }
}






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.