Is there any particular reason why this kind of literal is not included whereas hex and octal formats are allowed?
Java 7 includes it.Check the new features.
Example:
int binary = 0b1001_1001;
Binary literals were introduced in Java 7. See "Improved Integer Literals":
int i = 0b1001001;
The reason for not including them from day one is most likely the following: Java is a high-level language and has been quite restrictive when it comes to language constructs that are less important and low level. Java developers have had a general policy of "if in doubt, keep it out".
If you're on Java 6 or older, your best option is to do
int yourInteger = Integer.parseInt("100100101", 2);
actually, it is. in java7.
http://code.joejag.com/2009/new-language-features-in-java-7/
The associated bug is open since April 2004, has low priority and is considered as a request for enhancement by Sun/Oracle.
I guess they think binary literals would make the language more complex and doesn't provide obvious benefits...
There seems to be an impression here that implementing binary literals is complex. It isn't. It would take about five minutes. Plus the test cases of course.
Java 7 does allow binary literals !
Check this:
int binVal = 0b11010;
at this link:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Related
This question already has an answer here:
How to have placeholder for variable value in Java Text Block?
(1 answer)
Closed 2 years ago.
Just came across a new feature in Java 15 i.e. "TEXT BLOCKS". I can assume that a variable can be added inside a text block by concatenating with a "+" operator as below:
String html = """
<html>
<body>
<p>Hello, """+strA+"""</p>
</body>
</html>
""";
But are they providing any way so that we can add variables the way which is becoming popular among many other languages as below:
String html = """
<html>
<body>
<p>Hello, ${strA}</p>
</body>
</html>
""";
This question might sound silly but it may be useful in certain scenario.
Java 15 does not support interpolation directly within text blocks nor plain string literals.
The solution in Java 15 is to use String.formatted() method:
String html = """
<html>
<body>
<p>Hello, %s</p>
</body>
</html>
""".formatted(strA);
From the spec for text blocks:
Text blocks do not directly support string interpolation.
Interpolation may be considered in a future JEP.
"String interpolation" meaning
evaluating a string literal containing one or more placeholders,
yielding a result in which the placeholders are replaced with their
corresponding values
from Wikipedia
As stated above, maybe we'll get it in the future. Though it is difficult to say how they could possibly implement that without breaking backwards compatibility -- what happens if my string contains ${}, for example? The Java language designers rarely add anything that is likely to break backwards compatibility.
It seems to me that they would be better off either supporting it immediately, or never.
Maybe it would be possible with a new kind of text block. Rather than the delimiter being """, they could use ''' to denote a parameterized text block, for example.
As already discussed, this is not possible in JDK15 and you cannot change that fact.
But, I suppose you are trying to suggest a thing like this in C# language.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
Although this is just a syntax sugar thing over string.Format() method in C# (which is a counterpart of String.format() in Java), apparently it is nice if we can have this in Java. This is an extension to the existing way of describing string literal in the language syntax, but of course this can be easily adapted onto text block specification as well.
If this is what you have in your mind, you can make a proposal to Java Community Process to expand Java Language Specification. This is very much lighter syntax/semantics enhancement than adding full-featured template engine in Java Compiler/Runtime specification, and it is possible that they would agree with you.
As user #Michael mentioned: No. 'they' (team Project Amber, who are implementing JEP 368) are not providing any way to interpolate the string in the text block.
Note that I somewhat doubt it'll ever happen. For starters, there is the backwards compatibility issue; any such attempt to introduce interpolation requires some marker so that any existing text blocks aren't all of a sudden going to change in what it means depending on which version of javac to invoke.
But more to the point, you yourself, asking the question, can't even come up with a valid example, which is perhaps indicative that this feature is less useful than it sounds. It looks like you came up with a valid use case, but that's not actually true: If what you wrote would compile and work, then you just wrote a webapp with a rather serious XSS security leak in it!
The point is, what you really want is 'templating', and whilst templating sounds real simple (just evaluate this expression then shove the result into the string right where I typed the expression, please!) - it just isn't. Escaping is a large reason for that. But you can't blanket-apply the rule that ${strA} in a text block means: Evaluate expression strA, then HTML escape that, then put it in, for two reasons: Who says that the string you're interpolating things into is HTML and not, say, JSON or TOML or CSV or whatnot, and who says that the interpolation I desire requires escaping in the first place? What if I want to dynamically inject <em> or not, and I don't want this to turn into <em>?
Either we update the langspec to cater to all these cases and now we're inventing an entire templating system and shoving that into a lang spec which seems like a job far better suited to a dedicated library, or we don't, and the feature seems quite useful but is in fact niche: Either you rarely use it, or you have security and other bugs all over your code base - any lang feature that invites abuse is, and I'd hope one would agree with me on this - not a great feature.
Yes, many languages have this, but the current folks who get to decide what java language features make it into future versions of the language seem to be in the phase that they acknowledge such features exist and will learn lessons from it, but won't add features to java 'just because all these other languages all have it' - some thought and use cases are always considered first, and any such analysis of interpolation on string literals probably leads to: "Eh, probably not a worthwhile addition to the language".
a teacher of mine said, that Java cannot be LL parsed.
I dont understand this and wonder if this is true.
I searched for a grammar of Java 8 and found this: https://github.com/antlr/grammars-v4/blob/master/java8/Java8.g4
But even if I try to analyze the grammar, I dont get the problem for LL parsing.
Does anyone know if this is true, know a scientific proof or just can explain to me why it should be not possible to find a grammar construct of Java which can be LL parsed?
Thanks a lot guys and girls.
The Java Language Specification for Java 7 says it is not LL(1):
The grammar presented in this chapter is the basis for the
reference implementation. Note that it is not an LL(1) grammar, though
in many cases it minimizes the necessary look ahead.
If you either find:
left recursion, or
an alternative (A|B) that the intersection of two or more alternatives share the same FIRST set; FIRST(A) has one or more symbols also in FIRST(B)
Your grammar won't be LL(1).
I think it's due to the left recursion. LL parsers cannot handle left recursion and the current Java grammar is specified in some cases using them, at least Java 7.
Of course, it is well known that one can construct equivalent grammars getting rid of left recursions, but in its current specification Java language could not be LL parsed.
Thi is a fundamental questuion about how java works and so i dont have any code to support it.
I am new to java development and want to know how the different number systems, charecter sets like UTF 8 and unicode come together in Java.
Lets say a user creates a new string and int with the same value.
int i=100;
String S="100";
The hardware of a computer understands zeros and ones. so it has to be converted to binary?(correct me if im wrong). this conversion should be done by the JVM(correct me if im wrong)? and to represent charecters of different languages into charecters that can be typed into the keyboard (english) UTF-8 and such conversions are used(correction needed)?
now how does this whole flow fit into the bigger picture of running a java web application?
how does a string/int get converted to a binary for the machine's hardware to understand?
how does it get converted to UTF-8 for a browser to understand?
and what are the default number format and charecterset in java? if im reading contents of a file? will they be read into binary or utf-8?
All computers run in binary. The conversion is done by the JVM and the computer that you have. You shouldn't worry about converting the code into the coordinating 1's and 0's. The browser has its own conversion hard code to change the universal 1's and 0's(used by all programs and computer software) into however it decides to display the given information. All languages are just a translation guide for the user to "speak" with the computer. And vice versa. Hope this helps though I don't think I really answered anything.
How java represents any data type in memory is the choice of the actual JVM. In practice, the JVM will chose the format native to the processor (e.g. chose between little/big endian for int), simply because it offers the best performance on that platform.
Basically, the JLS makes certain guarantees (like that a byte has 8 bits and the values range from -128 to 127) - the VM just maps that to the platform as it deems suitable (the JLS was specified to match common computing technology closely, so there is usually no magic needed to guess how primitive types map to the platform).
You should never care how the VM represents data in memory, java does not offer any legal way to access the data in a manner where you would need to know (bypassing most of the VM's logic by using sun.misc.Unsafe is not considered legal).
If you care for educational purposes, learn what binary representations the underlying platform (e.g. x86) uses and take a look at the VM. It has little to do with java really, its all VM and platform specific.
For java.lang.String, its the implementation of the class that defines how the String is stored internally - it went through quite some changes over major java versions - but what that String exposes is quite narrowly defined (see JDK javadoc for String.length(), String.charAt()).
As for how user input is translated to java standard types, thats actually platform specific. The JVM selects the default encoding (e.g. String.toBytes() can return quite different results for the same string, depending on the platform - thats why its recommended to explictly specify the desired encoding). Same goes for many other things (time zone, number format etc.).
CharSets and Formats are building blocks the program wires up to translate data from the outside world (file, http or user input) into javas representation of data (or vice versa). For example, a Web application will use the encoding from a HTTP header to determine what CharSet to use when interpreting the contents (the HTTP headers encoding is defined to be US-ASCII by the spec).
What's the difference between KeyEvent.SHIFT_DOWN_MASK and KeyEvent.SHIFT_MASK?
The Javadoc says that "It is recommended that SHIFT_DOWN_MASK be used instead".
If you look at the values as binary numbers, you'll see that they form a complete bitset from 20 though 213. The *_MASK values form the lower range, and the *_DOWN_MASK form the upper. They all have the same recommendation, with the latter superseding the former.
Addendum: #Boann comments, "This states that they're different. It doesn't explain why."
I am relucatnt to speculate, but I think it's reasonable to infer that the developers needed to accommodate extended modifiers, discussed here, while preserving backward compatibility.
For implementation specific reasons, I have to use Java 1.2. I am trying to parse a String object with only numbers (I replace variables beforehand to abstract that step) and operators (PEDMAS). I have found a lot of libraries that do this well, but unfortunately nothing that is compatible with Java 1.2 (Even with fiddling, all of them are dependent on things like generics). Obviously I'm capable of making this myself, but I would certainly prefer to not remake the wheel. Are there any libraries that I just haven't found yet that could do this for me? Thanks.
(Requirements: Binary operators and parentheses)
EDIT: As requested, some examples of input and output:
"(10 / 5) + 4.5 - (8)" would give you -1.5
"(1/3) * 4" would give you 1.3333333...
"5^3 + 4 * 2" would give you 133
"-10 + 5" would give you -5
Hopefully that makes sense.
You can write your own recursive descent parser. This Java implementation uses StreamTokenizer, available since 1.0, but you'll have to substitute int constants for the enum tokens and ignore tokenIs(Symbol.WORD) for function identifiers.