Getting started with Java: Basics of Java

Getting started with Java

This year, Java turned 25. If you have ever felt grateful for LinkedIn, Twitter, or Facebook, then it’s not too late to send in your wishes to Java! Although there are many new kids on the block (Python snickers in the background), Java continues to occupy an important place in the hearts and code of 8 million developers worldwide. If you want to get acquainted with Java too, then read on!

1. Java’s programming environment

JDK, JRE, and JVM are three components that make up Java’s programming environment.

I) Java Development Kit (JDK) – It is a software package that is used to create Java applications. It converts code written by you i.e. source code into bytecode. This is done with the help of a debugger, which removes the errors, and a compiler. The java compiler, javac converts a .java file into a .class file which is executed by JVM. 

For example, if we write an application called HelloJavaApp, we need to save it with the .java extension. When we compile this class, it gets converted into a HelloJavaApp.class.

II) Java Runtime Environment (JRE) – It is a software that is a part of JDK and is used to run Java programs. It does so through various development tools, libraries, and JVM. With the help of Java Virtual Machine (JVM), you can run your Java code on any operating system, which makes Java a platform-independent language.  

‘Write once, run anywhere’ is Java’s stellar feature and every app developer’s dream come true!

2. Java terminology

I) Objects – Java is an object-oriented programming language, so everything revolves around classes and objects. An object in Java is similar to a real-world entity. For example, it can be a ‘person’ with attributes like name, age, and weight, which can be stored in Java through variables. This ‘person’ performs some functions like eating, working, playing, etc., which are called methods in Java. These variables and methods make up an object in Java.

II) Classes – A class is like a blueprint that you use to create objects of similar types. For example, you can have a class House, which can have rooms as objects. Although each room will share similar properties, it will also vary slightly. 

A class consists of variables, methods, and constructors. Every Java application begins with a class, which can be created using the class keyword. For example, class Internship. If you want to create an object of this class, you can use the keyword new to declare it. 

Internship intern = new Internship (“Shalini”, 20);

III) Methods – A method is a set of statements that is used to perform a certain task in Java. For example –

class HelloJava 

{

public static void main (String args[] )

{

System.out.print (“Hello, Java”);

}

}

This program prints Hello, Java. The main() method is used by JVM as a starting point to run this program, and the print() method is used to print the output.

IV) Data types You can store different types of data in Java using various data types, which have been divided into two categories – primitive and non-primitive.

Primitive data types occupy a specific size which has been predefined in Java. They are of 8 types –

i. byte –  It is used to store whole numbers from -128 to 127. Staying true to its name, it takes up 1 byte of space! For example – 

byte myAge = 21;

ii. short – It is used to store whole numbers from -32,768 to 32,767. It uses 2 bytes of memory. For example – 

short myStipend = 20000;

iii. int – It is used to store integers from  -2^31 to 2^31-1 (around 2 billion). It allocates 4 bytes of memory. For example –

int lotteryPrize = 1000000001;

You can use underscore to improve the readability of your code.

int lotteryPrize = 100_000_0001;

iv. long – It is used to store whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It takes 8 bytes of memory. For example – 

long accountNumber = 39504567921L;

Note the use of the suffix ‘L’. You can also write it in lowercase as ‘l’.

v. float – It is used to store decimal numbers. It uses 4 bytes of memory and is precise up to 6 – 7 decimal places. For example –

float bodyWeight = 70.5f;

As in the case of long, you need to use a suffix, which can be ‘F’ or ‘f’.

vi. double – This is another data type that you can use to store decimal values. It consumes 8 bytes of memory and is precise up to 16 decimal places. 

Both float and double should not be used to store currency because it may not be precise. You can use BigDecimal for such values.

vii. char  It is a 2-byte data type that is used to store a single character or digit. You must use single quotation marks while using char. For example – 

char firstAlphabet = ‘A’;

If you want to assign it a character in another language, you can use unicode. Unicode is an encoding system that is used to represent characters, emojis, and symbols. For example, the unicode for ‘₹’ is ‘\u20B9’ in Java.

char currency = ‘\u20B9’;

viii. boolean – It is a 1-bit data type that can be assigned either of the two values – true or false.

Non-primitive or reference data types are defined by the programmer. They contain the address (reference) of an object that holds the value. Strings, arrays, classes, and interfaces are the non-primitive data types in Java.

i. String – It is a sequence of characters. For example –

String name = new String(“Ragini”);

In the above example, String has been declared like a reference data type. It is an object of the String class. However, String is used frequently in Java, so it can also be written like a primitive data type –

String name = “Ragini”;

A String is immutable, which means that a String object cannot be changed.

ii. Array – It is used to store multiple values of the same data type. In the example below, you can store 100 integers in an array.

int [] primeNumbers = new int[100]

v. Variables – A variable is a memory location that stores a data value. For example –

int year = 2020;

In the example above, ‘year’ is a variable. Variables in Java can be of 3 types –

i. Local variables – These variables are declared inside a method, constructor, or block and can only be used within it. They are created when the method, constructor, or block is executed and stop existing afterwards. Local variables do not take a default value, so you need to assign a value to them.

ii. Instance variables – These variables are declared inside a class and outside methods, constructors, or blocks. However, they can be used inside all methods, constructors, or blocks within the same class. Instance variables are created when an object of the class is created and can be accessed by this object/s. Depending on their data type, they have default values such as 0 for integers, null for character, or false for boolean.

iii. Static variables – Like instance variables, static variables are also declared within a class but they use the keyword ‘static’. They are created when a .class file is created and are destroyed when the file stops existing. You can access static variables with the class name or object name.They can have a default value, so you don’t have to assign value to them when you are declaring them. 

VI) Identifiers – As the name suggests, these are names given to classes, methods, variables, packages, and interfaces. There are certain conventions that the programmers follow while using identifiers. Although they are not hard and fast rules, you should use them so that your code is easier to read and understand. So, unless you want to be the coder that people dread in an unflattering way, stick to the convention!

Image source – techHindustan

Here are some points that you should keep in mind –

i. Identifiers are case-sensitive. So, int year will not be the same as int Year.

ii. They should begin with a letter. Although you can use special characters like underscore(_) and dollar sign ($) in Java, you should avoid using them at the beginning.

iii. Don’t use spaces. This will give you a compile-time error. 

iv. While naming classes, use nouns that indicate the purpose of the class. If you are using more than two words, then use the pascal case. This means that you need to capitalise the first letter of each word. For example –

class CollegeLibrary

v. One-word variables should be written in lowercase. For compound words, you should follow the camel case. For example –

String bookTitle

You should choose a meaningful identifier for a variable unless it’s a temporary variable. For a temporary variable, the most commonly used names are i, j, k, m, and n for integers and c,d, and e for character.

vi. Method names are generally verbs, which follow the camel case. For example –

issue()

returnBook()

vii. You cannot use reserved keywords such as int, char, true, false, etc.

VII) Literals – The value that you assign to a variable is called a literal. For example –

int NextOlympicsYear = 2021; 

2021 is a literal in the above example. 

VIII) Access modifiers As a Java programmer, you can use some keywords to control the accessibility of a class, constructor, method, or variable. These keywords are called access modifiers, and they are of 4 types –

i. private – A variable, method, or constructor that has been declared private can only be used within the same class. 

ii. protected – A protected variable or method can be accessed by all classes within the same package.

iii. public – A class, variable, or method that has been declared as public can be accessed from any other class. public modifiers should be avoided in production level code.

iv. default – If you do not specify the modifier, then the class, variable, constructor, or method takes the default modifier, which allows any other class within the same package to access it.

IX) Operators To put variables and data types into use, we need to use certain symbols known as operators. For example, +, -, =, etc. Operators have been divided into the following categories –

i. Arithmetic operators – These are used to perform mathematical functions such as adding (+), subtracting (-), multiplying (*), dividing (/), and getting remainder (%). When you use multiple arithmetic operators in the same statement, Java performs the calculation from left to right and uses a hierarchy. Multiplication, division, and modulo operation (%) are given precedence over addition and subtraction. You can also use brackets to give higher precedence. For example –

short discount = 2000 – (20*2000)/100;

When we run this in a program, we get the following output –

ii. Relational operators – These are used to compare two variables or numbers, and they are of 6 types – 

greater than (>), greater than equal to (>=), less than (<), less than equal to (<=), is equal to (==), not equal to (!=)

Relational operators return a true or false value. For example – 

int age = 20;

boolean isEligibleToVote = age >= 18;

iii. Assignment operators – Besides the ‘=’ operator, there are 5 types of assignment operators –

 +=, -=, *=, /=, %=

These operators can be used to avoid rewriting variables. For example – 

int electricityBill = 500; 

int rent = 10000;

rent = rent + electricity bill;

The last statement can also be written as –

rent += electricityBill;

iii. Increment (++) and decrement (–) operators – These are used with a single operand to increase or decrease its value by 1. They can further be divided into prefix and postfix. 

A prefix operator increases or decreases the value of an operand and then uses it. For example –

int a = 10;

int b = ++a;

In this example, the value of ‘a’ will first increase from 10 to 11 and then be assigned to ‘b’. So, the value of ‘b’ will be 11.

A postfix operator uses the value of the operand first and then increases or decreases it. For example –

int a = 10;

int b = a++;

In this example, the value of ‘a’ will be first assigned to ‘b’ and then change to 11. So, ‘b’ will be equal to 10 and then ‘a’ will change to 11. 

iv. Logical operators – These perform logic operations such as AND, OR, and NOT by using three operators.

The AND (&&) operator is used to compare two conditions and returns true only when both conditions are true. For example –

int birthYear = 2000;

if ((birthYear > 1995) && (birthYear < 2015))

{

System.out.println (“You are from Generation Z”);

}

In the above example, both the conditions are true. So, the output will be – You are from Generation Z.

The OR (||) operator returns true when either of the conditions is true. 

The NOT (!) operator is used to invert the outcome of a statement. For example –

int a = 5;

int b = 6;

System.out.println ( ! (a<b) );

This will print the output as false.

X) Comments – You can add comments to your Java program to enhance the readability of your code. You can do this by using // followed by your statement. For example –

byte age; // variable to store the age of the participant

Java does not scan the comment for any errors, so you can write anything that explains the code in the best way.

These were the building blocks for programming in Java. Now let’s get our hands dirty by writing our first Java application!

3. First program in Java

i) Before getting started with the program, you need to first install JDK.

ii) Once you have installed JDK, open Notepad.

iii) Now let’s write a program to calculate age and print it.

class Age {

public static void main (String [ ] args) { // This is the first method that JVM accesses

int age; 

int birthYear = 1997;

int currentYear = 2020;

age = currentYear – birthYear;

System.out.print (“I am” + “ “+age+ “ “+”years old”); // “ “ refers to space

} //curly braces to close method

} //curly braces to close class

First java program

iv) When you have written the program, save it as Age.java. You can create a folder in the C drive to save it.

v) Next, open your Command prompt. You can do this by going to Start > Run > cmd.

vi) Let’s change the prompt to go to the directory where you have saved your file. For example, we have stored it in the C drive in a folder called MyJavaPrograms. So, we will write the following –

cd C:\MyJavaPrograms

vii) Next, enter ‘dir’ to see the files within this directory.

viii) Now let’s compile the program.

javac Age.java

You can check out this document to resolve any problems that you may be facing.

ix) If you type ‘dir’ again, you will see a .class file.

x) Let’s run the program now.

java -cp . Age

x) You should see the following output – 

Congratulations! You have made your first Java application!

This was your first taste of programming in Java. If you want to go big, you can check out Internshala’s Core Java training and create applications such as the Connect4 game! You can also use coupon code BLOG10 to get a discount of 10%. 

Leave a Reply

Your email address will not be published. Required fields are marked *