working with String in java - java

In the given code,'s' is an object of class String.
When we pass 's' to a function,a copy of s will be created,which will be pointing to the same string.
but even then the changes made by the function are not getting reflected when done through method 1 but are getting reflected when we go by method 2.
Method 1:
class ST{
public static void main (String[] args) {
String s="Test";
change(s);
System.out.println(s);
}
static void change(String s)
{
s=s+"test";
}
}
Method 2:
class ST{
public static void main (String[] args) {
String s="Test";
s=change(s);
System.out.println(s);
}
static String change(String s)
{
return s+"test";
}
}
My question is, if every time a copy of the original reference is created, which is also pointing to the same string, then why does method one fail?

String objects are Immutables! You can't change them, so s=s+"test" creates a brand new String.
So the only way to manage it is your method number 2

Related

Method and Variable Scope Issue in Java

I need help I cannot figure out how to fix the scope of my variables. I want this to be an example for my notes but have been on it for almost 2 hours.
public class methodPractice{
String streetName;
int streetNum;
public static void streetName()
{
String streetName = "Pope Ave.";
}
public static void streetNum()
{
int streetNum = 11825;
}
public static void main(String[] args)
{
streetName();
streetNum();
System.out.println("This is your home adress: " + streetNum +
streetName);
}
}
Thank you for your help.
You are shadowing the fields. Use this to make sure you get the fields, or a compile error.
public static void streetName()
{
this.streetName = "Pope Ave.";
}
public static void streetNum()
{
this.streetNum = 11825;
}
Here is your main method, with line numbers added:
1. public static void main(String[] args) {
2. streetName();
3. streetNum();
4. System.out.println("This is your home adress: " + streetNum + streetName);
5. }
A few points...
When line 2 runs, "streetName()" calls the static method below. The static keyword says you are free to call the method by itself – that is, you don't need an object; you don't need to call new methodPractice() first.
public static void streetName() {
String streetName = "Pope Ave.";
}
When line 3 runs, it's the same thing: "streetNum()" calls a different static method – again, totally fine to call this by itself.
public static void streetNum() {
int streetNum = 11825;
}
Line 4 is different, there are a few things going on. Your expectation is that "streetNum" finds the int that you declared on the class, but it doesn't work. Why? Because you defined that member with "int streetNum" – without "static". So what? Without being declared static, it means "streetNum" belongs to an object instance. What does that look like? Here's an example showing object creation, followed by setting the object member "streetNum" to 1.
methodPractice object = new methodPractice();
object.streetNum = 1;
You could work around this by declaring both of the non-static members to be static (static String streetName, and static int streetNum). Or you could leave them as is, and interact with them through an object instance (after doing new ..).

I can compile this code and the build is successful, although nothing is printing out on the print line

public class TEST {
String name1 = "Kelly";
String name2 = "Christy";
String name3 = "Johnson";
public static void main(String[] args) {
}
public void displaySalutation(String name1) {
displayLetter();
}
public void displaySalutation(String name2, String name3) {
displayLetter();
}
public void displayLetter() {
System.out.println("Thank you for your recent order.");
}
}
The main method needs to make a call to the method containing the print line. This can be done by creating an instance of TEST which contains the methods to print. You then call the methods contained in the instance variable.
I've updated your code to show how to create an instance and call the method.
public class TEST {
String name1 = "Kelly";
String name2 = "Christy";
String name3 = "Johnson";
// Define the entry point
public static void main(String[] args) {
// Create an instance of test
TEST test = new TEST();
/* Call the displayLetter method within TEST
Prints "Thank you for your recent order." */
test.displayLetter();
/* Call the printName method with the "Kelly" String as an argument.
Prints "Kelly" */
test.printName(name1);
}
// Prints a line
public void displayLetter(){
System.out.println("Thank you for your recent order.");
}
// Example print variable
public void printName(String name){
System.out.println(name);
}
}
I've corrected your code so that you can call the displayLetter method but I'm unsure exactly what you would like to do with the other two methods.

Calling an array from a different class - Java

How can I access my array from a different class? I have 3 classes; Main (where I want to access the array from) FramePanel (my GUI and where the value from UserInputNum is taken from) and StoryArray (where my array is saved).
I need to access the array in the nested If loop in the Main class, this is because I want too save the specific array data to a string and eventually append it into a JTextArea.
Here are the two classes needed:
Main.java
public class Main
{
public static String UserInput;
public static int UserInputNum;
public static void main(String[] args)
{
FramePanel.main();
StoryArray.main();
UserInputNum = Integer.parseInt(UserInput);
if (UserInputNum >= 0)
{
if (UserInputNum <= 399)
{
StoryArray.storyLine[UserInputNum];
}
else
{
}
}
else
{
}
}
}
StoryArray.java
public class StoryArray
{
public static String storyLine[] = null ;
public String[] getStoryLine()
{
return storyLine;
}
public static void main()
{
//String[] storyLine;
storyLine = new String[399];
storyLine[0] ("1")
storyLine[1] ("2")
storyLine[2] ("3")
storyLine[3] ("4")
storyLine[4] ("5")
storyLine[5] ("6")
In another class you can call the array like this:
String value = StoryArray.storyLine[index];
As it is a static public field you can access it directly by StoryArray.storyLine. But as you have a getter ethod I would suggest to make this getter setter static and the array field private and access it through getter method like that: StoryArray.getStoryLine() (to see why read about encapsulation).
You also shouldn't start your class (main) name from lower case, here are standard coding conventions for java language: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
Once you've called StoryArray.main(), then you should be able to do StoryArray.storyLine[/*element id*/] = "whatever you want" to get or set any element in storyLine. Additionally, you aren't defining any default array values. In StoryArray.main(), you need to have lines of the form storyLine[n] = "n".

Java - cannot make a non static reference to the non static field [duplicate]

This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 8 years ago.
Hello I am trying to build a simple program that converts a string containing a number into an integer. I am receiving the error on the System.out.println and not sure why, can anyone help?
public class TypeConvert {
int strToInt;
public int convert (String s){
strToInt = Integer.parseInt(s);
return strToInt;
}
public static void main(String[] args) {
String strNumber=("100");
TypeConvert convertToInt = new TypeConvert();
convertToInt.convert(strNumber);
System.out.println(strToInt);
}
}
This has been marked as duplicate so I am editing. I did actually read all the relevant posts to my problem but as I did not understand how to fix my problem with theirs I created my own post.
Change this,
System.out.println(strToInt);
to
System.out.println(convertToInt.strToInt);
because strToInt is a field of the TypeConvert instance (which you've named convertToInt).
Alternatively, you could write
System.out.println(convertToInt.convert(strNumber));
since the convert function returns the result.
Your convert method should be a static method since she doesn't need any "state" information.
public class TypeConvert {
public static int convert (String s){
int strToInt = Integer.parseInt(s);
return strToInt;
}
public static void main(String[] args) {
String strNumber=("100");
int strToInt = TypeConvert.convert(strNumber);
System.out.println(strToInt);
}
}
Usually you create non-static fields and instance methods when you need to use a state. For example let's print the name of a person:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public static void main(String[] args) {
Person bob = new Person("Bob");
Person john = new Person("John");
System.out.println(bob.getName()); // Prints "Bob"
System.out.println(john.getName()); // Prints "John"
}
}
In this case you absolutely need to "save" the name variable in a property of the instance because each Person is going to have a different name.
In the example you gave us, for a given string, the ouput will always be the same so you can use a static method.

calling main method from another method in the same class

How to call the main method?
void prompt()
{
System.out.println("Do you want to continue?");
Scanner confirm = new Scanner(System.in);
String con = confirm.nextLine();
if (con == "y")
{
//call the main method once again.
}
}
When I use
main();
It asks for the value of "args" yet I'm not sure what value I should put in it.
The main() method in a java program takes a String array argument.
public static void main(String[] args) {}
If you do not use the variable args inside of main() you could just pass null to it. Otherwise you would need to pass a String array to the method.
However, you should not be calling the main() method from inside your application. The main() method should be used as an entry point into your application, to launch a program, not be used to recursively execute the logic inside that application. If you have functionality needed again you should put it in a separate method.
Signature of main method is: public static void main(String[] args)
The main method accepts a single argument: an array of elements of type String.
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. For example:
public static void main(String[] args) {
System.out.println("args = " + args);
}
public static void prompt() {
System.out.println("Do you want to continue?");
Scanner confirm = new Scanner(System.in);
String con = confirm.nextLine();
if (con == "y") {
String[] args = {<set string array>};
main(args);
}
}
For more details, look at this Oracle document: The main Method

Categories