Digging Java

Java is one of the most popular and commonly used programming languages. It is widely recognized for its performance, platform independence, and security. We have tried to explain features of Java in detail. Let’s find out.

Java is used as a server-side language for back-end development, android development, desktop computing, games, and numerical computing. Various features of Java contribute to its wide use and popularity. In this blog, we have tried to explain features of Java programming language to understand why programmers, software developers, and data science professionals choose Java.

Features of Java

Below we have some of the most important features of Java programming:

1. Inspired by C and C++

Java is inspired by C and C++. The syntax of Java is similar to these languages, but the languages are quite different. Java inherits many features from C and C++. Compared to C++, Java code runs a bit slower, but it is more portable and offers better security features.

2. Simple and Familiar

Java programming language is simple to learn, understand, read, and write. Java programs are easy to create and implement compared to other programming languages such as C and C++. If you are familiar with the basic programming principles or the concept of OOP (object-oriented programming), it would be easy to master Java.

Why is Java simple?

  • Easy to learn

  • Clean code – easy to understand

Why is Java familiar?

  • It is similar to C and C++ and includes many features of these programming languages

  • The complex and ambiguous concepts in C and C++, such as explicit pointers and storage classes, are not included in Java

  • Easy to learn for programmers who know C or C++

3. Object-Oriented

Java is a fully object-oriented language, unlike C++, which is semi-object-oriented. It supports every OOP concept, such as Abstraction, Encapsulation, Inheritance, and Polymorphism. Java programs are developed using classes and objects. Another notable feature is that the main() function is defined under a class in Java.

4. Platform Independent

Java’s platform independence means that Java programs compiled on one machine or operating system can be executed on any other machine or operating system without modifications. It is also called an Architecture Neutral Language.

Java supports WORA (Write Once, Run Anywhere), meaning programmers can develop applications in one operating system and run on any other without any modification.

Java source code is compiled using Java Compiler. The compiler converts the source code into an intermediate code called the byte code. The JVM (Java Virtual Machine) further converts this code into the machine-dependent form. The JVM can execute byte code on any platform or operating system on which it is present.

5. Compiled and Interpreted

Java offers both compilation and interpretation of programs. It combines the power of compiled languages and the flexibility of interpreted languages.

When a Java program is created, the Java compiler (javac) compiles the Java source code into byte code. The Java Virtual Machine (JVM) serves as an interpreter that converts byte code to machine code which is portable and can be executed on any operating system.

6. Multi-Threaded

Java supports multithreading programming. A thread is an independent process to execute a set of statements. The term multi-threaded refers to creating multiple threads to handle multiple tasks simultaneously.

JVM uses multiple threads to execute different blocks of code of the same program in parallel. The multithreading feature allows programmers to write programs to do multiple tasks simultaneously. It improves CPU and main memory utilization as the application does not need to finish one task before starting the other.

Here are some of its advantages:

  • Maximum utilization of resources

  • Saves time

  • Saves cost

  • Threads are independent, so one thread does not affect the other

  • Enhances the performance of complex applications

7. Dynamic

Java is more dynamic compared to C and C++. It can adapt to its evolving environment. It allows programmers to link new class libraries, objects, and methods dynamically. Java programs can have a large amount of run-time information that one can use to resolve accesses to objects.

8. Robust

Java is a robust language that can handle run-time errors by checking the code during the compilation and runtime. The JVM will not be passed directly to the underlying system if it identifies any runtime error. Instead, it will immediately terminate the program and stop it from causing any harm to the system. Java has a strong memory management system. It also supports the concepts of garbage collection and exception handling.

9. Secure

Java is a secure language that ensures that programs cannot gain access to memory locations without authorization. It has access modifiers to check memory access. Java also ensures that no viruses enter an applet. Java’s bytecode verifier checks the code blocks for any illegal code that violates the access right. It also does not allow programmers to create pointers explicitly.

What are Java Methods?

A method, in general, is a programming construct, a reusable block of code that performs a specific task. Java Methods in a class are used to define the behavior of its objects. In other words, it describes what operations its objects are capable of performing.

For instance, you want to enter a few students’ names with roll numbers, and you wish to sort them in ascending order. Here you can create two methods, one for entering student details and the second for sorting the list of students.

There are 2 types of Methods in Java:

Pre-defined Methods

There are several built-in methods in java that are easily and directly accessible. These methods are from java standard libraries which can be Java Class Libraries (JCL) inside the java archive file with JVM and JRE. For example: print() method from class printstream, sqrt() from class math, min() and max() methods etc.

User-defined Methods

User-defined methods are created based on the requirements of the programmer. It has specific rules that have to follow to create a user-defined method.

Here on, we’ll proceed with understanding the working of user-defined methods.

How to declare a Method?

Syntax to declare a method in Java:


Access_Modifier Return_type Method_Name(Parameter_List){//definition/implementation/body of the method}
Copy code

1. Access_Modifier: It defines the access type of the method. It means to what extent and where the method can be accessed. It can be public, protected, private, or default.

FYI, a method with no access specifier is default i.e., package-level.

2. Return type: The return type or data type can be any of the datatypes (int, char, string, double, etc.). It returns the result to the method call in the respective datatype format.

Data Types Explained.

3. Method_Name: Method name follows the same rule as any programming language naming convention. Names should be in mixed case (uppercase, lowercase, underscore). Use verbs to describe the method.

4. Parameter_list: The list of parameters/arguments comes inside method round parentheses () separated by commas. If there are no parameters, it means, it’s a non-parameterized method that doesn’t pass any value to the method definition.

Example:


class Circle{    double radius;        void calculateArea() //method 1 definition    {        double area = 3.14*radius*radius;        System.out.println("Area of circle: " +area);    }    void calculateCircumference() //method 2 definition    {        double circum = 2*3.14*radius;        System.out.println("Circumference of circle: " +circum);    }}class Main{    public static void main(String args[])    {        Circle c = new Circle(); //creating object of class circle        c.radius = 5;         c.calculateArea(); //invokes calculateArea() with object c        c.calculateCircumference(); //invokes calculateCircumference() with object c    }}
Copy code

Output:

output1

Parameterized Methods

Parameterized methods contain a list of parameters separated by commas with method definition and declaration. Let’s see its implementation with an example.

Example:


class SimpleInterest{public double calculateSI(double p, double r, double t) //parameterized methods{    return p*r*t;}}class Main{    public static void main(String args[])    {        SimpleInterest si = new SimpleInterest();        double interest = si.calculateSI(20000.5, 0.8, 1.4); //sending values to the method        System.out.println("The interest calculated is: " +interest);    }}
Copy code

Output:

output2

How does a method call work?

Let’s take the above program, which calculates simple interest. Here, when the compiler comes to the statement where the method calculateSI() gets invoked. It tries to find a method with the name caculateSI() inside class SimpleInterest as the method is invoked with an object of class SimpleInterest.

While searching for the method in the class, it matches the method name, number, and type of parameters in the method declaration. In finding the correct method, the control of the program branches to the method. Then the actual parameters are mapped onto the formal parameters.

Consider the two statements below.

public double calculateSI(double p, double r, double t) //formal parameters

double interest = si.calculateSI(20000.5, 0.8, 1.4); //actual parameters

The formal parameter 20000.5 is copied into principal p, 0.8 into rate r, and 1.4 into time t. Hence, internally the compiler reads the statements like:

p=20000.5 //principal

r=0.8 //rate

t=1.4 //time

FYI, these variables are local variables for the method. Only the values are copied from actual parameters into formal parameters.

Returning values from a method

Take the Simple Interest example here as well.

The return statement should preferably be the last statement of a method as the control execution jumps to the calling method as soon as the return statement is encountered. The value returned to the calling method must be captured on a type compatible with the return type of the method.

return p\r*t;*

Therefore, the value returned from calculateSI() is captured in the variable interest of the double type.

double interest = si.calculateSI(20000.5, 0.8, 1.4);

Rules for returning values from a method:

  1. The value returned from a method must match its return type. Else the compiler will generate an error.

  2. The value being returned to the calling method is a local value and will be lost as soon as we exit the method. Therefore, this value must be caught in the calling method in a type compatible with the return type of the method.

Why use Methods?

  1. It facilitates code reusability by creating various methods or functions in the program.

  2. It also improves readability and accessibility to a particular code block.

  3. Methods creation makes it easy to debug for the programmers.

Contents of JDK

The Java Development Kit (JDK) contains several essential tools and resources for developing applications using the Java programming language. Some of its key components include:

  • The Java compiler translates Java source code into bytecode that can run on any platform with a Java Virtual Machine (JVM).

  • The Java Virtual Machine (JVM) provides an execution environment for Java bytecode.

  • The Java Class Library is a collection of pre-written code developers can use to build Java applications.

  • The Java Debugger is a tool developers can use to find and fix errors in their code.

  • JavaDoc provides an easy way to generate documentation from Java source code.

  • The JavaFX SDK is a set of graphics and media APIs that developers can use to create rich, cross-platform applications.

Take a look at the below image for reference:

Overall, the Java Development Kit is a comprehensive toolkit that provides developers with everything they need to create Java applications that can run on any platform.

JDK Components Description Table

Take a look at the below table to get an overview of the various components of Java JDK:

Component 

Description 

java 

Command-line tool used to execute Java programs and applications 

javac 

Command-line tool used to compile Java source code files into bytecode files 

jar 

Command-line tool used to package Java classes and resources into JAR files 

javadoc 

Command-line tool used to generate API documentation from Java source code 

jdb 

Command-line tool used to debug Java programs using a Java debugger 

jconsole 

Graphical tool used to monitor and manage Java applications 

jvisualvm 

Graphical tool used to profile Java applications and analyze their performance 

jps 

Command-line tool used to list Java processes running on the system 

jstat 

Command-line tool used to monitor the performance of Java applications and the JVM 

jstack 

Command-line tool used to print the stack trace of a Java process or thread 

jmap 

Command-line tool used to generate a memory map of a Java process 

jcmd 

Command-line tool used to send diagnostic commands to a Java process 

keytool 

Command-line tool used to manage keys and certificates used for secure communication in Java applications 

jdeps 

Command-line tool used to analyze the dependencies of Java classes and JAR files 

Note: This still needs to be an exhaustive list of all the components available in Java JDK. Still, it covers the most commonly used tools and additional ones useful in certain situations.

Overall, Java JDK provides developers with a comprehensive set of tools that can be used to develop Java applications for various purposes, including web applications, desktop applications, and mobile applications. Its versatility and ease of use have made it one of the most popular software development kits today.

Scanner class

The Java.util package’s Scanner class is used to read input data from a variety of sources, including input streams, users, files, etc.

Java User Input

In the java.util package is the Scanner class, which gathers user input. By creating an object of the class and using it, you can use any of the several methods given in the Scanner class documentation. The nextLine() method, which is used to read strings, will be utilized in our example:

Input Types

Below are some of the input types we use with the Scanner class.

Method 

Description 

nextBoolean() 

Reads a user-provided boolean value. 

nextByte() 

Reads a user-supplied byte value. 

nextDouble()  

A double value is read from the user. 

nextFloat() 

Reads a user-supplied float value. 

nextInt()  

Reads a user-supplied int value. 

nextLine() 

Reads a value for a String from the user. 

nextLong() 

A lengthy value is read from the user. 

nextShort() 

Reads a brief value supplied by the user. 

Take this as a case study

Example 1: Using a Scanner, read a Line of Text

Output:

Note the line in the example above that says

Here, we’ve made an input-named Scanner object.

To accept input from the standard input, use the System.in argument. It functions exactly like accepting keyboard input.

Then, we read a line of text from the user using the nextLine() method of the Scanner class.