This question already has answers here:
Can I have macros in Java source files
(9 answers)
Closed 6 years ago.
In C i used to use #define p printf
to help me code easily rather than typing printf every time
let me give an example to understand better
p("hello world");
it does the job of
printf("hello world");
There is a way in java to do this I went through it long back Its not a duplicate question as they answered there is no way Iam sure of there is a way to do this using ENUM
How can I implement this in java
You need to use a method in a helper class.
e.g.
enum Helper {;
static void p(String fmt, String... args) { System.out.printf(fmt, args); }
static void p(Number n) { System.out.print(n); }
}
so you can call
import static mypackage.Helper.p;
p("hello world");
There is no scanf though you can use a Scanner to do something similar.
Most of the useful things you can do with macros, you can do with simple Java syntax. In term the JIT will optimise the code at runtime to get the same performance benefits.
Simple answer: you don't. Java doesn't have that kind of text substitution.
Actually, you shouldn't be making those types of substitutions in C, either. A #define like that is a recipe for trouble.
For the love of god. Don't do this. You'll have a lot of unexpected behavior in your code.
However you could learn some shortcuts like typing "syso" + Return (in Eclipse) or "sout" +Return (in Netbeans). Does not shorten your code, but it's faster.
There is no similar macro available in Java. You could write your own methods that delegate to System.out.ṕrintln and the likes, but it would probably be unnecessary work for very little gains.
Think of it this way, typing out those words will make your fingers nimbler.
Related
This question already has answers here:
Java : parse java source code, extract methods
(2 answers)
Closed 1 year ago.
I have tried to develop a regex that captures a method and its body (The modifier is not important), but I could not develop a solid solution. The regex that I came up with so far is this: \\b\\w*\\s*\\w*\\s*\\(.*?\\)\\s*\\{([^}]+)\\}
It does not capture the methods correctly because it does not consider matching balanced Curley braces. Thus, sometimes it captures part of the method and not all. What am I doing wrong or what could I do to improve the solution that can capture the whole method!
You can't do this. It's impossible.
The 'regular' in 'Regular Expression' refers to a certain subset of grammars; the so-called 'Regular Grammars'.
Here's the thing:
Non-Regular Grammars cannot be parsed with regular expressions.
Java (the language) is Non-Regular.
Thus, you can't use regular expressions for this, QED.
So, how do you parse java?
There are many ways; so far, java is still so-called LL(k) parseable, which means that just about every 'parser/grammar' library out there will be capable of parsing java code, and many such libraries ship with a java grammar as an example. These usually aren't quite perfect, but pretty good.
A basic web search gets you many options. Alternatively, javac is free (but GPL, you'd have to GPL anything you build with it), and ecj (the parser that powers eclipse, amongst other things) is open source with a more permissive license. It's also faster. It's also far harder to use, so there's that.
These are fairly complex tools. However, java is a very complex language (much programming languages are). Parsing them is decidedly non-trivial.
Before you think: Geez, surely it can't be this hard, consider:
public void test {
{}
String x = "{";
}
Which is legal java.
Or:
public void test() {
// method body
\u007D
That really is legal java, that \u007D thing closes it. Of course...
public void test() {
//{} \u007D
}
Here the \u thing doesn't. It is a real closing brace, but, that is in a comment.
Another one to consider:
public void test() {
class Foo {
String y = """
}
""";
}
}
Hopefully, considering the above, you realize you stand absolutely no chance whatsoever unless you use a parser that knows about the entire language spec.
This question already has answers here:
What Are The Benefits Of Scala? [closed]
(5 answers)
Java 8 and Scala [closed]
(8 answers)
Closed 9 years ago.
I am reading about Scala here and there but I could not understand what would a Java developer gain from jumping on Scala.
I think it is something to do with functional programming.
Could someone please give me a concrete example of something I can not do in Java and going to Scala would save me?
This is not intented to be a critique on Java or something similar.I only need to understand the usage of Scala
I'm also jumping from Java's world, the first thing that I think will save you is that Scala has a lot of compiler magic that helps you to keep your code simple and clean.
For example, the following is how Scala's case class will help you, we could define a class using this:
case class Student(name: String, height: Double, weight: Double)
instead of this:
class Student {
public final String name;
public final String height;
public final String weight;
public Student(String name, double height, double weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
}
Yes, that is all, you don't need write constructor yourself, and you have all those equals, hasCode, toString method for free.
It may looks like not a big deal in this simple case, but Scala really make you to model things a lot easier and quicker in OO, even if you are not using functional programming construct.
Also, high-order function and other functional programming construct will also give you powerful tools to solve your problem in Scala.
Update
OK, the following is a example of how functional programming will make your code more easier to understand and clean.
Functional programming is a large topic, but I found that even I'm from Java's world and does not understand what is monad or typeclass or whatever, Scala's functional programming construct is still help me to solve problem more easily and more expressive.
There are many times we need to iterate over a collection and do something to the elements in the collection, depends on a condition to decide what to do.
For a simple example, if we want to iterate over a List in java, and delete all file that size are zero. What we will do in Java maybe looks like the following:
List<File> files = getFiles()
for (File file: files) {
if (file.size() == 0) {
file.delete();
}
}
It's very easy and concise, isn't it? But with functional programming construct in Scala, we could do the following:
val files = getFiles()
val emptyFiles = files.filter(_.size == 0)
emptyFiles.foreach(_.delete())
As you can see, it has less code than the Java's version, and out intention is even clear -- we want filter out all files that size is 0, and for all of it, call File.delete() on it.
It may looks weird at first, but once you get used to it and use it in right way, it will make your code a lot easier to read.
The technique is possible in Java (Function Java), but in the end it will looks like the following code:
list.filter(new Predicate<File>() {
public boolean predicate(File f) {
return f.size() == 0;
}
})
Which I'll just stick to the origin for-loop version, IMHO.
To get you started, this article by Graham Lea lists many ways that Scala can boost your productivity:
A New Java Library for Amazing Productivity.
It begins with:
a broad and powerful collections framework
collection methods that greatly reduce boilerplate
immutable collections that don’t have mutation methods (unlike java.util classes where e.g. List.add() throws an exception if the list is immutable)
an awesome switch-like function that doesn’t just match numbers, enums, chars and strings, but can succinctly match all kinds of patterns in lots of different classes, even in your own classes
an annotation that automatically writes meaningful equals, hashCode and toString methods for classes whose fields don’t change (without using reflection)
...
and the list goes on.
To be specific on your question:
in scala you can pattern match
scala has higher order functions (which is not the same as java8 lambdas)
anonymous function literals
strong type inference
lazy evaluation
variance annotation
higher kinded types
mixin behavior with traits (stackable composition)
implicit definition and conversion
xml literals
REPL
I could go on but I urge you to read at least some documentation.
For instance you can start here
Functional programming is the most brief and accurate statement. This and the shorter more expressive code that scala promotes translates to higher productivity.
Scala is also more Conscisce
There are also several other examples of this.
I'm trying to create a kind of "shorthand" syntax for Java that replaces verbose keywords with less verbose ones, so that I can write Java code with fewer keystrokes. Is there any way to replace keywords such as "public" and "static" with abbreviations of those keywords, and then translate that to "normal" Java code?
//would it be possible to convert this to "normal" Java code?
pu cl ModifiedSyntaxExample{
pu st void main(){
System.out.println("Hello World!")
}
}
This would be equivalent to:
//would it be possible to convert this to "normal" Java code?
public class ModifiedSyntaxExample{
public static void main(){
System.out.println("Hello World!")
}
}
The first version is less verbose (and therefore easier to type), because "public" and "class" are replaced with the abbreviations "pu" and "st".
If you are using any IDE than yes, its possible. For example in eclipse you have one code snippets which you can configure in such a way that, you will make your code less verbose. I hope I have understood your question correctly.
for ex - sysout will print System.out.println(); for you.
This question already has answers here:
What is a good use case for static import of methods?
(16 answers)
Closed 2 years ago.
I declare some constant variables in my SQLiteOpenHelper class:
public static final String USERNAME = "user_name";
public static final String PASSWORD = "password";
In an Activity where I create SQL queries, I import these fields:
import com.mygame.ui.login.LoginInfoSQLiteOpenHelper.*;
Is this a good practice?
Or the traditional way of referring to constants better?
LoginInfoSQLiteOpen.USERNAME
If you look at someone's code and see a field like
foo.do(baz, USERNAME);
wut(!), where did that var come from ?
search, grep, where is it declared ?
Using it as ClassName.FIELD makes things much clearer and cleaner.
You avoid confusion, and sometimes it makes more sense to have a proper classname that denotes the field, than a field that came out of nowhere.
well, not everyone uses an IDE, and not everyone reads code through an IDE(maybe through a repository on the web), and even some consider VIM an IDE, and I do use vim a lot(although I don't think of it as an IDE).
So, it's not about what an IDE can or can't do, but more of what code reading is about. Code reading, code quality, expressing ideas in your programming language of choice, in a way through abstractions that make sense and tie well together.
A few years late to the party... but I feel it is worth providing the opposite point of view. There is a reason why Java was designed to have static field imports, and the reason is to hide how the class is implemented to users of the class. This is an important design principle for outwardly facing code. I would agree with c00kiemon5ter take on it, however, there might be situations in which it is worthwhile.
More info on static field importing can be found here: https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
I recommend the second method, only importing classes not fields. So prefixing your constants with the owning class, like LoginInfoSQLiteOpen.USERNAME. It can become highly redundant, but it is much more readable and maintainable in the long run.
I am a TA for a programming class. There is one assignment in which the students have to write Scala. I am not proficient enough in Scala to read it quickly to verify that the program works or capable of quickly writing a script in Scala to run test inputs.
However, I am very capable in Java. I need some advice on a simple way to grade Scala assignments using my knowledge of Java. Is there a way to load in a Scala file into Java so I could have some simple Java methods to run test inputs for their programs? I am aware of the fact that they both compile to Java byte code, so I figure this should be possible.
Scala generates class files. Scala class files can be run with java, only requiring the scala-library.jar to be on the class path. The entry point on Scala programs appears to Java as a static main method on a class, just like in Java. The difference is that, in a Scala program, that main method is a method declared on an object. For example:
Java:
public class Test {
public static void main(String[] args) {
}
}
Scala:
object Test {
def main(args: Array[String]) {
// or:
// def main(args: Array[String]): Unit = {
}
}
The idea of testing by giving unit tests is interesting, but it will probably force non-idiomatic Scala code. And, in some rare cases, might even prevent the solution to be written entirely in Scala.
So I think it is better to just specify command line arguments, input (maybe stdin), and output (stdout). You can easily run it with either scala Test parms, or java -cp /path/to/scala-library.jar Test parms.
Testing input on individual functions might be a lot harder, though, as they may require Scala classes as input, and some of them can be a bit tough to initialize from Java. If you go that route, you'll probably have to ask many more questions to address specific needs.
One alternative, perhaps, is using Scala expressions from the command line. For example, say you have this code:
object Sum {
def apply(xs: Seq[Int]) = xs reduceLeft (_ + _)
}
It could be tested as easily as this:
dcs#ayanami:~/tmp$ scalac Sum.scala
dcs#ayanami:~/tmp$ scala -cp . -e 'println(Sum.apply(Seq(1, 2, 3)))'
6
To do the same from Java, you'd write code like this:
import scala.collection.Seq$;
public class JavaTest {
static public void main(String[] args) {
System.out.println(Sum.apply(Seq$.MODULE$.apply(scala.Predef.wrapIntArray(new int[] {1, 2, 3}))));
}
}
When you put the .class files generated by the student's code into your classpath, you can simply call the methods which your students developed. With a good Java IDE, you will even have code completion.
Rephrase the question: Assume you have a Java library that you need to test. But you only have the class files, not the source code. How do you do it? - Now, it's exactly the same case with Scala. In some cases, you will need to access strange static variables (such as $MODULE), but that should not be a hindrance. tobym has pointed you in the right direction with his answer.
But seriously, what can be the didactic value for the students? You will only be able to tell them whether or not their programs do the right thing, but you cannot point out to them exactly what mistake they made and how to correct it. They will already know by themselves whether or not their programs are correct. When they made errors, just telling them that they made something wrong won't help them at all. You need to show them exactly where the mistake was made in the code, and how to fix it. This is the only way you can help them learn.
If it is only one assignment and not more, maybe you can find a better way. Maybe you can invite another student who is proficient in Scala to help you out with this. Or maybe you can show some of the erroneous programs to the whole class and initiate a discussion amongst the students, in which they will find out themselves what went wrong and how to correct it. Talking about code in this way can help them a lot, and, if done right, can be a valuable lesson. Because this reflects what they will do later in business life. There won't be a prof telling them how to correct their errors. Instead, they will have to figure it out together with their coworkers. So maybe you can turn this lack of knowledge on your part into an opportunity for your students.
You can compile Scala into a .class file (e.g. "scalac ./foo.scala") and run methods from your Java grading program.
This might be useful reference: How do you call Scala objects from Java?
Well, you could write unit tests (with JUnit, for instance) before the assignment and have the students write the programs to conform to the tests.
Or you could decompile scala to java (with JD-gui, for instance).
But to be fair, if the students are only going to use scala for this one specific assignment, chances are that they are mostly going to translate directly from java to scala, intead of writing idiomatic scala. In that case I'm sure you will be able to understand scala code very easily as it will look almost exactly like java...
You can run
scalac SomeProgram.scala
scala SomeProgram input1
a lot of time during the time it would take to write some java that triggers scala compile and running of the bytecode generated