- Introduction to Java Programming.
- Introduction to Flowchart and Pseudocode.
- Data Types in Java.
- Type Casting in Java.
- Operators in Java.
- Read Input from User in Java.
- Decision-Making Statement in Java.
- if...else statement in Java.
- Switch case statement in Java.
- For loop in Java.
- While loop in Java.
- Do While loop in Java.
Java Programming Complete Tutorial
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.
Access Specifiers in Java.
The process of hiding information is implemented using Access Specifiers known as visibility modifiers. They regulate access to classes, fields, and methods. Access Specifiers specify if fields or methods in a class can be invoked from another class or sub-class. In simple words, they are used to restrict access.
There are four types of Access Specifiers in Java.
- Public
- Private
- Protected
- Default (no specifier)
When no access specifiers are specified for an element, its accessibility level is the default. There is no keyword default. (alert-passed)
| Access Modifiers | default | private | protected | public |
|---|---|---|---|---|
| Accessible inside the class | Yes | Yes | Yes | Yes |
| Accessible within the subclass inside the same package | Yes | No | Yes | Yes |
| Accessible outside the package | No | No | No | Yes |
| Accessible within the subclass outside the package | No | No | Yes | Yes |
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.
Accessors and Mutators in Java.
Accessors and Mutators are two very important concepts in Java. It is used to read and update the private data member of a class.
To understand this concept more clearly we first have to understand encapsulation and access specifiers. Encapsulation is an important concept in Object-oriented programming and it is implemented by wrapping up the data and methods into a single unit.
The data present inside the class need to be secure and for this, we declare the data in a class as private. We cannot access the private data-member of other classes outside that class. To read and update the private data member a class outside that class we have to use public methods of that class. These methods are called Accessors or Getters and Mutators or Setters.
Accessor or Getters are methods used to return the value of a private field of a class. It does not change the state of the Object.
example:
public String getName() {
return name;
}
Mutators or Setters are methods used to set a value of a private field of a class. It changes the state of the object.
example:
public void setName(String fullName) {
name = fullName;
}
Example Java Program to Understand Accessors and Mutators.
public class Student {
//attribute
private int studId;
private String studName;
//Accessors or Getters
public int getStudId() {
return studId;
}
public String getStudName() {
return studName;
}
//Mutators or Setters
public void setStudId(int studId) {
this.studId = studId;
}
public void setStudName(String studName) {
this.studName = studName;
}
}
import java.util.*;
public class Main
{
public static void main(String[] args) {
//Object Creation
Student Obj = new Student();
//assign value using Setters
Obj.setStudId(112);
Obj.setStudName("Rahul");
//retrive value using Getters
System.out.println("Student ID: "+Obj.getStudId());
System.out.println("Student Name: "+Obj.getStudName());
}
}
Output:
Student ID: 112 Student Name: Rahul
In the above example, we can see that how we are reading and updating the private data member of the Student class from the Main class with the help of the Object of Student class.
Hope you found this article useful if you have any question related to this topic feel free to ask me in the comment section below.
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.
Java Classes and Objects.
Why it is important to create a Class in Java?
What is an Object?
There are three main characteristics of Objects,
- State: Represents the data of an object.
- Behavior: Represents the behavior of an object such as deposit, withdrawal, etc.
- Identity: It is used internally by the JVM to identify each object uniquely.
What is a Class?
Example of class:
public class Car {
String carColor;
String carBrand;
String fuelType;
}
Example of object:
Car objCar = new Car();
Attribute Declaration.
Attributes / Fields are used to declare the properties of a class. These attributes are called instance variables. They can be intrinsic types like int, boolean, etc, or user-defined types.
example: private double salary;
Method Declaration.
Methods describe the responsibility of the class. These methods are common for all objects. Hence they are known as instance methods. A method always has a name and a return type and it can accept parameters.
example:
public void calculateArea(int height) {
int result = height*height;
System.out.println(result);
}
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.
Read Input From User in Java.
In Java, Input can be read from the keyboard in many ways. One such way is to use the predefined/inbuilt class Scanner which is present in java.util package. Predefined/inbuilt classes in Java are organized in the form of packages. To use Scanner class, include package java.util using import statement as:
//import just a Scanner class import java.util.Scanner; //import the entire package java.util import java.util.*;
Next, create a Scanner object to give input from the system from the given keyboard.
- Scanner sc = new Scanner(System.in);
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Roll No: ");
int rollNo = sc.nextInt(); //integer input
System.out.println("Enter Student name: ");
String name = sc.next(); //single word input
System.out.println(rollNo+" : "+name);
}
}
Output:
Enter Roll No: 112 Enter Student name: John 112 : John
Like in the above example, the Scanner class has methods to get input of various data types.
| Methods | Data Type |
|---|---|
| nextInt() | Integer |
| nextFloat() | Float |
| nextDouble() | Double |
| nextLong() | Short |
| nextBoolean() | Boolean |
| next() | Single word (String without space) |
| nextLine() | String without space |
| * For next() :even if you try to input multiple words, the will takes the first word only as input | |
Important note: Reading String using nextLine().
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Student name: ");
String name = sc.next();
System.out.println("Enter the Address: ");
String address = sc.nextLine();
System.out.println("Name: "+name+" Address: "+address);
When you will execute the above code, the address will not be taken as input because Scanner skips the nextLine() when it is used after the next() or nextXxx() (ex: nextInt()) method. It is because the next() reads only the String, not the new line, and nextLine() consumes the next line (\n) as input, hence no input is received.
To overcome this problem, when using nextLine() after next() or nextXxx(), consume the new line by including the statement sc.nextLine(). See the below example to understand more.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Roll No: ");
int rollNo = sc.nextInt();
//captures the new line
sc.nextLine();
System.out.println("Enter Student Full Name: ");
String name = sc.nextLine();
System.out.println(rollNo+" : "+name);
}
}
Output:
Enter Roll No: 112 Enter Student Full Name: John Gupta 112 : John Gupta
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.
Binary Search Algorithm in Java.
Given a sorted integer array arr[] of size n and a target element X, the task is to write a Java program to find and return the index of the target from the given array. Return -1 if the target element is not present in the array.
Example:
Input: arr[] = {1, 2, 3, 4, 5, 6, 8} X = 4
Output: Element found at index 3
Input: arr[] = {3, 5, 10, 11, 12} x = 6
Output: Element not found in the arrayBinary search and Linear search are the two most popular search algorithms and binary search is more efficient because its time complexity is less than linear search. But the important thing to note is that binary search is only applicable to a sorted array.
Binary Search Algorithm.
The Binary Search Algorithm is based on the idea of comparing the target value with the middle element of the array. If the target value is equal to the middle value of the array then searching is complete. If they are not equal and the target value is smaller than the middle value, we will continue searching on the left side of the array. If the target value is larger than the middle value, we will continue searching on the right side of the array.
Steps for Binary Search Algorithm:
- Initialize the left and right pointer as low = 0, high = n-1.
- While low <= high, compare the middle element arr[mid] of the array with target value x.
- If the middle element matches with target arr[mid] = x, return the index of the middle element mid.
- If the target is less than the middle element arr[mid] > x, continue searching the left half. (high = mid - 1)
- If the target is larger than the middle element arr[mid] < x, continue searching the right half. (low = mid + 1)
- If the target element is not found, return -1.
Java Program for Binary Search Using Iteration.
// Java code to search the target element using binary search public class BinarySearch { public static int binarySearch(int[] arr, int target) { int left = 0, right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; // Element not found } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int target = 5; int result = binarySearch(arr, target); if (result != -1) { System.out.println("Element found at index " + result); } else { System.out.println("Element not found in the array"); } } }
Element found at index 4
Java Program for Binary Search Using Recursion.
// Java code for Binary Search to target element using Recursion public class BinarySearch { public static int binarySearchRecursive(int[] arr, int target, int left, int right) { if (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { return binarySearchRecursive(arr, target, mid + 1, right); } else { return binarySearchRecursive(arr, target, left, mid - 1); } } return -1; // Element not found } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int target = 5; int result = binarySearchRecursive(arr, target, 0, arr.length - 1); if (result != -1) { System.out.println("Element found at index " + result); } else { System.out.println("Element not found in the array"); } } }
Element found at index 4Java Program for Binary Search Using Built-in Function.
// Binary Search Built-in Function in Java to search // an element in sorted array import java.util.Arrays; public class BinarySearch { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int target = 6; // Sorting the array (required for binary search) Arrays.sort(arr); // Using binarySearch method int result = Arrays.binarySearch(arr, target); if (result >= 0) { System.out.println("Element found at index " + result); } else { System.out.println("Element not found in the array"); } } }
Element found at index 5
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.
Linear Search Algorithm in Java.
Input: arr[] = {9, 1, 3, 5, 7} X = 3
Output: Element found at index 2
Input: arr[] = {1, 2, 3, 4, 5, 7, 9} X = 6
Output: Element not found in the array
Linear Search Algorithm.
- If it matches, return the index.
- If it doesn't match, move to the next element.
Pseudo Code for Linear Search Algorithm.
function linearSearch(arr, target): for i from 0 to length of arr - 1: if arr[i] equals target: return i return -1
Java Program for Linear Search Algorithm.
// Java code for linear search algorithm to find and // return the index of searching element public class LinearSearch { public static int linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; } } return -1; } public static void main(String[] args) { int[] arr = {4, 2, 7, 1, 9, 5}; int target = 7; int result = linearSearch(arr, target); if (result != -1) { System.out.println("Element found at index " + result); } else { System.out.println("Element not found in the array"); } } }
Element found at index 2- Time Complexity: In the worst case, linear search has a time complexity of O(n), where n is the number of elements in the array. This is because, in the worst scenario, we may have to go through the entire array to find the element.
- Space Complexity: Linear search has a constant space complexity of O(1). It doesn't require additional memory that scales with the size of the input.
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.
Arrays Data Structure in Java.
An Array is a reference data type that can hold a fixed number of the same type of data. Array elements are store contiguously and the length of the array is decided when the array is created. We cannot change the array length after creation.
Array in Java is very different than the array present in other programming languages like C/C++. Some key points to note about Array in Java.
- In Java, arrays are dynamically allocated. What does it mean? It means that we can allocate memory to an array at run time using the heap.
- Arrays are objects in Java and we can use several array properties on them like we can use object property length to know the size of the array.
- We can specify the size of the array using int and short data type only.
int mark[] = {10, 20, 30, 40 ,50}; //primitive datatype
Employee empList[] = new Employee[3]; //non-primitive datatype
empList[0] = new Employee();
empList[1] = new Employee();
empList[2] = new Employee();The values that we store in an array are called elements and each element can be accessed by using their index.
Declaring an Array in Java.
The two common ways of declaring an array in Java is:
datatype[] arrayName;
or
datatype arrayName[];
//You can declare array of several different datatype:
int[] arrayInt;
long[] arrayLong;
short[] arrayShort;
float[] arrayFloat;
double[] arrayDouble;
boolean[] arrayBoolean;
char[] arrayChar;
String[] arrayString;Creating an Array in Java.
An array is created when we allocate memory to an array.
arrayInt = new int[10]; //creating an array
Initializing an Array in Java.
It is a process of assigning values to each element of the array.
arrayInt[0] = 10; //initializing first element arrayInt[1] = 15; //initializing second element arrayInt[2] = 20; //initializing third element arrayInt[3] = 25; //so on.. arrayInt[4] = 30;
Accessing Array Elements in Java.
We can access any array elements using their index value.
System.out.println(arrayInt[0]); //15 System.out.println(arrayInt[1]); //20 System.out.println(arrayInt[4]); //30 System.out.println(arrayInt[8]); //0 because our array length is 10 but the index 8 is not initialize with any value so by default it assign with 0.
System.out.println(arrayInt[11]); //Error We will get "ArrayIndexOutOfBoundsException" because our array length is 10 and we are trying to access index value 11 which is out of its range.
Java program to create integer array and access each element using their index value.
public class ArrayExample
{
public static void main(String[] args) {
//declare an integer
int[] array;
//allocating memory to the array
array = new int[8];
array[0] = 10; //initializing first element
array[1] = 20; //initializing second element
array[2] = 30;
array[3] = 40;
System.out.println("Element at index 0: "+array[0]); //accessing first element
System.out.println("Element at index 1: "+array[1]); //accessing second element
System.out.println("Element at index 2: "+array[2]);
System.out.println("Element at index 3: "+array[3]);
System.out.println("Element at index 6: "+array[6]);
}
}
Output:
Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Element at index 3: 40 Element at index 6: 0
You can also access array elements using a loop.
public class Main
{
public static void main(String[] args) {
//declare an integer
int[] array;
//allocating memory to the array
array = new int[5];
array[0] = 10; //initializing first element
array[1] = 20; //initializing second element
array[2] = 30;
array[3] = 40;
array[4] = 50;
System.out.println("Length of Array: "+array.length);
for(int i = 0; i < array.length; i++) {
System.out.println("Element at index "+i+":"+array[i]);
}
}
}
Output:
Length of Array: 5 Element at index 0:10 Element at index 1:20 Element at index 2:30 Element at index 3:40 Element at index 4:50
An array of Objects.
An array can also store objects similarly like it stores primitive data types.
Example: Student studentList[] = new Student[3];
The array variable studentList[] does not hold an array of Student objects, instead, it holds an array of Student reference variables. To make these variables hold the object, we have to create the object as:
studentList[0] = new Student(); studentList[1] = new Student(); studentList[2] = new Student();
Example of Array of Object in Java.
import java.util.*;
class Student {
public int stud_roll_no;
public String studen_Name;
Student(int rollno, String name) {
this.stud_roll_no = rollno;
this.studen_Name = name;
}
}
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//allocating memory to object of type student
Student studentList[] = new Student[3];
//initializing elements of the array
for(int i = 0; i < studentList.length; i++) {
System.out.println("Enter the rollNo: ");
int rollno = sc.nextInt();
System.out.println("Enter the name: ");
String name = sc.next();
studentList[i] = new Student(rollno, name);
}
//accessing elements of the array
for(int i = 0; i < studentList.length; i++) {
System.out.println(studentList[i].studen_Name+" Roll no is: "+studentList[i].stud_roll_no);
}
}
}
Output:
Enter the rollNo: 101 Enter the name: Rahul Enter the rollNo: 102 Enter the name: Mohit Enter the rollNo: 103 Enter the name: Kajal Rahul Roll no is: 101 Mohit Roll no is: 102 Kajal Roll no is: 103
Multidimensional Arrays in Java.
A multidimensional array is also called an Array of Arrays in which an array holds another array. Each row of the array can contain different lengths. The dimension of the array is decided by the number of square brackets ([ ]) you are adding. These are also known as Jagged Array.
- int[] arr; // 1D array
- int[][] arr; // 2D array
- int[][][] arr; //3D array
public class Main
{
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
1 2 3 4 5 6 7 8 8
Array as a Function Argument.
Java passes "objects by reference" and not by values. The array is passed as a reference and not as a copy of individual elements so any change done using array reference will be reflected in the original array.
Example of an array as a function argument in Java(Sort an Array).
class SortArray {
public void sort(int[] newArr) {
int n = newArr.length;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n-1; j++) {
if(newArr[j] > newArr[j+1]) {
int temp = newArr[j];
newArr[j] = newArr[j+1];
newArr[j+1] = temp;
}
}
}
}
}
public class Main
{
public static void main(String[] args) {
SortArray obj = new SortArray();
int arr[] = {20, 12, 50, 65, 15, 10};
obj.sort(arr);
for(int i : arr) {
System.out.print(i+" ");
}
}
}
Output:
10 12 15 20 50 65
The above example program is to sort all the array elements in ascending order. Similarly, we can perform several different operations on an array, like searching an element in an array using different searching methods or sorting the array elements in ascending or descending order.
I'm a full-time Software Developer with over 4 years of experience working at one of the world’s largest MNCs. Alongside my professional role, I run a news blog, WorkWithG.com, which focuses on Google tools, tutorials, and news. I'm passionate about breaking down complex topics and making learning accessible for everyone.







Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.