What is Java?

Java is a class-based programming language developed by James Gosling and his friends in 1991. Java follows the rule of “write once, run anywhere” because it is a platform-independent language. This approach is further fortified by the Java Virtual Machine (JVM). The virtual machine accommodates Java programs on a variety of operating systems. JVM also helps handle the memory a program occupies.   

The first version of the programming language, known as JDK 1.0, was released in the year 1996 by Sun Microsystems. Sun Microsystems was later acquired by Oracle. Since the language is easily writable and decipherable by developers, it is known as a high-level language. Below is a simple program following the syntax of Java programming:

                     public class HelloWorldJava

                     {

                        public static void main (String args[ ])

                      {

                        System.out.println("Hello World"); //This statement prints the phrase Hello World

                       }

                   }

In the above program, 'println' is a predefined method used in a program to print any output onto the screen. 'System' is a predefined class. 'Out' is a member of ‘System’ class. The term 'public' in Java programming language declares the visibility of a member; that is, members declared as public can be accessed by all other classes in the program file. The Java main function is always 'static' as it tells the compiler that object creation is not mandatory to access the main() method. The main program's type is 'void', which denotes that the main program does not return any value. String args[] denotes the series of arguments that are passed to main() method at the time of program execution.  

Learning the Basics of Java

It isn't too hard to learn Java basics as it is an object-oriented language. Python, C, C++, and Ruby are a few other programming languages that follow concepts of object-oriented programming. This means that a beginner who is familiar with one such language will find it easier to learn Java. Developers who are already familiar with OOPs principles will have no problems learning Java. The following list elucidates some of the common features of object-oriented programming: 

  • Object:  An object represents real-world entity such as customer, employee, product and so on.
  • Class: A class is a data structure that contains a group of objects. It can be either Public, Private, or Protected. 
  • Inheritance: A class in programming can take on the properties of its parent class.
  • Polymorphism: Polymorphism allows an object to behave differently in different contexts. There are two types of polymorphism namely static and dynamic.
  • Encapsulation: Encapsulation is usually used to keep the data safe. It differs from abstraction in that the latter hides unnecessary data (implementation details) from users.
  • Message-passing: This is the means through which objects communicate with one another.
  • Abstraction: Using abstract classes and interfaces, a developer can achieve abstraction.

Java Fundamentals

Java data types

Data type specifies the different sizes and values that can be stored in the variable. 

Primary (primitive) datatypes: Primitive data types can be classified into 8 distinct data types. They are int, float, char, double, boolean, short, long, and byte. Each of these types has its own size variations as well. For instance, int will occupy 4 bytes of space, while boolean will occupy just 1 byte of data (it takes up true or false values). 

User-defined (non-primitive) datatype: These are also known as reference types as they signify objects. The programmer defines the non-primitive data types. Non-primitive types include class, interface, arrays, and string.

Variables 

Variable is the name given to a piece of memory. It can be preceded by a type, which indicates the type of value it can store. There are three types of variables: 

  • Local variables
  • Instance variables
  • Class variables

Local variable: A variable that is declared inside the body of the method is called a local variable. This limits the scope of the variable to that method. The Java syntax is:

void function (int a )
                        {
                            int x;  // local variable
                         }

Instance variable: A variable that is declared inside the class but outside of all the methods is called an instance variable. They can be accessed by methods belonging to the same class and by using an object of the class. When the object is deleted, these variables are also destroyed.

                    Class A 
                   { 
                      int a;  // instance variable
                         public static void main ( )
                    }

Class variable: A variable that is declared with the help of the static keyword is called a class variable or static variable. Only a single copy of the variable is created when the class is instantiated for the first time and all instances of the class shares the single copy.
             Static int x; // static variable 

Typecasting

Converting one datatype to another datatype is called typecasting. There are two types of typecasting: 

  • Implicit typecasting: It is automatically performed by the compiler. 
  • Explicit typecasting: It is done by the programmer.

Input and output

Input (or scanner class): Scanner is a pre-defined class in Java that is available in java.util package. It is used to get user input. To use this, an object of the Scanner class must be created. 

               Scanner object_name=new Scanner(System.in);

Output (System.out.print()): It is an output statement in Java, through which we can print the variables, expressions, and much more content. The System is a predefined class here, while ‘out’ is a static member of the System class. The ‘print’ method that is used to display the argument passed to it on the console. However, it does not add a new line like the 'println' method.

System.out.println("Hello World");

Tokens

A token is the smallest element of the program that can be identified by a compiler. Every Java statement and expression is created using a combination of tokens. 

Example:
                  Class A
                      {
                        public static void main (String args[ ])
                                {
                                     int a=10, b=20;
                                     int c= a+b;
                                    System.out.print(c);
                                }
                       }

Keywords: Keywords are the reserved word whose meaning is already pre-defined and cannot be used as identifier. According to the example above, class, public, static, void, and int are some of the keywords.

 Identifiers: In Java, the identifier is the name of a variable, method, class, package, or interface that is used for the purpose of identification. According to the above example, the class name, main (which is the name of a function), and variables names are some of the identifiers.

Operators: An operator is a symbol that is used to perform some operation according to user requirements on the variables and their values. According to the above example +, = are the operators given. Operators can be classified as:

  • Arithmetic operators: +,-, /, *
  • Relational operators: <, >, <=, >=
  • Logical operators: &&, ||
  • Increment/decrement operators: ++, -- (post and pre increment/decrement)
  • Assignment operators: ==, +=, -=, /=, *=
  • Ternary operators: ? :
  • Bitwise operators: &, |

Statements in Java

Decision statement: It is used to alter the control flow based on the occurrence of some condition.

If Statement:  An if statement depends on conditions like true and false. It is further divided into simple if, if-else and nested if-else statements.

Switch statement: Switch is a multiple-way decision statement. Here, the value of a variable decides the path a program takes. For instance, if a variable titled 'age' is used as the parameter for the switch statement, depending on its value, any number of cases can be executed. If age=5, case 1 is executed to print a phrase "Age is five". Similarly, other cases can produce different results. 

Looping statement: A loop allows the repetition of certain statements several times. Fast execution, reusability, decreased lines of code, and reduction in memory space are some features of a loop. While, do-while, for loop, and for each loop are the different types of looping statements.

  • While loop: While loop is a pre-test loop (the loop's condition is checked prior to entering the loop). It is used when we do not know the number of iterations in advance. It is also known as the entry control loop. 

     While (condition)
      {
           ………
           ……….
      }

• Do-while loop: Do-while loop is a post-test loop (the loop's condition is checked after executing the loop’s body at least once). It is used when we want to execute the loop’s body at least once even if the condition is false. It is also known as the exit control loop. 

       do
         {
           …..
           ….
        }
          While(condition);

• For loop: For loop is the most commonly used loop. It is used when we want to perform initialization, condition, and increment/ decrement operations in a single line.


        for (initialization; condition; increment/decrement)
         {
         ……….
         ……….
        } 

For each loop: For each loop is mainly used to fetch the values from a collection-like array.                     

for (data type var 1 : var 2)
  {
     ……
      ……
   }

Nested-for loop: A for loop which is contained inside another 'for loop' is called 'nested for loop'.
    for (initialization; condition; increment/decrement)
    {
       for (initialization; condition; increment/decrement)
       {
       }
    }

Steps for Writing a Java Program

  • For saving the Java file, type the name of the file into the field provided with the extension .java, for example, HelloWorld.java. This name should always reflect that of the public base class in the program. 
  • To compile a program (compilation phase), use the command javac class-name.java in the command line window. For instance, javac HelloWorld.java. 
  • To run the program (execution phase), use the command java class-name. For example, java HelloWorld.
  • Comments can be used to list down additional details about how the program works. They can be divided as: Single line comment (//), multiline comment (/*…………*/), and documentation comment (/**…………..*/). The comments will be ignored by the compiler.

Context and Applications 

This topic is significant in the professional exams for both undergraduate and graduate courses, especially for 
• B.E. / B. Tech in Computer Science 
• M.E. / M. Tech in Computer Science  

Want more help with your computer science homework?

We've got you covered with step-by-step solutions to millions of textbook problems, subject matter experts on standby 24/7 when you're stumped, and more.
Check out a sample computer science Q&A solution here!

*Response times may vary by subject and question complexity. Median response time is 34 minutes for paid subscribers and may be longer for promotional offers.

Search. Solve. Succeed!

Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.

Tagged in
EngineeringComputer Science

Programming

Fundamentals of Programming

History of Java

Java Homework Questions from Fellow Students

Browse our recently answered Java homework questions.

Search. Solve. Succeed!

Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.

Tagged in
EngineeringComputer Science

Programming

Fundamentals of Programming

History of Java