Contents
- 1 Installation of Java
- 2 Multi-threading
- 3 Secure
- 4 Platform independent
- 5 Portability
- 6 Object-Oriented
- 7 Robust
- 8 Data types and operators
- 9 Inheritance
- 10 Encapsulation
- 11 Polymorphism
- 12 Abstraction:
- 13 Exception Handling
- 14 Control Statements
- 15 Let’s begin:
- 16 If condition:
- 17 Ternary Operators:
- 18 The for Loop
- 19 Enhanced for Loop
- 20 Nested for loop
- 21 While loop
- 22 Do while loop
- 23 Infinite loop
- 24 Classes & Objects
- 25 Arrays
- 26 Structure of a program
- 27 File Handling Input and Output
Java concepts are a must for all programmers. Usually, we learn C, C++ for starting, And the next language we learn is Java. In this article, we are going to put in front of you some of the fundamental concepts of Java. And before we start, we need to learn what it is, what are the features of Java and how we can install it. In this blog we are going to cover the installation process of Java, how we write the Hello World program, what member variables are, what are data types and operators, and what are control statements. Then we will go through the classes and objects, and the structure of a program. Finally, we will look into Input and Output handling of the file in Java, and the arrays in Java. And we will finish off the article discussing the OOPS concept and Exception Handling. So, let’s begin the article. And you can contact us for your Java Online Training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java Training.
Installation of Java
You can download Java from here. However, make sure you have an Oracle Account, and you will require to accept the terms and conditions. You need to download the developer version from here. Download Java’s latest version. However, remember that JRE has been deprecated from Java 10 onward. Hence now you need not include it in the URL after JDK plus there is no JRE now. This will show when you will be installing the Netbean. Before, when you used to download, both the JDK and the JRE used to be present in the zipped file. However, now you will find only JDK. Download hence and follow all the instructions, and go on clicking ok. Once you install Java successfully, you need to update the Environment variable. You will witness here as well. If you are downloading a version post-Java 10, you need to add only the jdk bin URL in the environment variable path section. Or else you need to add till bin the URL for JRE as well.
Remember we are installing on Windows 10. Go to Start and search for System. And then search for the Advanced System Settings. Now click on Environment variable, and double click on Path. Now go to C drive, and under Program files find Java, and then inside that bin. Now click on the arrow in the Address bar, and copy the URL from there. In case, you have the Java version less than 10, you need to repeat this process for the JRE as well. Now add both of these URLs to the path, which you get after double-clicking on Path in the Environment Variable. Click ok and you are done. Now open the CMD, and enter Java -version. The Java version you downloaded will be shown. Congratulations, you have successfully installed Java on your Windows 10 machine.
Now you need to install the NetBeans or the Eclipse IDE. We are mentioning both so that you can install both of them or anyone. Download NetBeans full version from the internet, and also the Eclipse. Follow the installation process, as it shows. The JDK is required for both, which we have already installed. And the IDE will pick the JDK URL automatically. On successful installation, you need to add the server. And we will show later how to add the Apache Tomcat 9.0 server to the Netbeans. Remember, the web application will run on this Apache Tomcat 9.0 server. Let’s now see how we can curate a Hello world program, and that is our next point of discussion.
However, before that, let’s have a look at some of the salient features of Java. The salient features are as below:
Open Source
Java has always been anopen-source product, and all have public access. As a programmer, you can post the entire source code, and it’s downloadable by anyone. No license is required, and you get a GPL license or the General public License that we get through the open-source software.
High Performance
It’s an interpreted language, and hence it is not as fast as C or C++. However, it enables the best performance through the just-in-time compiler.
Multi-threading
Through Java, you can perform several tasks simultaneously as it is multithreaded. The advantage is you make use of the same memory and various other resources for executing numerous threads at one time, such as during typing, grammatical errors get checked.
Secure
Java is the best in security. Through its security features, we can develop virus and temper-free systems. And it always run-in runtime environment that has no interaction with the system OS, and therefore secure.
Platform independent
The C and C++ are compiled in platform-specific machines. Whereas Java is writing once, run anywhere programming setup. Java gets compiled into bytecode. And this is platform-independent, and you can run it on any of the machines. It also ensures security. And if the JRE is present on a machine, it can run the Java program.
Portability
The Java code is quite portable, and highly in fact. You can write the code in the windows environment and execute it in the Linux environment.
Object-Oriented
You will find all Java is an object which has data and behavior. And it can be easily extended as it is Object model-based.
Robust
Java to remove error-prone code put weights on runtime and compile-time checking. However, the main improvement in Java is in mishandled exception and memory management through the inclusion of exception handling and the Garbage collector.
Let’s now write the first Java program, which is the Hello world program
Hello World Program
Our first Java program is as below. We have declared a class called HelloWorld and printed the
“Hello World” message inside it. The code is as below:
public class HelloWorld {
public static void main(String[] args){
System.out.println(“Hello World”);
}
}
Member variables in Java
Member Variable
It is used to store the data value. There are three ways of declaring the data variable in a class. they are Local variables, instance, and Class/static variables.
Local: It’s the variable declared within a class method shown as below:
public class Student {
public void PrintStudent(string name){
string name1=name; // This is a local variable
System.out.println(“Student Name is:” +name1);
}
}
Above we have a local variable name1, declared with the method PrintStudent with parameter “name.”
The Instance variable
public class Student {
public String name; // instance variable
Student(String n){
name=n;
}
public void PrintStudentName() { // Method
System.out.println(“The name of the student is:”+name);
}
public static void main (String args[]){
Student obj=new Student(“NareshIt”);
obj.PrintStudentName();
}
}
Above “name” is the instance variable and it gets the value “NareshIt in the main function.
Class Variable or the Static Variable
These variables have one copy stored by all objects in a class. Let’s see the below code.
public class Student {
public static int HeadBoy; // This is class or static variable
public static void main(String args[]){
HeadBoy=”NareshIT”;
System.out.println(“HeadBoy is”+HeadBoy);
}
}
Above “HeadBoy” Is the class variable or the static variable. And its value remains the same everywhere in the class.
Data types and operators
We make use of the Data type to store various values in a variable. The main data types are Integer, character, float, and Boolean. Various data types under the Integer isthe byte, Long, Short, and Int. Various under Float are float and double. Various character types are char, and various Boolean types are Bool.We also have the string data type. And we have used that in the code that we have written till now in this blog post on various instances.
Now let’s have a look at the Operators.
We have mainly four types of operators which are respectively Arithmetic Operators, Unary operators, Logical operators, and relational operators. Let’s discuss each of them one by one.
Arithmetic Operator: the four arithmetic operators are addition, subtract, multiply, divide, and modulus.
Unary Operators : The unary operators are like increment and decrement operators. ++ is the increment and – is the decrement.
Relational Operator : It sets up the relation between the two entities. Like <,>,>=,<=,!=,==
Logical Operator: They are applied to Boolean values.
Before understanding anything else, let’s first discuss the oops concept. And then we will continue with the basics of JAVA.
OOPS concepts like Inheritance, Polymorphism, Encapsulation, and Abstraction
Inheritance
We already know what this is. However, let’s repeat that it’s the process where one class inherits the other class properties. There are two classes, the child class, and the parent class. It is the child class that inherits the properties of the parent class. it is also the derived class or we also know it as the subclass. And the class from which the child class inherits the properties is the parent class. And we also know it as the base class.
Let’s have one example to understand it more elaborately.
Suppose, there are “Class 9” and “Class 9 passed Students” and “Class 9 failed students”, which are the respective classes.The two of the last classes are the child class. And the first class is the parent class or the base class. You can clearly understand that both passed and failed students of class 9 will have the same list of subjects. Hence, it’s not a must that the child class inherits everything from the base class. We do have the scope specifiers which explain what is inherited and what is not.
The inheritance puts aside the code redundancy. There is a long list of inheritance types, and we will discuss that deep in the forthcoming blog post, please be assured. In that post, we will cover Object-oriented programming elaborately.
Encapsulation
We have the data and the code wrapped In one unit and that is the Encapsulation. Or you can experience that methods and variables are bound together in one class. And that is what we know as encapsulation. We can use the class variables only through the class method, and that ensures security. These variables are hidden from other classes but can be inherited through inheritance.
Polymorphism
Through this, we can have multiple forms of the variables, functions, and objects. And the most appropriate example of polymorphism is when various child classes implement the parent class differently. Also, it is implemented while we do the function overloading. The entire concept we will cover in a forthcoming blog, so please do not worry about these for now. One more example, however, is the Teacher asks the students to draw a shape. And the students draw the circles, and some draw the rectangle. This is what we know as Polymorphism.
Let’s, however, brief the function overloading here. Suppose we have the three definitions of the same function as below:
Void calculatearea(int a, int b);
Void calculatearea(int radius);
Void calculatearea(float side);
Based on the parameters passed the above same method will calculate the area of the rectangle, circle, or Square. And this is polymorphism. If you still didn’t get it please do not worry. We will have an elaborate post on OOPS soon.
Abstraction:
When talk about calculating an area, we can sometimes use the function, pass the parameters, and get the results. We are only concerned with the results and don’t care about the code and the calculation. Like Data Scientists use the Python methods and they don’t care about the code involved, whereas the data engineer deals with the code. And this is what we know as an abstraction. It makes the task simpler for the layman and puts the burden of coding and the calculation of one other person like above we have the data engineers.
And that completes the OOPS part for now. If you are finding difficulty in understanding the above, then you need not worry as we will soon cover the OOPS in a separate blog and detail.
Exception Handling
An exception is some issue that is not expected and arises at runtime. It hinders the sequential and normal flow of the program. Hence, we need to resolve it for avoiding the problems. Some of the exceptions are as below.
- Invalid format for function calling parameter missing
- Arithmetic out of bound exception
- Arithmetic divide by zero exception.
- And so on.
Let’s have a look at one through below code:
public class Student {
public static void main(String args[]) {
try {
float marks[] = new marks[20];
System.out.println(“Printing 21st element:” + marks[21]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“The Error encountered is :” + e);
}
System.out.println(“Out of bound”);
}
}
The output will be “Out of bound”
Now let’s hit back at the Java Core, and discuss the Control statements.
Control Statements
The control statements determine the program flow. All main types of control statements are available in Java. May it be conditional statements or iteration loops. There are two kinds of loops in Java and are the conditional statements, and the second one is iteration loops.
Under the conditional statements, we have the if condition, Else if condition, Else if ladder, Nested if condition, ternary operators, and iterative loops like the while loop, do-while loops, and “for loop.” We also have Nested for loop, Nested while loop, and Nested do-while loop. And then we have the Switch statement. We are going to discuss each of these in detail in this part. Please read carefully. These are essential for java programming, or in any programming language.
Let’s begin:
If condition:
In the conditional loop, a piece of code executes based on the Boolean value of the condition. In case of false, another piece of code executes. And when we talk of if condition. If the condition is true then the piece of code executes, or else the flow leaves the if loop and moves along with the next statement.
Package if-condition loop;
public class if-condition loop {
public static void main(String[] args) {
int num = -11;
if (num>=0) {
System.out.println(“positive.”);
}
System.out.println(“negative.”);
}
}
Output:
Negative
Else If condition
We use this for the execution of one statement out of two. There is one piece of code under if and one piece of code under else. If the “if” condition is true then that code executes, orthe “else” condition is true then else the code executes. Let’s have an example for this
Package else-if condition;
Import Java.util.scanner;
Class elseifcondition
{
Public static void main (string args[])
{
Scanner a=new Scanner(System.in);
System.out.println(“Enter the number”);
Int num = a.nextInt();
If (num > 20)
{
System.out.println(“Number is greater than 20”);
}
Else
{
System.out.println(“Number is less than 20”);
}
}
Output:
Enter the number
30
The number is greater than 20
Else if Ladder
In this we have consecutive Else If statements, and the true one executes from a series of code under if and else. And then the flow comes out of the else if ladder. Remember one condition must fulfill for the code to come out of anything else if ladder. And we can place break and continue statements in between to exit from the loop at any moment in the ladder if we feel it’s required.
If we place break then the flow comes entirely out of the loop. And if we use continue then the flow goes past that loop but continues to loop further.
package else-if-ladder;
import java.util.Scanner;
public class StudentMarks {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
System.out.println(“Enter Student marks”);
int marks=a.nextInt();
if(marks>=90){
System.out.println(“A+”);
}
else if(marks >=80 && marks<90){
System.out.println(“A”);
}
else if(marks <=70 && marks >60){
System.out.println(“B”);
}
else if(marks <=60 && marks>50){
System.out.println(“C”);
}
else {
System.out.println(“Failed”);
}
}
}
Output:
Enter the Marks
95
A+
Nested If condition
The Nested-if has one else if statement inside the another if statement.
package nested_if;
public class NestedIf {
public static void main(String[] args) {
int a = 10, b = 20, c = 30; char smallest;
if (a < b) {
if (a < c) {
smallest = ‘a’;
}
else {
smallest = ‘c’;
}
}
else {
if (b < c) {
smallest = ‘b’;
}
else {
smallest = ‘c’;
}
}
System.out.println(“Smallest is ” + smallest);
}
}
//Output:
Smallest is a
Ternary Operators:
These are the conditional statements that has three arguments. The first is the conditional argument, and the second is for true, and the third one is for false.
package Ternary;
import java.util.Scanner;
public class Ternary {
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
System.out.println(“Enter a”);
int a=k.nextInt();
System.out.println(“Enter b”);
int b=k.nextInt();
int Greater = a>b? a : b;
System.out.println(Greater);
}
}
//Output:
Enter a
20
Enter b
30
30
And now we are going to discuss the iteration in Java. We have three kinds of iteration loops not only in Java but in all the programming languages.
They are the While loop, for loop, and the Do while loops.
The for Loop
This is the control flow statement that executes a certain code segment from a known number of iterations. It has three arguments namely the initialization variable, counter, and the last one is the decrement/increment variable Let’s now have a program example for them for a loop.
Following code is an example for For Loop.
package for_loop;
public class for_loop {
public static void main(String[] args) {
int[] numeral = {3, 4, 5, 6, 7};
System.out.println(“Making use of For Loop:”);
for(int i=0; i<numeral.length; i++){
System.out.println(numeral[i]);
}
}
}
//Output:
Making use of for loop
3
4
5
6
7
Remember, the println automatically prints the number on a new line after every iteration.
Enhanced for Loop
This is similar to for loop, though it minimizes the code length and does not make use of the counter variables and the initialization variable. The control moves directly inside the array or the collection and it executes the operation on each element, which it accesses through the index.
Below is an example of an Enhanced for loop
package Enhanced_for_loop;
public class Enhanced_for_loop {
public static void main(String[] args) {
int[] numeral = {3, 4, 5, 6, 7};
System.out.println(“Making use of Enhanced For Loop:”);
for(int a:numeral){
System.out.println(a);
}
}
}
//Output:
Making use of Enhanced for loop
3
4
5
6
7
Nested for loop
This has for loop inside the for loop, and in nested for. The inner loop is triggered by the outer loop. And we can have any level of nesting. There is no limitation on this account. However, make sure that it terminates at some instance, or it will take the program to the infinite loop, and your program will never terminate.
Below is a program where we use the Nested for loop
package nested_for_loop;
public class nested_for_loop {
public static void main(String[] args){
int[][] 2darr = { { 4, 6 }, { 7, 8 } };
for (int i = 0; i<=1; i++)
{
System.out.println(“Value at” + i + ” : “);
for (int j = 0; j<=1;j++)
{
System.out.println(2darr[i][j]);
}
System.out.println(“”);
}
}
}
//Output:
Value at 0: 46
Value at 1: 78
While loop
This is the iteration that repeats until a Boolean condition gets justified.
Below is a program explaining the use of while loop
package while_loop;
import java.util.Scanner;
public class whiledemo {
public static void main(String[] args) {
int i = 0;
while(i<=1)
{
Scanner k = new Scanner(System.in);
System.out.println(“Enter a number”);
int a=k.nextInt();
if(a%2==0)
{
System.out.println(a);
}
++i;
}
}
//Output:
Enter a number
2
2
3
In the first iteration since 2%2= 0 2 is printed again. And in the second iteration since 3#2!=0, 3 is not printed. And thus, we have the above output as the iteration terminates immediately as I am greater than 1.
Do while loop
It’s the conditional statement that is similar to the While loop. However, there is one difference. The
Do while the look has the Boolean statement at the end of the loop. And hence the do-while loop always executes at least once.
Below is the program explaining the working of the Do while loop.
The following code is an example for Do While Loop.
//Insert elements in an array and add them using normal While Loop
//this program multiplies the input number with the previous over all multiple, and exit of we enter 0
package do_while_loop;
import java.util.Scanner;
public class do_while {
public static void main(String[] args) {t
int a, mul = 1;
Scanner k = new Scanner(System.in);
do {
System.out.print(“Enter a number to multiple and 0 to exit “);
a = k.nextDouble();
mul *= a;
}
while (a != 0);
System.out.println(“Multiple of all the numbers = ” + mul);
}
}
//Output:
Enter a number to multiple and 0 to exit
2
Enter a number to multiple and 0 to exit
3
Enter a number to multiple and 0 to exit
0
Multiple of all the numbers = 6
Infinite loop
This is not actually as practically designed, and should be avoided. However, if sometime any condition is not met then we encounter the infinite loop.
package infinite_loop;
public class infinite_loop {
public static void main(String[] args) {
int a=1;
while(a== 0) {
System.out.println(“NareshIT”);
a++;
}
}
}
//Output:
NareshIT
NareshIT
———– TO INFINITE
Let’s now have a look at the classes and objects in Java.
Classes & Objects
The class in Java is the collection of objects with the same type and properties. It hence contains the fields or what we know as the variables. And we also have the methods for describing the behavior of the object. Let’s now have a look at its syntax.
class classname {
list of member variables
list of methods
}
And we can access the methods and member variables through the object.
An object of a class is an instance of a class with behavior and state. Through it, we can access the data of the class. Let’s have a look at the syntax to see how we create an object of a class in java.
Student obj1 = new Student();
Here, the Student is the class name and obj1 is the object of the student. The new is used for allocating the memory. And the next is the call to the constructor. We can also pass the parameters of the constructor here if the constructor has the parameters defined in the class definition.
class Student()
void printStudent(); { // Method
—— // method body
}
public static void main(String args[]){
Student obj=new Student(); // object creation
obj.printStudent(); // calling a method through an object
}
If you want to know more, please do not worry at all. You can join our course on Java, and for that, you can contact us anytime.
Let’s now consider the Arrays
Arrays
It’s similar to what we have in C++ or any of the other languages. It’s a data structure that holds the sequential elements of the same type.
Suppose we want to store 50 student names. We can write 50 names separately. However, we can always create an array of type string and add the 50 student names one by one it. Or we can statically add the 50 names at once as well. Arrays hence reduce the redundancy. And, each of the arrays has two components known as the index and the value.
And the indexing begins with 0 and ends at n-1. Hence, if n is the size of the array then array length is n-1. We have two types of arrays. They are the single-dimensional arrays and the multi-dimensional arrays.
The single-dimensional array has a list of variables of one type, which all are accessible through one name. An array can be initialized as below:
Int a[] = new int[6];
You can have a look at the below as an array with elements. We are here initializing the array with all the values.
Int a[]= new aa[]{1,2,3,4,5,6};
Int a[]= {1,2,3,4,5,6};
Both of the above methods are correct for initializing an array in java.
Or we can use the for loop, or fill method, and many other methods are available in arrays as well.
For complete details please enroll in our Java course. You can contact us anytime for it.
Multi-dimensional array: It’s a multi-dimensional array, that is stored in a matrix form. And we can initialize it as below:
Int label[][]= new int[5][6];
This is the same as matrices in mathematics,
Thus, arrays help you in optimizing the code where you can insert the data at any location.
Let’s see the below code to understand the concept of the array in Java.
import java.util.*;
public class Array_Eg {
public static void main( Stringargs[])
{
int num[][]= new num[10][10]; // array initialization
Scanner obj= new Scanner(System.in); // for inputing a number we use scanner
for(i=0;i<10;i++){ // nested for loop
for(j=0;j<10;j++);
{
System.out.println(“Enter Number”);
num[i][j]=obj.nextInt(); //We store the values in array
for(i=0;i<10;i++){
for(j=0;j<10;j++)
{
System.out.println(num[i][j]);
}
}
}
}
In the code above, we created a two-dimensional array of type int. We then input the array elements using nested for loop, and final we printed out all the elements of the array.
However, there is a lot in an array, and likewise, we have tuple, dictionary, heaps, trees, LinkedList, queue, deque, stacks, and various other data structures. And you can learn all these by joining our Java course. Feel free to contact us anytime to enroll in our Java course.
Structure of a program
And thus, we now hope you have an idea about Java. For detailed knowledge, we would like you to join our Java course. However, before ending this blog post we put forward the structure of a Java program.
We always create a class and mention the variables and the methods in that. And we execute all the methods from within the main method. Like as below:
Public class Student{
Member variables;
Methods;
Public static void main(String args[])
{
// Call the class methods from here
}
}
File Handling Input and Output
Java has a separate library for handling the input and output functionalities. The java.io is the package/library which does the handling of the input and the output streams. We have two streams, which are the input stream and the second one is the output stream.
Input stream
This does the reading of the data from various sources.
Output Stream
This does the writing of the data to the destination.
File Input/Output Handling
Java has a dedicated library to handle all its input and output functionalities. It is the java.io package/library that handles all the input/output streams in Java. Java has two types of streams, they are:
- Input Stream
- Output Stream
Input Stream
It is responsible for reading data from all the sources.
Output Stream
It is responsible for writing the data to the destination.
An example of this is as below:
package NareshIT;
import java.io.*;
public class Test {
public static void main(String args[]) {
try {
byte writetofile[] = { 2, 4, 6, 8, 10 };
OutputStream ow = new FileOutputStream(“NareshIT.txt”);
for (int a = 0; a <Writetofile.length; x++) {
ow.write(Writetofile[a]);
}
ow.close();
InputStreamiw = new FileInputStream(“NareshIT.txt”);
int sizeofile = iw.available();
for (int i = 0; i<sizeoffile; i++) {
System.out.print((char) iw.read() + ” “);
}
iw.close();
}
catch (IOException e) {
System.out.print(“There is an error”);
}
}
}
Hope you now have an idea of how the file handling is being done.
However, this is not that all. Java has a lot to offer. Like if you will have a look at the Scanner, you will find there are so many methods available. And we can get any kind of input through Scanner. May it be the string, double, long, int, or any type of input variable. You can get them as input through the Scanner. And the whole data structure is being covered through the Scanner.
Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java Online Training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let’s have a look at what you will get with this Java Training package:
- You need to pay a nominal fee.
- You can choose any Java certification, as per your skills and interest.
- You have the option to select from online and classroom training.
- A chance to study at one of the best Java training institutes in India
- We provide Java Training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.
- Naresh I technologies cater to one of the best Java Online Training in India.
- And a lot more is waiting for you.
Contact us anytime for your complete Java Online Training.
Title |
---|
Java Tutorial For Beginners | Java Programming Made Easy |
Features of Java Programming Language |
Where Is Java Used In Industry? |
Why Java Is So Popular Language? |