Java - Basics and First Program part2


Java - Basics and First Program part2

Java Access Modifiers:

  • Modifiers modify classes, methods, etc. There are two categories of modifiers:
  1. Access Modifiers: default, public, protected, private
  2. Non-access Modifiers: final, abstract, strictfp
Java Arrays :

  • Objects that store multiple variables of the same type are called arrays.

Java Enums :

  • Enums were introduced in java version 5.0
  • Enums limits a variable with few predefined values. 
  • It is termed as enumerated list.
Comments in Java

  • Similar to c and c++, Java supports single-line and multi-line comments
  • Characters inside the comment statements are not compiled by the Java compiler.

First Java Program:

  • Open notepad and add type the below sample java code.
  • Find the name of the class that contains the main() method. Here the class that contains main() is HelloWorld. Hence save the file as HelloWorld.java.
  • Go the command prompt window. 
  • If you are saving all your java programs in C:\Program Files\java\jdk\bin, then you require admin rights to execute your program in command prompt. Hence start the command prompt using “Run as Administrator” as shown below:


  • Go to the directory where you saved the class. Assume it's C:\Program Files\java\jdk\bin, then set the directory as follows:


  • Type 'javac HelloWorld.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line.
  • Now, type 'java HelloWorld' to run your program.
  • You can see the output on the command prompt window.

Sample Code :

public class HelloWorld
{   
    public static void main(String[] args)
    {
        System.out.println("WikiTechy - Welcome to the world of Java");  
    }
}

Note:
  • Save the file as “HelloWorld.java”, that is the name of the class that has the “main” method. 
  • The main method is the place where the code execution process starts
  • The main method should be placed inside a public class and there should be only one 

Code Explanation :


    Hello World - Name of the class, same as filename that is “HelloWorld.java”.

    main - method where program execution starts. Contains array of strings as parameter.

    System - a class built into java.lang package

    out - public static member of the System class, which is of type PrintStream.

   println - method of the PrintStream class. It takes an expression as an parameter and displays it in String form to the standard output window.


Output :



  • Now type javac HelloWorld.java to compile the code.
  • Now the code is compiled without errors. 
  • So type java HelloWorldto execute the code and get output.