3. Quiz Question: Why only 1 Public Class in JAVA file

แชร์
ฝัง
  • เผยแพร่เมื่อ 18 ม.ค. 2025

ความคิดเห็น • 60

  • @DeepakKumar-yl3ok
    @DeepakKumar-yl3ok 9 หลายเดือนก่อน +9

    But if you are saying that when the filename is equal to the class name, JVM does not need to know about what all classes are present inside the file, it can directly call the class which has the same name as file name, then why is there a need of only 1 public class
    file -> B.java
    two classes -> public class A {}
    public class B {},
    so even though there are two public classes, JVM knows that it would call B java, because that is having the same name as file name

    • @ritikagrawal9768
      @ritikagrawal9768 7 หลายเดือนก่อน +2

      yeah same doubt

    • @vedanshgaur9517
      @vedanshgaur9517 6 หลายเดือนก่อน +2

      Generally other classes should be kept private or protected withing the package for security reasons. Surely you can make every class public but it is not a good practice.

    • @kumarsubrato1658
      @kumarsubrato1658 3 หลายเดือนก่อน

      Hii deepak
      did you clear your doubt if so could you please clear it for me
      like i have the same doubt

    • @ankamma-p5k
      @ankamma-p5k 2 หลายเดือนก่อน

      @@kumarsubrato1658 if class is prefixed with a public jvm invoke that main method directly, if not a public class then might not be available to jvm because of default modifier (java default access modifier is default) in java then default access modifier access within that package outside package not avaiable .

    • @ajaydev8371
      @ajaydev8371 26 วันที่ผ่านมา

      ​@@vedanshgaur9517bro not every class be public in a package there must be only one public class not more than that so your answer in invalid for his question

  • @eshwarsai5027
    @eshwarsai5027 8 หลายเดือนก่อน +2

    one of the finest explanations. Great!

  • @ANSHULGUPTA880
    @ANSHULGUPTA880 ปีที่แล้ว +6

    Still this doesn't clarify why JAVA files with NO main methods are also restricted by same design?

    • @ConceptandCoding
      @ConceptandCoding  ปีที่แล้ว +4

      Couple of reasons only I can think of:
      - doing this restriction, efficiency of compiler might have improved, as it knows public class name and File name would be same.
      - second, it bring some code structure and readability

  • @roushank948
    @roushank948 3 หลายเดือนก่อน +1

    It really doesn't matter where main method is.

  • @CodingJoySoul
    @CodingJoySoul ปีที่แล้ว +2

    Please make videos more frequently.

  • @sushantbasak1647
    @sushantbasak1647 11 หลายเดือนก่อน +1

    Hey Shrayansh, Suppose I have a file name as HelloWorld.java. Inside it I created the HelloWorld1 class.
    I am then using the javac to convert it into HelloWorld1.class.
    After that I can simply call java HelloWorld1 and it is working.
    I am confused as you mentioned that Class name should match with the FileName. Can you please help?

    • @sushantbasak1647
      @sushantbasak1647 11 หลายเดือนก่อน +1

      Ref code -
      import java.io.*;
      class HelloWorld1 {
      public static void main(String[] args) {
      System.out.println("HelloWorld");
      }
      }
      javac HelloWorld.java
      java HelloWorld1

    • @Study-lo6vh
      @Study-lo6vh 11 หลายเดือนก่อน +1

      @@sushantbasak1647 Your public class name should match the file's name.

  • @BJPTamilNaidu
    @BJPTamilNaidu 7 หลายเดือนก่อน +1

    have you ever used main method in real projects?

    • @ConceptandCoding
      @ConceptandCoding  7 หลายเดือนก่อน +1

      yes daily,
      whenever we start the server, spring boot internally invoke SpringApplication class, and main method act as a entry point for that

    • @BJPTamilNaidu
      @BJPTamilNaidu 7 หลายเดือนก่อน +2

      @@ConceptandCoding before spring boot introduced ?

    • @ramdafale
      @ramdafale 7 หลายเดือนก่อน

      @@BJPTamilNaidu Yes. It's in all java project.

  • @mils3318
    @mils3318 10 หลายเดือนก่อน +2

    I would correct you a lil bit for the 2nd point, PUBLIC class name MUST be same as file name (source file), otherwise it will be compilation error.

  • @weirdstrategist
    @weirdstrategist ปีที่แล้ว +9

    hi, i have a main.java and as part of that i have the following code
    public class Main {
    // This class is empty and does not have a main method.
    }
    class Helper {
    public static void main(String[] args) {
    System.out.println("Hello, World!");
    }
    }
    this compiles and creates two classes Main and Helper and if i run helper then i can see the hello world , so seems like main() need not be linked to the public class always.

    • @ulavaashok7381
      @ulavaashok7381 6 หลายเดือนก่อน +3

      If we are in same package then we can access the class within same package and it will execute the main method, But if class is not public then it won't be accessed outside the package, see below classes.
      Note: As per java convention rules and JVM it's best practice to keep main method in public class
      package package1;
      class Hello{
      public static void main(String args[]){
      System.out.println("Hello World");
      }
      }
      package package2;
      import package1.Hello;
      public class Main{
      //Empty class as per you
      }
      class Hi{
      public static void main(String[] args) {
      //calling main method from Hello class, where it will throw error
      //since Hello class is not public
      String[] arr = {"1", "2"};
      Hello.main(arr); // Calling the main method of Hello class
      }
      }
      Where it will throw below compilation error
      Main.java:3: error: Hello is not public in package1; cannot be accessed from outside package
      import package1.Hello;
      ^
      Main.java:14: error: Hello is not public in package1; cannot be accessed from outside package
      Hello.main(arr); // Calling the main method of Hello class

  • @shailjasharma302
    @shailjasharma302 ปีที่แล้ว +2

    Hi, I had a question. If there is only one public class in the program, JVM will know where to find the main method. Why does the name need to be same as that of the class as well?

    • @ConceptandCoding
      @ConceptandCoding  ปีที่แล้ว +1

      There can be 100 of public classes but in one file there can be only 1 public class.
      And that class name should be same as of file name.
      Otherwise if in a single file there are 3 classes how JVM knows which class has the main method

    • @rohithchittibommala2002
      @rohithchittibommala2002 ปีที่แล้ว +2

      ​@@ConceptandCodingbut java doesn't allow multiple public classes in a single file

    • @ConceptandCoding
      @ConceptandCoding  ปีที่แล้ว +1

      right@@rohithchittibommala2002

    • @akashparihar515
      @akashparihar515 11 หลายเดือนก่อน +1

      Shreyansh, i have the same doubt, if we have the only one public class in a file then why the class name should be the same as file?
      As there is only one public class in file jvm can easily identify where to call the main method?

    • @cleanconceptbyshakib
      @cleanconceptbyshakib 5 หลายเดือนก่อน

      @@ConceptandCoding But JVM can compile default class with main method also.So this explanation is not valid.Suppose i declare 1 file and one public class within the file with same name which has main method.But i also able to create another normal class with main method and also i can run the class.

  • @vishwasdhanwani6134
    @vishwasdhanwani6134 ปีที่แล้ว +3

    Hey Shrayansh, I don't think main method must be inside public class as jvm will read .class or bytecode file and jvm will be able to read the main methods.
    To be extra sure my knowledge, I tried with an example
    class MainClass11 {
    public static void main(String[] args) {
    System.out.println("hello vishwas");
    }
    }
    public class NotMainClass11 {
    }
    This compiles & creates 2 classes. And if you run >> java MainClass11 then it will run main method().
    I hope, this was helpful.
    Thanks
    BTW love your content😁😁

    • @ConceptandCoding
      @ConceptandCoding  ปีที่แล้ว +1

      Thanks buddy.
      For this example you have created 2 different files MainClass11 and NotMainClass11.
      Could you pls try putting both the class in the same file and then try.

    • @dhirajrana397
      @dhirajrana397 ปีที่แล้ว

      @@ConceptandCoding I put them in same class, but still it runs:
      public class PublicClass {
      public int p;
      }
      class NonPublicClass {
      public static void main(String[] args) {
      PublicClass publicClass = new PublicClass();
      System.out.println(publicClass.p);
      }
      }

    • @harshitanand7349
      @harshitanand7349 ปีที่แล้ว

      Agreed with Vishwas. I can define main method in non-public class as well.
      Let’s say I have a java file Demo.java. Your ide will automatically write public class Demo{}
      Create a non-public class say Hello inside this Demo file. You can add main method inside this Hello class and it will compile without any error.
      Yes one thing is there. If you compile the file it will create Demo.class file and when you’ll run it the JVM will call the public class main method and not the non-public class main method.

    • @rwordspecialist6734
      @rwordspecialist6734 6 หลายเดือนก่อน

      @@dhirajrana397 bro but if we don't define if it's public or private class then it's considered as public class therefore your second class named 'NONPUBLIC ' is also a public class.
      So the jvm searches for the public class with main function in it correct me if I'm wrong.

    • @ankamma-p5k
      @ankamma-p5k 2 หลายเดือนก่อน

      if you don’t specify any class as public and have multiple classes with main methods in a single .java file, the JVM will not automatically choose a main method to execute. Instead, you need to specify the fully qualified class name when running the program.
      @conceptandCoding

  • @din-do-that
    @din-do-that 2 หลายเดือนก่อน

    don't think to much, it's just mainly to improve the performance for compiler.

  • @chetanm898
    @chetanm898 ปีที่แล้ว +1

    How to become a member ?

    • @ConceptandCoding
      @ConceptandCoding  ปีที่แล้ว +1

      You will find join button at channel home page Chetan.

    • @chetanm898
      @chetanm898 ปีที่แล้ว +1

      @@ConceptandCoding I am not able to see join button next to subscribe I am trying it from mobile

    • @chetanm898
      @chetanm898 ปีที่แล้ว +1

      Please reply

    • @VibrantAmit
      @VibrantAmit ปีที่แล้ว +1

      @@ConceptandCodingI’m also unable to find

    • @Gag乂y
      @Gag乂y 11 หลายเดือนก่อน +1

      There is no join button there

  • @napster5944
    @napster5944 ปีที่แล้ว +1

    I am not able to download all videos from this playlist, i like to have it on my local

    • @ConceptandCoding
      @ConceptandCoding  ปีที่แล้ว +2

      There might be some plugin available, check once.

    • @ANSHULGUPTA880
      @ANSHULGUPTA880 ปีที่แล้ว +1

      bcos its member only...google restrictions

  • @ShubhamRajput23
    @ShubhamRajput23 ปีที่แล้ว +1

    Hi Shreyansh,
    While I can understand that only 1 public class is allowed per file but I defined 2 class in my file both with access modifier as default(package-private) and one of them contained main method. There was no error in the program and it ran successfully. So does that mean JVM has capability to search for main method in multiple default classes if there is no public class defined?

    • @ConceptandCoding
      @ConceptandCoding  ปีที่แล้ว +3

      Generally, In Java, JVM looks for the "public static void main(String[] args)" method to serve as the entry point for a standalone Java application. The main method must be declared within a class, and that class needs to be specified when running the Java program.
      If you have multiple classes in the same file, each with its own main method, But that file name should match with one of the class right, so while running the code, most probably it will pick that class which name is equivalent to file name.

    • @mils3318
      @mils3318 10 หลายเดือนก่อน +3

      @@ConceptandCoding I just tested this claim of yours using Java21 in InteliJ.
      I created a .java file with a certain name and in it defined two default classes with completely different names and without defining a public class (of course the same name as the name source file).
      In both of those classes, inside that source file, I defined classic main methods that print different messages in the console.
      When I started the program, it called and printed in the console the contents of the FIRST main method it encountered defined in that file.
      So, to define the main method, it is not necessary to write it in the public class, it can also be written in the default class. And the program is carried out regularly. Probably the JVM looks ONLY at the exactly defined signature of the main method according to the Java language specification.
      But it is worth noting that it is BEST practice to define public class and inside main method.

  • @DrimeshPendam
    @DrimeshPendam 7 หลายเดือนก่อน +1

    We can create a class with employee and can keep its name to other rather than employee which is same name for class and guess what it still runs but when it runs then jvm create a .class file name with the class name . i.e employee

  • @crackit3974
    @crackit3974 ปีที่แล้ว +2

    Hi bro, I need your advice,
    I am a recent graduate of IIIT. I worked as an 6 month SDE Intern at Amazon .
    I received an inclined vote but due to headcount, did not receive offer,
    I have been actively applying to companies, I applied around 150+ companies, I received only 2 interview calls, I got one offer , startup said that they will give me 3 month internship(20k)+ PPO ( base 6L) (location: Jaipur)(role: Java Backend Developer)
    I am not understanding what to do, I am from Telangana

  • @shwetanksudhanshu4383
    @shwetanksudhanshu4383 6 หลายเดือนก่อน +1

    Hello, can you please make the other videos are public instead of members only :) , it would really help. Thanks

    • @laghavmohan7210
      @laghavmohan7210 4 หลายเดือนก่อน

      No bro, Shreyansh need to give real life examples of data encapsulation.

  • @kartikrawat3610
    @kartikrawat3610 หลายเดือนก่อน

    Summary
    Adding notes here for reference: (NoteGpt)
    In Java, a single file can only contain one public class to ensure the JVM can easily identify the main method and its corresponding file.
    Highlights
    📁 Only one public class is allowed in a Java file.
    🏷 The public class name must match the file name.
    🚀 Main method must be in a public class for JVM access.
    🔑 JVM invokes the main method using the class name.
    📜 Multiple classes in a file can exist, but only one can be public.
    ⚠ Having multiple public classes would confuse the JVM.
    🔄 This structure ensures clarity and organization in Java programs.
    Key Insights
    💡 Public Class Limitation: Java restricts files to a single public class to simplify the access and invocation process for the JVM. This minimizes potential errors and confusion.
    📚 Main Method Accessibility: The main method, being the entry point of any Java application, must reside in a public class so that the JVM can access it without any package restrictions.
    🔍 File and Class Naming: The requirement for the public class name to match the file name helps maintain consistency and clarity, allowing the JVM to easily locate the entry point of the program.
    ⚙ Static Invocation: The main method is static, allowing the JVM to invoke it without creating an instance of the class, further simplifying the execution process.
    ❗ Avoiding Ambiguity: By limiting public classes, Java prevents ambiguity in which class contains the main method, streamlining the program’s execution.
    🏗 Organizational Structure: This restriction encourages developers to organize their code better, as they must carefully plan which class will serve as the primary entry point.
    🔗 Interrelation of Rules: Understanding the relationship between having a single public class and the main method’s requirements is crucial for effective Java programming and design.

  • @anuragsadula3036
    @anuragsadula3036 หลายเดือนก่อน

    Googled this
    can we have two public classes in one Java file?
    No, you cannot have two public classes in one Java file.
    Here's why:
    Naming Convention:
    The Java compiler requires that the name of the public class matches the name of the file. If you had two public classes, which one would the file be named after?
    Compilation Unit:
    A Java source file is considered a single compilation unit. A compilation unit can only have one public class that serves as the entry point for that unit.

  • @cleanconceptbyshakib
    @cleanconceptbyshakib 5 หลายเดือนก่อน

    Clarification:
    I think only one public class is only usefull when we are run java by comman line.Example : javac Tutorial.Java
    In this way JVM know there is a public class named Tutorial and contain main method .And JVM compile this. In command line there is no way to run normal class with main method. It is allowed that declare main method in normal class as many you want but we can't run them from command line .But in modern IDE, we can run normal class with main method.
    And we can say that it is just a language specification and convention

  • @infinity-hu4yk
    @infinity-hu4yk หลายเดือนก่อน

    Why do we even consider these questions the rule must be adhered the public class name should be equal to file name. I mean you know the rule since the beginning now you must answer why that rule must be followed. Whats next then the interviewer should ask why it was called java not royal Enfield.

  • @pleasantdayNwisdom
    @pleasantdayNwisdom ปีที่แล้ว +1

    Video 4