0
does system.out.print work in this way ?
is it same as System.out.print class A // system { static B o=new B(); } class B //printstream { void display(String s) { System.out.print(s); } } class PrintK { public static void main(String a[]) { A.o.display("somnath"); } }
7 Answers
+ 4
Oh, sorry I couldn't tell.
System is a class that you are calling.
out is a member in that class that you are accessing, of type printstream.
The class printstream has the methods print or println, which are what you are calling.
Which is why you do System.out.println();
out would be static so you don't need to create an instance of the class.
So yes it works just like how you wrote it in the question.
You actually can just do: out.print();
If you do this:
import static java.lang.System.out;
Now you can just write:
out.println("My stuff");
So, System is in the java.lang library.
Example:
import static java.lang.System.out;
public class Program
{
public static void main(String[] args) {
out.print("test");
}
}
Output:
test
+ 3
Yes.
Why not just do something like this anyway?
class Program{
public static void main(String[] args){
display("lel");
}
private static void display(String msg){
System.out.println(msg);
}
}
+ 2
Just made a method same as your display(String) but in the class with the main method. Yours will work though if you need something like that.
+ 2
If you just had to write print() that would imply it is a default method already defined for you.
I don't think Java supports global functions so that's never valid.
Also, print() is actually not useful for the user for real projects that have UI. It is only good for debugging at that point. So, I can't see a reason to have that method in every project.
Here's a quote from a quote from stack overflow:
"Java has no functions. Object-oriented programming supersedes functional and procedural styles. Mixing the two styles just leads to confusion and dilutes the purity of an object-oriented language. Anything you can do with a function you can do just as well by defining a class and creating methods for that class.
It's not to say that functions and procedures are inherently wrong. But given classes and methods, we're now down to only one way to express a given task. By eliminating functions, your job as a programmer is immensely simplified: you work on with classes and their methods."
+ 1
actually...i wanted to know why we write System.out.print like this....why not System.print Or out.print?
0
what r u doing ?
0
but why it is so complex...what is the need of system class...it could be simple ...we can directly call print method by creating printStream class object Or PrintStream.print...