String Class Is Not Immutable - Can Reassign Another Value To Same Variable

Feb 26, 2015

public static void main(String[] args) {
String str1="Java";
str1="one";
System.out.println("str1="+str1);
}

String object is stored in a private final char array in String.java.
private final char value[];

The basic characteristic of a final variable is that it can initialize a value only once. By marking the variable value as final, the class String makes sure that it can’t be reassigned a value.

so the String objects can be initialized only once but the above code shows that str1 was initialized first with "Java", then it can be re-assigned value "one" bcos the output is one. If it can be re-initialized, basic characteristic of final variable is not satisified and hence how can we call String objects are immutable?

View Replies


ADVERTISEMENT

Why Only String Class Is Immutable

Feb 24, 2015

I would like to understand why only String class is immutable.

1. Why String class is immutable? What is the main reason for making String class as immutable.
2. Why there is no int pool or float pool or Integer pool etc, why only String pool.

View Replies View Related

Meaning Of String Or Immutable Class

Aug 26, 2014

this is my code :

String name = "Mohan";

String is a immutable class and where these character stored when we assign some character. How the logics are working inside the String class.

View Replies View Related

String Immutable In Java?

Jun 26, 2014

I am a java fresher. I want to know weather String is immutable in Java or not .....

View Replies View Related

How To Test If Class / Object Is Immutable

Jul 2, 2014

I have make the immutable class as below, Now my question is how I can test if my this class/object is immutable

package com.learning;
import java.util.*;
import java.util.Map.Entry;
public final class ImmutableTest {
private final int id;
private final String name;
private final HashMap<String, String> hm ;

[Code]...

How I can Test If it is immutable class without looking ?

View Replies View Related

Create Separate String Objects As Strings Are Immutable

Jan 28, 2015

I want to clarify it whether this below code, when running this loop, will it create separate string objects as strings are immutable or else, will it keep the same reference(as each time inside loop, we use the same name 'rslt') and assign new string value for this?

while(inc < numberOfColumns){
String rslt=rs.getString(inc+1);
rowArr[inc] = rslt;
inc++;
}

View Replies View Related

Create Class Employee Which Contains A String Variable Employee Number

Jul 13, 2014

I have searched for totalPay is always 0 and the responses are not related to my problem (that I can tell).This is a class assignment and I have other questions besides why the method is not working.

Here are the instructions: Create class Employee which contains a String variable Employee Number, a String variable Employee Name, an integer Hours Worked, and a double Pay Rate. Create get and set methods for each variable. Provide method "totalPay" which calculates and returns the total pay by multiplying the hours worked by pay rate. Use figure 8.12 as an example of an object with get and set methods.

Unlike other examples of this type question online this one has Employee Number as a String variable. The book is How to Program Early Objects by Deitel 9th edition.We have instructions to do only what she has told us too. At this point it is objects and getter and setter methods. It is only the beginning of week 2.

ON THE LINES WHERE I HAVE QUESTIONS I AM COMMENTING IN ALL CAPS. NOT SHOUTING, JUST TRYING TO MAKE IT EASIER

package test11;
import java.util.Scanner;
public class Test11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

[code]..

Essentially I cannot figure out how to get the method getTotalPay to be called by the Scanner and do the math. I also have this random bracket problem that showed up about an hour ago.

The concept I don't get is that if I omit this.employeeNumber =id; etc. I error all over the place. If I change it to this.employeeeNumber = employee Number Netbeans tells me it is assigning itself to itself, which I know. When I try to use id instead of employeeNumber I get errors all over. If i remove "this" from it the same happens. why in public class employee I have to change to those values (id, name, etc) in the construct and set them again? I don't see where or how they can be used, so why do i have to do it?

View Replies View Related

How To Use Value Of String Variable Cel1 As Variable Name

May 23, 2014

I have a JFrame jf and JPanel jp on it. jp has five TextFields named cel1, cel2.. cel5. I wish to construct a String Cel + for loop index and run a for loop to reset the values of all the text fields using a single statement such as cel1.SetText("abc"). Similar things can be done in foxfro. How does one do it in java?

View Replies View Related

Error Passing Value Of A Variable From One Class To Main Method Of Another Class

Jan 8, 2014

I've 3 classes.

1. Circle
2. GetInputFromUser
3. testCircle

package ABC;
public class Circle {
private double radius;
public double getRadius() {
return radius;

[Code] .....

In the testCircle class, in the line: getRadius = ui1.GetInput();

It's showing the error: The method GetInput(float) in the type GetInputFromUser is not applicable for the arguments ()

And when I do: getRadius = ui1.GetInput(rad);

It's showing the error: rad cannot be resolved

View Replies View Related

Using A Variable From Main Class In Another Class

May 31, 2014

I have a program with 4 classes, all of them in the same package, one of them is the Main class, and in that class I declared a variable named "port" of type int. One of the 3 another ones is the class Connection class, which it requires the port variable. I want to use this variable in the Connection class. How can I do it?Both classes are shown below:

Main.java
package server;
/* Imports */
/* Another variables */
int port; /* <-- IS THIS ONE */

[code]....

View Replies View Related

4 String Variable Concatenation

Jan 27, 2014

I am trying to concatenate 4 strings together to later be able to make them all upper case, or lower case or get the length. I keep getting an error on line 16.

import java.util.Scanner;
public class userInput
{
public static void main(String[] arg)
{
Scanner keyboard;
keyboard = new Scanner(System.in);
String msg1, msg2, msg3, msg4;

[Code] ....

View Replies View Related

Can Classes Be Immutable In Some Situations But Not Others

Feb 12, 2014

I have some complex objects I want to design. Most of the time I would like these objects to be immutable so that other classes cannot change their values. However, I also want to create an editor to create these objects and the editor will need to change the object's values. It would also be useful to be able to set the objects' fields one at a time during serialization rather than doing everything in a huge constructor.

C provides a way to make objects unchangeable by using the 'const' keyword, but Java doesn't have that. I could also wrap my objects in other accessor objects, but then I'm duplicating a lot of code. Are there any good ways to make my objects mutable only to certain other classes?

View Replies View Related

Strings Are Immutable In Java

Sep 21, 2014

strings are immutable in java...so can we apply toupper nd tolower function directly in a string

View Replies View Related

Implementation Of Immutable Queue

Nov 12, 2014

The following codes shows an implementation of an enqueue function of a FIFO immutable queue, and the output result shows the String "c".

I don't understand why since I expected it should be null.

The head and the tail of an ImmutableQueue Object are two separate queue, and each time I call the enqueue function, it just return a new object with a new tail, however, the head is not modified except the first two times I call the function.

Therefore, I expected head.next.next should be a null element, but the result is not like that.

public class ImmutableQueue<E> {
private int size =0;
public Queue<E> head;
public Queue<E> tail;
public ImmutableQueue(){}
private ImmutableQueue(Queue<E> hd, Queue<E> tl){
head=hd;
tail=tl;

[Code] ....

View Replies View Related

FIFO - Implementation Of Immutable Queue

Nov 12, 2014

The following codes shows an implementation of an enqueue function of a FIFO immutable queue, and the output result shows the String "c". I don't understand why since I expected it should be null.

The head and the tail of an ImmutableQueue Object are two separate queue, and each time I call the enqueue function, it just return a new object with a new tail, however, the head is not modified except the first two times I call the function.

Therefore, I expected head.next.next should be a null element, but the result is not like that.

public class ImmutableQueue<E> {
public Queue<E> head;
public Queue<E> tail;
public ImmutableQueue(){}
private ImmutableQueue(Queue<E> hd, Queue<E> tl){
head=hd;
tail=tl;

[Code] ......

View Replies View Related

Static Variable Within A Class?

Dec 8, 2014

I have a class Tree in which all the methods to build a tree are in place. But however I would want variable of by Tree which is pointing to the last node being added to the tree.

So basically every time you keep adding a node to the tree you tail pointer gets updated to point to the last node. I have this so far.

public class NonEmptyTree implements Tree {
private Tree left;
private int data;
private int leftleafCount;
private int rightleafCount;
private Tree right;
private Tree tail; // This variable must be shared by all the object. There needs to just one tail pointer to the tree.
public Tree insert( data ) {
tail = // gets updated every time when new node gets added.

View Replies View Related

How To Transfer The Value Of A Variable From One Class To Another

Mar 12, 2015

I am developing a program that seems to need to transfer the value of a variable from one class to another. However, neither of the classes is the main class.

This simplified code should make my problem clear:

This is my main class where I create runone from Class1 and runtwo from Class2:

public class MainClass {
public static void main(String[] args) { 
Class1 runone = new Class1();
Class2 runtwo = new Class2(); 

}

This is Class1 where I set up x and give it the value 20. I also have a getter-method to be able to access the value of x from other classes.

public class Class1 {
int x = 20;
public int getX(){
return x;
}}

This is Class2, where I try to access the value of x that was set up in runone.

public class Class2 {
int y;
public Class2() {
y = runone.getX + 10;
System.out.println(y);
}
}

Unfortunately, I get the error message "runone cannot be resolved to a variable."

What do I do to be able to access the variable x (that is set up in Class1) from Class2?

View Replies View Related

How To Implement A Variable Into Another Class

Apr 13, 2015

I would like to implement a variable in a class that is used in another class, how can I do that?

I have a Mall class and a Customer class I would like to associate the position of the customer that is in the Mall class and also implement the same in the Customer class.

Here is a small part of the code without all the methods.

//the two objects
Mall m = new Mall("RandomMall",50,30);
Customer c1= new Customer("Jack",1240);
//the first part of the mall class without the methods
class Mall{
private String name;
private int width,length;
String[][]grid = new String[width][length];

[code]...

View Replies View Related

Passing In Variable From One Class To Another?

Aug 16, 2014

It just wont work... Everytime I try to pass a variable into a class it sets it to 0. What to do.

The variable should be '2', but it prints out as 0!?

Java Code: package Zoo;
import java.util.Random;
public class Animal {
Random random = new Random();
public void Eat(){
System.out.println("The animal starts to eat.");

[Code]...

The method bash, needs the variable 'playerTwo' to be 2, to carry on. But it prints out 0.

Int the animal constructor, I passed in the variable from another class, and it prints out 2 in the constructor like it should. But outside of the constructor it is equal to 0.

View Replies View Related

Pass A Variable From One Class To Another

Jan 5, 2014

As the title says, how can I pass a value from one variable to another class?

Example:

So here I'm switching one frame to another, called "redigeraProjekt". Now in this class, I want the value from .getSelectedIndex() pass over to that class. I've tried to use the variable "valIListan" but it cannot find it. Probably because it's "private" (?)

valIListan = listaAllaSpelProjekt.getSelectedIndex();
redigeraProjekt npj = new redigeraProjekt(); // "switching" to another frame
npj.setVisible(true);
this.setVisible(false);

I hope you understand what I'm saying

View Replies View Related

Each Class Contain Private Variable

Sep 22, 2014

I'm working on a project that contains multiple classes. Each class contains and must contain only PRIVATE variables. Here's my issue. When my test code calls for a new instance of "StudentClass" as so:

StudentClass studentClass = new StudentClass(offeredClass.getClassIdNumber(),
offeredClass.getClassName(),
offeredClass.getClassroom());

The corresponding constructor won't let me initialize it's variables because they are declared private within another class, as shown here:

StudentClass (float classIdNumber, String className, Classroom room){
this.classIdNumber = classIdNumber;
this.className = className;
this.room = room;
}

When getClassName, getClassroom, and getClassIdNumber are passed to a toString() method elsewhere in my test code. the output is returned just fine. When passed through the StudentClass, I'm getting Null across the board.

View Replies View Related

How To Compare Integer To A String Variable Array

Apr 17, 2014

I'm trying to do something like this:

Java Code:

for (int i=1; i<2; i++);
int randomNum = rn.nextInt(range) + 1;
if (randomNum == CardList.CARD_NAME[randomNum]){
} mh_sh_highlight_all('java');

But the CARD_NAME variable is a string. I just want to compare the array to the integer.

View Replies View Related

Class Method Which Take String And Returns A String In Reversed Version

Dec 16, 2014

i am trying to write a class method which will take in a string and returns a string which is the reversed version of that string. it compiles fine but when i try to run it it states Main method not found in class StringReverse,please define the main method as public static void main(String[]args). I am new to java and cannot figure out

import javax.swing.JOptionPane;
public class StringReverse {
public String reverseString(String str){
JOptionPane.showInputDialog(null,"Please enter word");
char c = str.charAt(str.length()-1);
if(str.length() == 1) return Character.toString(c);
return c + reverseString(str.substring(0,str.length()-1));}}

View Replies View Related

Get The Value Of A Variable Stored In Another Class Of Another Package?

Nov 12, 2014

Source packages

1.First package : CarDealer.java (JFrame form)

2. Second package : Vehicle.java (JFrame form)

- The user runs CarDealer JFrame in which appears a JTexField in which he types in some characters (pretending he types some data about selling licence).
- The user clicks on the JButton "Save" that stores the characters typed in inside a String variable called strLicence.
- The user clicks on the JButton "Open 'Vehicle Form'" that opens the Vehicle JFrame.
- Finally, in the Vehicle JFrame I want to write a code that can see/use the value of the String variable called strLicence.

In other words, for example, I want to store the value of strLicence in a new variable declared in the Vehicle class.

(Actually I'm working with a long and elaborate project for the dissertation of my bachelor's degree, so, for cutting to the chase, I simplified it by creating an essential JFrame project.)

I used netbeans

1. CarDealer.java

package Firstpackage;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;

[code]....

I also attach the netbeans project in a zip file ....

View Replies View Related

Sandwich Class Static Variable

Apr 14, 2015

Sandwich class. I have thus far completed creating a sandwich class with a seperate sandwich Tester class to run with it. (this is according to the assignment). Now I must create Static variables for the sandwich class:

Add two static variables to the Sandwich class to count how many sandwiches are sold and how many slices of tomato are used. Initialize each to 0.Where do you add code to increment the sandwich counter? Determine this and then add code.

public class Sandwich
{
static int numOfSold = 0;
static int slicesUsed = 0;
private String meat;
private int numOfSlicesOfTomato;
private boolean lettuce;

[code]....

View Replies View Related

Class Cannot See Its Own Protected Variable From Another Package

Jan 30, 2014

how access levels work from subclasses and other packages, and I have discovered that a class cannot see it's own protected variable from another package which I thought it would be. I know that it says in the java docs "The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package." but I thought that would also include it's own class.

Java Code:

package food;
import food.fruit.*;
public class Food {
protected int protecte = 5;
private int privat = 5;
protected void method(){

[Code] ....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved