import static java.lang.System.out;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class ShadowingByImporting
{
public static void main(String[] args)throws FileNotFoundException
{
out.println("Calling println() in java.lang.System.out");
PrintWriter pw=new PrintWriter("log.txt");
writeInfo(pw);
pw.flush();
pw.close();
}
public static void writeInfo(PrintWriter out)
{
out.println("Calling pritnln() in the parameter out");
System.out.println("Calling println() in java.lang.System.out Example");
}
}
The above program is given in Khalid Mugal's SCJP Guide,according to him by the principle of shadowing in static import the second println method in writeInfo. Method will execute twice, but when I run this following dissimilar output came.
Please somebody explain what's the actual concept.
Calling println() in java.lang.System.out
Calling println() in java.lang.System.out Example
This has nothing to do with static imports in general,
but rather with the fact that the parameter out of writeInfo is hiding the outer definition of out which in this case happens to be a static import.
This hiding is also possible when you have
public class ShadowingByImporting
{
PrintWriter out = ...;
public static void main(String[] args)throws FileNotFoundException
{
In function writeInfo, the out is a local variable, while System.out is fully-qualified, representing the standard output stream.
static import is generally used to import static public object into your scope, like System.out in this case. So you can use out directly without the fully qualified name ClassName.ObjectName, System.out in this case.
Related
I'm currently self studying Java, and am not sure with this "import" thing. It adds classes(not sure), and has methods that would serve a different function relative on the type of class I declare from the "import"ed thing.
I'm curious if import is frequently used for work, or is this relative to the user if he/she would want to use import or not.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner ThisObject = new Scanner(System.in);
}
}
Java import is a compile time feature that allows you to omit the package name when programming. There is no byte-code import, the compiler will replace
Scanner ThisObject = new Scanner(System.in);
with
java.util.Scanner ThisObject = new java.util.Scanner(System.in);
As for how common it is, I would say extremely. However, there is another form of import called static import which allows you to bring static methods and fields from another class into your current namespace. static import is not very common. Finally, Java variable names start with a lower case letter (by convention).
import static java.lang.System.in;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner thisObject = new Scanner(in); // System.in through static import
}
}
This question already has answers here:
how to write content in a Specific position in a File
(5 answers)
Closed 7 years ago.
I need to add this is a class or this is a method in a text/java file before class name or method name (line no is available through japa).
I have tried all possible cases I can, try to edit text/Java file with file reader/writer (but it always append at the end ,and want above class/method name), pmd, japa (can read but can't find option to edit) and random access files interface (can edit too but it don't append instead overrides character).
Nothing has helped so far, is there any way I can achieve this?
For example, the original source code:
import java.lang.*;
class test1{
public static void main(String[] args) {
System.out.println("hello world");
}
}
after
import java.lang.*;
/*this is a class*/
class test1{
/*this is a method*/
public static void main(String[] args) {
System.out.println("hello world");
}
}
You can use JavaParser and implement your own ModifierVisitorAdapter. Find below a small snippet you can start with.
import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.Node;
import japa.parser.ast.body.ClassOrInterfaceDeclaration;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.comments.BlockComment;
import japa.parser.ast.visitor.ModifierVisitorAdapter;
import java.io.File;
import java.io.IOException;
public class ModifierVisitorAdapterDemo {
public static void main(String[] args) throws IOException, ParseException {
File sourceFile = new File("Test.java");
CompilationUnit cu = JavaParser.parse(sourceFile);
cu.accept(new ModifierVisitor(), null);
// instead of printing it to stdout you can write it to a file
System.out.println("// enriched cource");
System.out.println(cu.toString());
// to save it into the original file
// this will overwrite the input file
Files.write(sourceFile.toPath(),
cu.toString().getBytes(Charset.defaultCharset()),
StandardOpenOption.TRUNCATE_EXISTING
);
}
private static class ModifierVisitor extends ModifierVisitorAdapter {
#Override
public Node visit(ClassOrInterfaceDeclaration n, Object arg) {
if (!n.isInterface()) {
n.setComment(new BlockComment(" this is a class "));
}
return super.visit(n, arg);
}
#Override
public Node visit(MethodDeclaration n, Object arg) {
n.setComment(new BlockComment(" this is a method "));
return super.visit(n, arg);
}
}
}
Assuming following input file Test.java
import java.lang.System;
class Test {
static class Foo {
}
static interface IFace {
}
public static void main(String... args) {
}
}
the output will be
// enriched cource
import java.lang.System;
/* this is a class */
class Test {
/* this is a class */
static class Foo {
}
static interface IFace {
}
/* this is a method */
public static void main(String... args) {
}
}
You can definitely use JavaParser to do that. You can visit the tree finding all classes and methods (you can use a visitor to do that or just start from the root of the file (CompilationUnit) and call recursively node.getChildrenNodes(). When you find an instance of ClassOrInterfaceDeclaration or MethodDeclaration you just add a comment using the method node.setComment()
Now you can dump the file (going from the AST back to source code) using the DumpVisitor or just call compilationUnit.toString()
Disclaimer: I am a JavaParser contributor
Feed free to ask other questions here or open an issue on GitHub. The project is currently maintained at https://github.com/javaparser/javaparser
I thought I reasonably understood the use of packages but am experiencing an ostensibly trivial issue when attempting to use a method from an imported package.
I have three files in the following directory structure:
Tester.java
approach1\Approach.java
approach2\Approach.java
Their code is as follows:
Tester.java
import approach1.Approach;
public class Tester {
public static void main(String[] args)
{
approach1.Approach.sharedMethod("TEXT");
sharedMethod("TEXT");
}
}
approach1\Approach.java
package approach1;
public class Approach {
public static void sharedMethod(String approachText)
{
System.out.println("Approach Text: " + approachText);
}
}
approach2\Approach.java
package approach2;
public class Approach {
public static void sharedMethod(String approachText) { }
}
As you can likely guess, I'm trying to elicit different responses from the different approaches based on what package/class is imported. The problem I encounter is within Tester.java. The first, explicit line works fine whereas the second, imported line (sharedMethod("TEXT")) throws an error of "The method sharedMethod(String) is undefined for the type Tester". I don't understand as I have imported one of the packages, so the method should be visible.
Any clarification would be appreicated as I'm a Java newb. Thanks!
You could import your static method shareMethod like this
import static approach1.Approach.sharedMethod;
the standard kind of imports that you have used only import the classes - so everything within a class must be referenced using the class name. just use:
Approach.sharedMethod()
and now the compiler will be able to know which method to use all depending on which Approach class you have imported at the top.
Just to clarify:
import approach1.Approach;
public class Tester {
public static void main(String[] args)
{
Approach.sharedMethod("TEXT");
}
}
is different from
import approach2.Approach;
public class Tester {
public static void main(String[] args)
{
Approach.sharedMethod("TEXT");
}
}
You should only specify the class name and leave it to the package import statement at the top to determine which package to find the class/methods from.
You only need to explicitly mention the package in the main program body if there is a conflict in names or if you have not imported anything.
I'm very new to java (about 1 week), and i'm stuck on a bit of code. I've looked everywhere, but nothing works. I'm trying to send a string from a MainProgram class to a FileWriter class.
MainProgram:
import java.util.*;
public class MainProgram {
public static void main(String[] args){
static answer;
Scanner Input = new Scanner(System.in);
System.out.println("Enter something so I can write it to a file");
String answer = Input.nextLine();
System.out.print("You said ");
System.out.print(answer);
}
}
FileWriter:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class FileWriter{
public static void SaveList() throws FileNotFoundException{
PrintWriter writer = new PrintWriter("OMGIMAFILELOLZ.txt");
writer.println(answer);
writer.close();
}
}
No matter what I do, I can't pass the answer string onto the FIleWriter class. Please help!
BTW Please don't make the answer too complex. I just came from QBASIC, and i'm only 12, so keep it simple please!
In this line static answer; you have not mentioned the
data type of answer.
main is already a static block,so you can not declare static
variables inside main method
declare answer in the class level like this public static String
answer;
class level syntax
public class MainProgram {
public static String answer;//class level declaration
public static void main(String args[])
{
//some codes
}
static answer;
First of all data type is missing for that.
And you cannot declare fields in methods.
That should be
static String answer;
public static void main(String[] args) {
// answer = Input.nextLine();
Then in FileWriter class,
writer.println(MainProgram.answer);
For my programming class, I was told to make a program that uses recursion. I was confused and went to see my friend who was already in the class and he showed me this program. I thought recursion had to use things like r1(x-1), etc. Is it actually recursive? If it's not, how do you make it recursive?
import java.util.*;
import java.io.*;
class ReverseFile
{
private static Scanner infile;
public static void main(String[] args) throws IOException
{
infile= new Scanner(new File("hw_1.txt"));
r1();
}
public static void r1()
{
String s;
if (infile.hasNextLine())
{
s = infile.nextLine();
r1();
System.out.println(s);
}
}
}
It is recursive as r1 calls itself. The fact that no arguments are passed to r1 doesn't matter.