Should I import a math library, and if so how? - java

So I want to print out the math functions, "PI" and "E."
Here is how I'm trying to do it:
System.out.println(Math.PI);
System.out.println(Math.E);
I think I have to import the math library.

E and PI are not functions, they're static fields (data members). That code will output their values correctly. You don't have to import anything, the Math class is in the java.lang package, which is imported by default. (It's the only package imported by default, I believe.)

You don't have to import anything here. The java.lang.Math class should already be available as java.lang package is imported by default

This works just fine:
/**
<P>{#code java MathXmpl}</P>
**/
public class MathXmpl {
public static final void main(String[] igno_red) {
System.out.println(Math.PI);
System.out.println(Math.E);
}
}
Output:
[C:\java_code\]java MathXmpl
3.141592653589793
2.718281828459045
Since Math is in the java.lang package, it does not need to be imported. java.lang is the "default package" and everything in it is already implicitly imported for you.

Related

Is their any class/classes inside java root package

The below code has no compilation error:-
import java.*;
class Test{
public static void main(String[] args){
}
}
My question is does the package named java only includes sub-packages or it also includes any class/classes. If yes then which class(s). If no then why we are able to import it.
There are no class directly under java. All the JDK's classes are under subpackages.
Having an empty package (or a package with no classeses in it) is perfectly legal in Java. You can import all the classes in it (which is no classes) with the * syntax. This isn't wrong - it's just pointless.

what is the difference between user defined package and system defined java package with respect to accessing static content

Q) With respect to accessing static content, what is the difference
between user defined package and java system package (say java.lang
etc)
I'm preparing for ocjp6. using 1.6.26 java version
my java program has a package named "pack" in PackageTest.java
package pack;
public class PackageTest {
public static final int i=20;
}
}
javac -d . PackageTest.java
created PackageTest.class file in pack folder
now accessing static contents of PackageTest class from another java
program (TestStaticContents.java) as below
import pack.PackageTest.*;
// here importing all contents of PackageTest class
class TestStaticContents {
public static void main(String[] args){
System.out.println("normal import, accessing i value with class name: "+PackageTest.i);
}
}
javac TestStaticContent.java
displaying Compilation Error:
TestStaticContents.java: cannot access PackageTest bad class file: .\PackageTest.java
If i try accessing static contents of Math class from my java program
its not displaying any compilation error i.e
import java.lang.Math.*;
// here importing all contents of Math class
class TestMathStaticContents {
public static void main(String[] args){
System.out.println("normal import, accessing pi value with class name : "+ Math.PI);
}
}
javac TestMathStaticContents.java
No Compilation Error, and PI value is printed as expected.
Why this behavior is different compared to User defined package?
I believe I understand your problem now. You've placed both PackageTest.java and TestStaticComponents.java in the same package, pack. Two classes that share the same package cannot explicitly import one another.
You've hinted at this yourself by providing TestStaticComponents.java with a package-private class identifier.
Your import statement works perfectly if both classes reside in different packages.
import java.lang.Math.* attempts to import the nested types from Math, not the static members. You should be using import static:
import static java.lang.Math.PI; //recommended to avoid wildcards
When using imported static members, you do not need to reference the class when using the member: You can use PI instead of Math.PI.
No Compilation Error, and PI value is printed as expected.
This is because java.lang.Math, like all types in the java.lang package, is automatically imported: there's no need to import it. Because of this, Math.PI isn't causing an error like you'd expect.
If you used PI instead of Math.PI, you would have gotten an error, informing you the static member wasn't imported.

How to write an import statement to refer to a java class in a jar?

How can I refer to a Java class in stdlib1.jar when the directory structure is like this? How to write the import statement?
I want to call a method under stdlib1.jar, I have configured it.
The classes are in the default package. According to this answer, it is not possible to import classes from the default package. So, they have to be moved to another package or you have to use reflection.
You call a method from a class and not from a package.
You don't need to specify the jar when you call a method from a class belonging to it. Which matters is your jar is in the classpath
In your screenshot if the lib makes part of the classpath folders, you can import and use classes from it in your code.
Here the classes of your jar use the default package (no package name) which seems weird for a third-party library. Default package is not recommended since it doesn't allow to naturally reference and use the classes of the archive from the client code.
I am not sure you are using the correct version of the jar. Look at that :
http://grepcode.com/snapshot/repo1.maven.org/maven2/com.googlecode.princeton-java-introduction/stdlib/1.0.1
This contains classes in the edu.princeton.cs package :
With package, you could declare this :
For example :
You could create a class like that and use BinaryIn like that:
package main;
import edu.princeton.cs.BinaryIn;
public class MyClass(){
public static void main(String args[]){
BinaryIn in = new BinaryIn();
}
}

Java classes and packages

Hello everybody I am a beginner of Java. I am blocked at this point with the following
program:
import prog.io.Orario;
import prog.io.ConsoleOutputManager;
class primoprogramma{
public static void main(String[] args){
ConsoleOutputManager video=new ConsoleOutputManager();
video.println("ciao");
}
}
That gives me the error:
bad class file: ./prog/io/Orario.class
class file contains wrong class: prog.utili.Orario
Please remove or make sure it appears in the correct subdirectory of the classpath.
I did everything I could tried in those days but nothing works. Here there the class
Orario:
package prog.utili;
public class Orario {
private static char separaratore=';';
}
Thank you for any advice
Your class Orario has the wrong package declaration (package prog.utili; instead of package prog.io;)
The compiler scans your import of prog.io.Orario.
It searches for class Orario in a file Orario.class in directory prog/io.
The class found has the package prog.utili declared which is not the desired one - Error
In java, directorys are the same as package names.
So, a class Orario in the package prog.utili
have to be in a directory prog/utili instead of prog/io

How to use java methods defined in another class/file

I've been working on some problems from Project Euler, and, in the process, have written a lot of useful methods (in Java) that I might like to use in other Java projects. I want to be able to call them in the way that you call a function from java.lang.math, so if I had a method primeFactor() I could call it using MyMathMethods.primeFactor(number). How would I go about this? Would I make some kind of package that I could import? Would I make a superclass that includes all my useful math-y functions and have whatever class I'm working with in a new project extend that? There are probably multiple ways to do this, but I don't know what is best. Thanks in advance.
Mark your utility methods as public static. Package your classes containing those utility methods in a jar. Add/Refer that jar in your project, where you want to use the. Then in your code you can call them in a static way lke : MyUtilityClass.myUtilityMethod();
The best thing for this situation is to work in meaningful packages and make their jar
You can create a package like
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Also on classes
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
You can import them like
import animals.*; OR be more specific import animals.MammalInt;Now you can make the jar file , import it in your project and use its methodYou can eaisly do it by this commandjar cmf MyJar.jar Manifest.txt MyPackage/*.class
For more details about jar creation please see thisAs a side note: Be carefull about visibility of members and functions while packaging itBecause there usage and accessibility matters a lot while we are using them
You could create separate java project with your util classes only and then create jar file and import into any another project.
Simply instantiate the class. Like your example, if you had a class MyMathMethods with the function primeFactor(number) then at other classes, simply instantiate it with something like private MyMathMethods myMathMethods;. Now, to call the function simply do myMathMethods.primeFactor(number); You may need to import its package as well.
False understanding of packages is any class defined within a package is visible to all other classes. Not true from my experience. If you have classes containing utility style methods you want to make available in another class? Simply declare a new instance of the class in the class you need the method in. Like... private MathUtilsClass mathUtilsClass = new MathUtilsClass(): Then any method you want to call from this class uses the new identifier, e.g. mathUtilsClass.greatFunction(); This is stupidly easy and should solve your problem.

Categories