Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

Display Variable's value in Text in a Java Program

Value of a variable displayed with a String

In computer programming, a letter or digit is called a character and a collection of letters or digits that make a phrase, sentence, or paragraph, is called a string. Java uses the concatenate operator (+) to paste two or more strings together. However, you can also use the concatenate operator to display the value of a variable with a String. Shown below is the Java code to display the value of a variable with a String.

import javax.swing.*;

public class varsInText 
{

   public static void main(String s[])
   {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.setSize(300,300);
      frame.setLocationRelativeTo(null);
      frame.setTitle("Variables in Text");

      int inches = 72;
      int feet = 6;

      String tall = "My height is " + inches + " inches or " + feet + " feet.";

      JTextArea myText = new JTextArea();
      myText.setLineWrap(true);
      myText.append(tall);
      frame.add(myText);

      frame.setVisible(true);
   }
}

In the code shown above two integer variables are declared, one named inches is initialized with the value 72, and one named feet is initialized with the value 6. The line below that declares a String named tall is initialized with substrings and the variables names. Java will automatically convert the integer values to Strings for display.

Note that, although in Java, the names of primitive variable types, like int and char begin with lower-case letters, the String variable type is capitalized. That's because strings are actually objects, which makes them very powerful because they contain methods like .length() and getChars.

I generally hate it when people add a bunch of extra code to an example. It confuses things. But in this case I've included the javax.swing library and added code to create a JFrame and a JTextArea. If I didn't add this extra code, you would need to use the System.out.print command to output text, and I don't think that's an interesting or realistic way to learn Java programming.

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro


Java

Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2024 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268