Aditya Yada Aditya Yada - 1 year ago 42
Java Question

package statement not working

package com;

class Account {

public double balance;

public Account(double initBalance) {
balance = initBalance;

Account.class file is generated but it in same folder. File sub folder named 'com' is not created.
Actually I tried to compile directly . Now I can see its totally wrong to compile a java file folder without specifying root directory . ( -d . )

Answer Source

If you are compiling your code from command line, then you can use the following command to automatically create the folder corresponding to your packages: -

javac -d .

This will create a folder com in the current folder, where your is placed, and move the class file automatically to that folder.

Note that, packages are there for your class files. You can place your .java file anywhere. But in addition, your corresponding .class file should be inside a folder corresponding to your package in your .java file.

For e.g, see the below directory structure: -

root --+ 
       +-- com --Account.class  (com is the package folder)

So, the fully qualified name of your Account class becomes - com.Account.

Then in order for your Account class to be found by other class, set the classpath till the com folder ( Note: - Don't include the com folder in classpath).