This question already has answers here:
What is this: [Ljava.lang.Object;?
(2 answers)
Closed 2 years ago.
I have a need to create the class name of an array in Java. I notice when using reflection to look at class names an array has a certain pattern:
For example for an array of array of com.foo.Thing
[[Lcom.foo.Thing;
What is the formula used to create this class name? I presume other letters besides 'L' mean different things. Are there libraries that help with this?
One letter for each primitive, one symbol for arrays, and one letter for reference:
I = int
J = long
D = double
F = float
Z = boolean
C = char
B = byte
S = short
Lcom/foo/Thing; = reference 'com.foo.Thing'
[ = array of whatever is next (so, [[I is an int[][]).
This is VM-speak for type signatures. For example, the signature of:
public boolean[] foo(String[] args, int count) { ... }
is: ([Ljava/lang/String;I)[Z.
It is for machines and not humans; it is easy to parse (you just move forward, no need to look-ahead).
This is not the 'class name' of a thing; the usual name for this construct is 'vm name'. Note that generics just disappear from these; the VM name of List<String> is Ljava/util/List;. It's why you can't override methods if the two methods end up with the same name, param types, and return type if you remove all generics.
Related
This question already has answers here:
Java N-Dimensional Arrays
(3 answers)
Closed 5 years ago.
Is it possible to have an n dimensional array in Java without having to explicitly specify the number of dimensions?
I.e. if I wanted a 2D array of ints I'd do:
int[][] myArray = new int[a][b];
For the above I've had to specify that the myArray variable is of type int[][]. What I'm asking is whether there's the possibility to declare a variable that is an array of n dimensions without having to know n in advance.
I.e. If I had the variable test, test could be of type int[][] or int[][][] or int[][][][][][][][][][][] - you get the idea. I just want to define test without having to define the number of dimensions.
I'm sure the above kind of breaks the type system in Java so I'm open to any ideas as I think I'm approaching this the wrong way.
To give you a bit of context I've developed an algorithm to find an integer in a 2D array of integers that are sorted by both row and column in ascending order. I've noticed that it will work with any dimension array and would thus like to make it more generic. However, I don't fancy defining a function for every possible dimension of array to be passed as a parameter since the dimensions could (unlikely as it is) be anywhere from 1D to infinityD - hence the question.
This is also just for my own curiosity as to whether this can be done for any dimension array. I don't know whether this potentially can't be done using Java's built in facilities and I'd be better building my own class system to support multi-dimension arrays in this situation.
You can not define an array as unknown-dimensional. But you can make your own class like NDimensionalArray, that would wrap array of another NDimensionalArray instances, and implement getter like getValue(int indexes...), and dimension()
class NDimensionalArray {
NDimensionalArray[] arrays;
int value;
int getValue(int... indexes) {
if (indexes.length == 0) return value;
return arrays[indexes[0]].getValue(indexes[1],indexes[2],...,indexes[n-1]);
}
void setValue(int value, int... indexes) {
// implement simillary to getValue
}
int getDimension() {
if (arrays == 0 || arrays.length == 0) return 0;
return arrays[0].getDimension() + 1;
}
}
that's not a working class, but only an idea, creating the entire structure is on your own. You would need to implement all the index and null checks.
This question already has answers here:
Error assigning to an an element in an array of BigInteger
(4 answers)
Closed 7 years ago.
Trying to use BigInteger first time, and this is my code:
public class Factx
{
public static void main(String[] args)
{
BigInteger[] asd = new BigInteger[10];
asd[0] = 123456458979851322316546445665;
System.out.println(asd[0]);
}
}
Compiling this, gives an error Integer number too large
I also tried changing,
asd[0] = new BigInteger(123456458979851322316546445665);
referred some other questions as well, didn't do much help, am I missing something? Whats the best fix? Thanks,
asd[0] = 123456458979851322316546445665; doesn't work for two reasons :
You can't assign a primitive value to a variable whose type is a reference type (unless that reference type is the wrapper class of that primitive type, like Integer is the wrapper of int).
123456458979851322316546445665 is too large for an int literal (and even if you add L suffix, it will still be too large for a long literal). This also explains why asd[0] = new BigInteger(123456458979851322316546445665); doesn't work.
Instead, use the BigInteger constructor that takes a String :
BigInteger[] asd = new BigInteger[10];
asd[0] = new BigInteger("123456458979851322316546445665");
System.out.println(asd[0]);
Output:
123456458979851322316546445665
Create BigInteger via
asd[0] = new BigInteger("123456458979851322316546445665");
BigInteger doesn't accept explicit cast from integer to BigInteger, only via constructors.
This question already has answers here:
C++ Pointers to Pointers in Java
(5 answers)
Closed 7 years ago.
For last some day I am learning Java while I have some knowledge in C. Now I am trying to convert code written in C to a Java code. There I found a pointer to pointer (pptr)variable declaration like this -
int n;
int *ptr;
int **pptr;
n = 13;
ptr = &n;
pptr = &ptr;
As far as I know, in Java there is no pointer type variable. My question is there any way to represent pptr or anything equivalent of pptr in Java?
Let's look at some of the use cases for multiple indirection in C, and see how they apply to Java.
Use Case #1: you want a function or method to change the value of a pointer or reference parameter such that it points to a new object, and have that change reflected in the caller.
In C, that would look something like this:
void foo( T **p )
{
*p = new_value(); // update the thing p points to
}
void bar( void )
{
T *var; // for any type T
foo( &var ); // foo will set var to point somewhere else
}
var is a pointer to something, and we want the function foo to change var such that it points to something else. Since C passes all function arguments by value, if we want foo to update var, we must pass a pointer to var, giving us a pointer to pointer type in foo.
Java doesn't expose operations on pointer types (no unary & address-of or * indirection operators), so we can't do this directly. We'd have to wrap the reference we want to change in another reference type and pass that wrapper type to the method, and even then I'm not sure it would do the same thing as the C code above:
public class thing
{
// attributes
}
public class thingWrapper {
{
public thing t;
}
public void pointToNewThing( thingWrapper tw )
{
tw.t = newThing();
}
public void bar()
{
thing t = new thing();
...
thingWrapper tw = new thingWrapper();
tw.t = t;
pointToNewThing( tw );
t = tw.t;
...
}
Use Case #2: you want to allocate a multi-dimensional array in a piecemeal fashion, rather than in a single operation. This is useful if you want a "jagged" array (where the number of elements in each row isn't uniform) or if you're trying to allocate a lot of memory and don't have a single available block large enough for the whole thing.
In C, you'd do something like
T **arr = malloc( N * sizeof *arr );
if ( arr )
{
for ( int i = 0; i < N; i++ )
{
arr[i] = malloc( M * sizeof *arr[i] );
}
}
because C arrays are not "first class" objects, and cannot be manipulated and assigned directly, so you have to do this through pointers.
Java treats arrays completely differently such that you don't need to do the pointer-to-pointer dance at all:
T arr[][] = new arr[N];
for ( i = 0; i < N; i++ )
{
arr[i] = new arr[M];
}
I can't think of other use cases off the top of my head, but that should give you a flavor of how you'd translate the C concept to Java.
The short answer is yes. But first, a lesson in Java...
In Java, whenever you use objects, pointers are involved. If you have an object, the variable that "holds" that object is actually a pointer to that object. So if you are working with objects, you are already using pointers.
Now for primitive data types (e.g., integers, chars, or floating point numbers), Java does not use pointers, though. So if you want pointers for primitive data types, you need to use a wrapper class, such as Integer, which effectively promotes the value to an object.
Note, however, that the default wrapper classes are immutable.
If you want double-pointers (a pointer to a pointer) or triple pointers, you will need to create custom wrapper classes, like an ObjectWrapper class, that allows you to set up an arbitrary number of objects each pointing to (or "holding") the next.
What you can do is create an int array even with a size of 1 this way when you access the array it will always refer to the same place in memory as far as your programming is concerned.
As we know variables are of different data types, but which data type are their names of?
As it seems they are String, but if they are String then this should be allowed:
int i=6;
String [] arr+i;
...as we can add an int to a String.
So if these are not String then what are they?
And if we want to create variable names dynamically how can we create it?
By dynamically I mean whenever the user clicks on a specific JComponent, a new variable is created, like:
int i=0;
//on first click
String str+i; ///str0
i++;
///on 2nd click
String str+i; ////str1
///i++;
How can I do it?
You can not create dynamic variables in Java because Java isn't a scripting language. YOu need to create variables in source code. But Java provides other ways to do this.
You can use arrays or Map<String, String> etc for this purpose.
Map<String, String> map= new HashMap<>();
int i=0;
while(true) {
// you can use whatever condition you need
details.put("key" + i, "val: "+i);
i++
// some condition to break the loop
}
Java identifiers are not of any type and definitely not String. You can't do this in java, instead, you use a data structure to use these values like ArrayList<String>and store the nth String in the nth index of the data structure like so:
ArrayList<String> strings= new ArrayList<String>(); // Create a new empty List
strings.add(index, string); //add string at index position of the List; can be replaced with strings.add(string) if the strings are being sequentially added
CONSIDER THIS:
public class Test {
public Test() {
}
public static void main(String[] args) {
// GenericType<Integer> intObj;//creates a generic type for integers
//String type
GenericType<String> strObj=new GenericType<String>("My data");
System.out.println("Value is " +strObj.getValue());
}
}
class GenericType<GT>{
GT obT;
GenericType(GT o){
obT=o;
}
GT getValue(){
return obT;
}
void showType(){
System.out.println("Type of GT is " +obT.getClass().getName());
}
}
GT is the name of a type parameter. This name is used as a placeholder for the actual type that will be passed to GenericType when an object is created. Thus, GT is used within GenericType whenever the type parameter is needed. Notice that GT is contained within
< >. This syntax can be generalized. Whenever a type parameter is being declared, it is specified within angle brackets. Because Gen uses a type parameter, Gen is a generic class, which is also called a parameterized type.
as mentioned above JAVA provide you with advanced generic classes such as ArrayList, Vectors, Hashmaps to cater for such scenarios .
previous thread similar: How to create new variable in java dynamically
Variable names do not have data types. They are merely references. They are not a String, they are not an int, they are just names. You can't dynamically declare a variable with a name derived from the name of another variable, Java does not work this way.
Java does not work this way. Other languages do but Java isn't one of them. You can't dynamically manipulate the names of variables because they are fixed at compile time. However, in some interpreted scripting languages such a thing is possible.
To be more accurate if they are fixed to be anything at all they are fixed at compile time. If java is not compiled in debug mode the names of the variables cease to be at all. They just become addresses of memory locations.
See this for details: Can I get information about the local variables using Java reflection?
Firstly variables can be categorized into two. primitives (standard ) types such as int, float,double, char,boolean, byte... and non-primitives(user defined)types such as String, Integer, Float, Double. String type fall under non primitive , its a class provided by java.lang Api such that when you create a string variable you are indeed creating an object EX String str; str is an object it can as well be declared as String str=new String();
hence the string class consist of helper methods that may help to achieve your objective, you can as well use concatenation/joining of strings as follows:
class Demo{
String str;
static int i;
JButton but=new JButton("click me!");
.....
public static void actionPeaformed(ActionEvent e){
Object source=e.getSource();
str="msg";
if(source==but){
String newStr;
newStr=str+i;
System.out.println(newStr);
}
}
}
where str may contain some message/text eg from label/elsewhere for every click
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is Java pass by reference?
see example below... need java.io library to run...
public class BlankClass extends ConsoleProgram {
public void run() {
while(true) {
setFont("London-24");
String name = readLine("Type a name: ");
fixName(name);
/* I know that the way this is written doesn't make sense and that println(fixName(name))
* is the right way. However, I thought that when objects then the method is using the object
* (in this case a string) and not a copy of it. In other words, it is referenced.
* So if it is referenced why isn't it printing out Steven when I give it STEVEN.
*/
//println(fixName(name); this is removed to show the question.
println(name);
}
}
private String fixName(String name) {
char first = name.charAt(0);
first = Character.toUpperCase(first);
name = name.substring(1);
name = first + name.toLowerCase();
return name;
}
}
Java always passes parameters by value - but in the case of classes/objects, the value that's passed is a reference, not an object itself.
What the type involved, the value of the argument expression is copied as the initial value of the parameter. Changes to the parameter variable itself are not seen by the caller, whereas changes to the object that the reference refers to will be seen.
For example, using StringBuilder (which is a mutable type):
public void foo(StringBuilder builder)
{
builder = new StringBuilder("Change to builder");
}
public void bar(StringBuilder builder)
{
builder.append(" - appended");
}
Now:
StringBuilder x = new StringBuilder("Original value");
foo(x);
System.out.println(x); // Still prints "Original value"
StringBuilder y = new StringBuilder("Original value 2");
bar(y);
System.out.println(y); // Prints "Original value 2 - appended"
Note that when I say "the value of the argument expression", that is never an object - it's either a primitive value, or a reference.
I like to think of an analogy with houses. Suppose you have a piece of paper (a variable) with directions to a house written on it. You call a method and use that variable as the argument - that creates a new piece of paper (the parameter) with the same directions on. If the method crosses out the original directions and replaces them with some other ones, that doesn't change the first piece of paper. On the other hand, if the method follows the directions and then paints the house red, then you would see that change if you followed the directions on the first piece of paper.
EDIT: To explain your original code... no objects are being copied, but the value of name in run is being copied into fixName. You're then changing the value of the parameter in fixName when you write this:
name = name.substring(1);
You're changing it again when you write:
name = first + name.toLowerCase();
Neither of these have changed the value of name in the calling code, which is still referring to the original string.
You're then returning the new string reference here:
return name;
but your calling code is completely ignoring it, because you've just written:
fixName(name);
One way to demonstrate what's happened is to use the return value in a new variable:
String fixedName = fixName(name);
Then you could print out name (which would show the original string) and fixedName (which would show the new one).
you pass a reference, so you work with the same string, BUT you return another string, because String in java is immutable - every operation (such as subString) produce new string and if you want to perform many operations on string (such as substring, replace etc.) use a StringBuffer or StringBuilder
This does not really answer your question, but you should avoid assigning parameters (like 'name' in this case), it can be handy at times but it is generally considered a bad practice because it often leads to unreadable and hard to maintain code.
In your case the variable is both a parameter and a local variable.
In Eclipse there is a warning you can activate for this in
Preferences->Java->Compiler->Errors/Warnings->Code style->Parameter assignment
I would recommend to set the parameter 'name' final in order to enforce this.
Return another String that is based on your 'name' String and name it properly.
The goal is that anyone reading your code should be able to quickly understand what is going on by elimination (the function is private, it is static, the parameter is final...). This excludes a lot of side effects.
Search for the concept of 'pure functions' on the web. Make the method static so the person reading your code knows that there are no side effects on the instance.
Here is the new version:
private static String fixName(final String name) {
final char firstCharOfName = Character.toUpperCase(name.charAt(0));
final String fixedName = firstCharOfName + name.substring(1).toLowerCase();
return fixedName;
}