Skip to main content

Java source file structure


Java source file structure: 
• A java program can contain any no. Of classes but at mot one class can be declared as public. “If there is a public class the name of the program and name of the public class must be matched otherwise we will get the compile-time error”.
• If there is no public class then any name we give for the java source file.
Example:
Case1: • If there is no public class then we can use any name for java source file there are no restrictions.
Example: 
 A.java
 B.java
 C.java
 navneet.java
case2:
If class B declared as public then the name of the program should be B.java otherwise
we will get a compile-time error saying “class B is public, should be declared in a file
named B.java”.
Cae3:
If both B and C classes are declared as public and name of the file is B.java then we will
get a compile-time error saying “class C is public, should be declared in a file named
C.java”.
It is highly recommended to take only one class for the source file and the name of the program
(file) must be the same as the class name. This approach improves the readability and
understandability of the code.
Example:
      class A
            {
                 public static void main(String args[])
                        {
                              System.out.println("A class main method is executed");
                        }
              }
     class B
         {
                   public static void main(String args[])
                        {
                                 System.out.println("B class main method is executed");
                         }
          }
      class C
             {
                     public static void main(String args[])
                            {
                                  System.out.println("C class main method is executed");
                            }
             }
   class D
     {
      }
D:\Java>java A
A class main method is executed
D:\Java>java B
B class main method is executed
D:\Java>java C
C class main method is executed
D:\Java>java D
Exception in thread "main" java.lang.NoSuchMethodError: main
D:\Java>java Navneet
Exception in thread "main" java.lang.NoClassDefFoundError: Navneet
• We can compile a java program but not java class in that program for every class one
dot class file will be created.
• We can run a java class but not java source file whenever we are trying to run a class the
the corresponding class main method will be executed.
• If the class won’t contain the main method then we will get runtime exception saying
“NoSuchMethodError: main”.
• If we are trying to execute a java class and if the corresponding .class file is not available
then we will get runtime execution saying “NoClassDefFoundError: Navneet”.
Import statement:
      class Test{
                 public static void main(String args[]){
                ArrayList l=new ArrayList();
             }
       }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:3: cannot find symbol
symbol: class ArrayList
location: class Test
ArrayList l=new ArrayList();
Test.java:3: cannot find symbol
symbol: class ArrayList
location: class Test
ArrayList l=new ArrayList();
We can resolve this problem by using a fully qualified name “java.util.ArrayList l=new
java.util.ArrayList();”. But the problem with using a fully qualified name every time is it
increases the length of the code and reduces readability.
We can resolve this problem by using import statements.
Example:
import java.util.ArrayList;
     class Test
         {
              public static void main(String args[]){
              ArrayList l=new ArrayList();
            }
       }
Output:
D:\Java>javac Test.java
Hence whenever we are using import statement it is not required to use fully qualified
names we can use short names directly. This approach decreases the length of the code and
improves readability.
Case 1: Types of Import Statements:
There are 2 types of import statements.
1) Explicit class import
2) Implicit class import.
Explicit class import:
Example: Import java.util.ArrayList
This type of import is highly recommended to use because it improves the readability of the
code.
Best suitable for Hi-Tech city where readability is important.
Implicit class import:
Example: import java.util.*;
It is never recommended to use because it reduces the readability of the code.
Bet suitable for Ameerpet where typing is important.
Case2:
Which of the following import statements are valid?
Case3:
• consider the following code.
class MyArrayList extends java.util.ArrayList
   {
   }
The code compiles fine even though we are not using import statements because of we
used a fully qualified name.
Whenever we are using the fully qualified name it is not required to use an import statement.
Similarly, whenever we are using import statements it is not required to use a fully qualified

name.
Case4:
Example:
import java.util.*;
import java.sql.*;
      class Test
          {
              public static void main(String args[])
                 {
                      Date d=new Date();
                  }
         }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:7: reference to Date is ambiguous, both class java.sql.Date in java.sql and class
java.util.Date in java.util match
Date d=new Date();
Note: Even in the List case also we may get the same ambiguity problem because it is available
in both UTIL and AWT packages.
Case5:
• While resolving class names compiler will always give the importance in the following
order.
1) Explicit class import
2) Classes present in the current working directory.
3) Implicit class import.
Example:
import java.util.Date;
import java.sql.*;
    class Test
      {
           public static void main(String args[])
              {
                     Date d=new Date();
               }
     }
The code compiles fine and in this case util package Date will be considered.
Case6:
Whenever we are importing a package all classes and interfaces present in that package
are by default available but not sub package classes.
Example:

To use pattern class in our program directly which import statement is required?
 Case7:
• In any java program, the following 2 packages are not required to import because of these
are available by default to every java program.
1. java.lang package
2. default package(current working directory)
Case8:
“Import statement is a totally compile-time concept” if more no of imports are there then
more will be the compile time but there is “no change in execution time”.
Difference between C language #include and java language import.
In the case of C language #include, all the header files will be loaded at the time of
include statement hence it follows static loading.
But in java import statement no “.class” will be loaded at the time of import statements
in the next lines of the code whenever we are using a particular class then only
corresponding “.class” file will be loaded. Hence it follows “dynamic loading” or “London –demand” or “load-on-fly”.
Static import:
This concept introduced in 1.5 versions. According to sun static import improves
readability of the code but according to worldwide programming exports (like us), static imports create confusion and reduces the readability of the code. Hence if there is no
specific requirements never recommended using a static import.
1.5 versions new features
1) For-Each
2) Var-arg
3) Queue
4) Generics
5) Autoboxing and Auto unboxing
6) Co-variant return types
7) Annotations
8) Enum
9) Static import
10) String builder
• Usually, we can access static members by using the class name but whenever we are using
static import is not required to use the class name we can access directly.
Without static import:
class Test
    {
        public static void main(String args[])
            {
                 System.out.println(Math.sqrt(4));
                 System.out.println(Math.max(10,20));
                System.out.println(Math.random());
           }         
    }
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.841306154315576
With static import:
import static java.lang.Math.sqrt;
import static java.lang.Math.*;
      class Test
        {
              public static void main(String args[])
                   {
                        System.out.println(sqrt(4));
                        System.out.println(max(10,20));
                        System.out.println(random());
                 }
       }
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.4302853847363891
Explain about System.out.println statement?
Example 1 and example 2:
Example 3:
import static java.lang.System.out;
         class Test
          {
               public static void main(String args[])
                 {
                        out.println("hello");
                       out.println("hi");
                }
        }
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
hi
Example 4:
import static java.lang.Integer.*;
import static java.lang.Byte.*;
             class Test
              {
                   public static void main(String args[]){
                  System.out.println(MAX_VALUE);
             }
           }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:6: reference to MAX_VALUE is ambiguous, both variable MAX_VALUE in
java.lang.Integer and variable MAX_VALUE in java.lang.Byte match
System.out.println(MAX_VALUE);
Note: Two packages contain a class or interface with the same is very rare hence ambiguity
problem is very rare in normal import.
But 2 classes or interfaces can contain a method or variable with the same name is very
common hence ambiguity problem is also very common in static import.
While resolving static members compiler will give the precedence in the following order.
1. Current class static members
2. Explicit static import
3. implicit static import.
Example:
• If we comet line one then we will get Integer class MAX_VALUE 2147483647.
• If we comet lines one and two then Byte class MAX_VALUE will be considered 127.
Which of the following import statements are valid?
Diagram: 
Usage of static import reduces readability and creates confusion hence if there is no
specific requirements never recommended using static import.
What is the difference between general import and static import?
We can use normal imports to import classes and interfaces of a package. whenever we
are using normal import we can access class and interfaces directly by their short name
it is not required to use fully qualified names.
We can use static import to import static members of a particular class. whenever we
are using static import it is not required to use the class name we can access static members
directly.
Package statement:
It is an encapsulation mechanism to group related classes and interfaces into a single
module.
The main objectives of the packages are:
To resolve name confects.
To improve the modularity of the application.
To provide security.
There is one universally accepted naming conversion for packages that are to use an internet

the domain name in reverse. 
Example:
How to compile a package program:
Example:
package com.durgajobs.itjobs;
    class HydJobs
      {
           public static void main(String args[]){
           System.out.println("package demo");
         }
     }
• Javac HydJobs.java generated class file will be placed in current working directory.
Diagram:  
· Javac –d. HydJobs.java
· -d means destination to place generated class files “.” means current working directory.
· Generated class files will be placed into a corresponding package structure.
Diagram:
· If the specified package structure is not already available then this command itself will
  create the required package structure.
· As the destination, we can use any valid directory.
If the specified destination is not available then we will get a compile-time error.
Example:
D:\Java>javac -d c: HydJobs.java
Diagram:
· If the specified destination is not available then we will get a compile-time error.
Example:
D:\Java>javac -d z: HydJobs.java
· If Z: is not available then we will get a compile-time error.
How to execute a package program:
D:\Java>java com.durgajobs.itjobs.HydJobs
· At the time of execution compulsory, we should provide a fully qualified name.
Conclusion 1:
· In any java program, there should be at most one package statement that is if we are
taking more than one package statement we will get a compile-time error.
Example:
package pack1;
package pack2;
              class A
                    {
                    }
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack2;
Conclusion 2:
· In any java program, the 1st non-cement statement should be package statement [if it is
available] otherwise we will get a compile-time error.
Example:
import java.util.*;
package pack1;
      class A
            {
             }
Output:
Compile-time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack1;
Java source file structure:
· All the following are valid java programs.
Note: An empty source file is a valid java program.

Comments

Post a Comment

Popular posts from this blog

Core Java

Content 1 - Language fundamental   Identifier Reserved words Data types Literals Arrays Types of variables Var arg method Main method Java coding standards 2 -  Declaration and Access Modifiers Java source file structure Class modifiers Member modifiers Interfaces 3 - Exception Handling Introduction Runtime stack mechanism Default exception handling in java Exception hierarchy Customized exception handling by try-catch  Control flow in try-catch Methods to print exception information Try with multiple catch blocks Finally Difference between final, finally, finalize Control flow in try-catch-finally Control flow in nested try-catch-finally Various possible combinations of try-catch-finally throw keyword throws keyword Exception handling keywords summary Various possible compile-time errors in exception handling Customized exceptions Top-10 exceptions  4 - String Concept of String Immutable String String Comparison String Conca