While loop in Java.

Java while loop is a control flow statement used to iterate a block of code repeatedly until the boolean condition present in the while loop is true. It is mainly used when we don't know the number of iteration in advance. The loop gets automatically stops when the boolean condition returns false. 
while loop in Java

Example: Write a Java Program to sum all numbers from 1 to 10 using a while loop.

public class Main
{
	public static void main(String[] args) {
		
		int i = 1, sum = 0;
		
		while(i <= 10) {
		    sum = sum + i;
		    //increment value of i for next iteration
		    i++;
		}
		System.out.println("Sum: "+sum);
	}
}
Output:
Sum: 55


Example: Write a Java Program to print all-natural numbers from 1 to 10 using a while loop. 

public class Main
{
	public static void main(String[] args) {
		
		int i = 1;
		
		while(i <= 10) {
		    System.out.print(i+" ");
		    i++;
		}
	}
}
Output:
1 2 3 4 5 6 7 8 9 10

For loop in Java.

For loop in Java is used to iterate a part of the program n number of times. There are other types of loops like while loop or do-while loop but they are used when the number of iteration is not known in advance and for loop is used when the number of iteration is fixed or known in advance. 

A simple for loop consists of three parts:

  • Initialization: It is the initial condition of a loop that executes only once before the execution of the code block. 
  • Condition: The loop will keep executing until the condition become false. This condition is tested each time before each iteration. 
  • Increment/Decrement: It executes every time after the block of code gets executed.

Example: Write a Java Program to Print all natural numbers from 1 to 10. (Simple loop)

public class Main
{
	public static void main(String[] args) {
		
		for(int i = 1; i <= 10; i++){
		    System.out.println(i);
		}
	}
}
Output:
1
2
3
4
5
6
7
8
9
10


Example: Write a Java Program to Print 3X3 matrix (nested loop).

public class Main
{
	public static void main(String[] args) {
		
		for(int i = 0; i < 3; i++){
		    System.out.print(i);
		    for(int j = 0; j < 3; j++){
		        System.out.print(" "+j);
		    }
		    System.out.println("\n");
		}
	}
}
Output:
0 0 1 2
1 0 1 2
2 0 1 2


Example: Write a Java Program to Print all the elements of an Array. (for each loop)

Here, we are using a for-each loop to traverse all the elements of an array.  For-each loop syntax is different from simple for loop. 

//syntax of for-each loop
for(type var : arr)
{
//statement;
}

public class Main
{
	public static void main(String[] args) {
		
		int[] arr = {10, 15, 20, 25, 30, 35, 40};
		
		for(int i : arr) {
		    System.out.print(i+" ");
		}
	}
}
Output:
10 15 20 25 30 35 40

Switch case Statement in Java.

Java Switch statement

Java switch case is like if..else statement, it also executes only one block of code from multiple blocks of code present. The data type that can be used to control the switch statement are int, byte, short, char, long and from Java 7 a String literal constant can also be used to control a switch statement. 

Some important points about switch cases in Java.  

  • We can have N number of switch-case statements in Java. 
  • Duplicate values are not allowed or we will get a compilation error. 
  • Data of the value which we provide to the switch case must be the same as the data type of the expression of the switch case. 
  • The datatype which is allowed for switch case expression is int, char, short, byte, and long.
  • Break statement in switch case is to control execution if we remove break then it will execute all the code until it reaches its end or meets new break statement. 
  • The default statement is optional, it gets execute when no expression matches the case. If we remove the default statement then noting will execute in that case. 

Example: Write a Java program to print the month name base on the given number. 


public class Main
{
	public static void main(String[] args) {
		
		int monthNumber = 12;
		
		switch(monthNumber) {
		    case 1:
		        System.out.println("January");
		        break;
		    case 2:
		        System.out.println("February");
		        break;
		    case 3:
		        System.out.println("March");
		        break;
		    case 4:
		        System.out.println("April");
		        break;
		    case 5:
		        System.out.println("May");
		        break;
		    case 6: 
		        System.out.println("June");
		        break;
		    case 7:
		        System.out.println("July");
		        break;
		    case 8:
		        System.out.println("August");
		        break;
		    case 9:
		        System.out.println("September");
		        break;
		    case 10:
		        System.out.println("October");
		        break;
		    case 11:
		        System.out.println("November");
		        break;
		    case 12:
		        System.out.println("December");
		        break;
		    default:
		        System.out.println("Not a valid month number!!");
		}
	}
}
Output:
December

Example: Write a Java program to print the season name based on the given month number.

  • Spring - March, April, May
  • Summer - June, July, August
  • Autumn - September, October, November
  • Winter - December, January, February

public class Main
{
	public static void main(String[] args) {
		
		int monthNumber = 12;
		
		switch(monthNumber) {
		    case 3:
		    case 4:
		    case 5:
		        System.out.println("Spring Season!!!");
		        break;
		    case 6:
		    case 7:
		    case 8:
		        System.out.println("Summer Season!!!");
		        break;
		    case 9:
		    case 10:
		    case 11:
		        System.out.println("Autumn Season!!!");
		        break; 
		    case 12:
		    case 1:
		    case 2:
		        System.out.println("Winter Season!!!");
		        break;      
		    default:
		        System.out.println("Not a valid month number!!");
		}
	}
}
Output:
Winter Season!!!

if...else Statement in Java.

Java  If else statement

In Java, if...else statement is used to check the boolean condition is true or false and based on the outcome, it runs a particular block of code and skips the other block of code present. There are various different ways and conditions in which the if-else statement is used for solving easy and complex problems.  

Example 1: if statement.

The block of code will execute if the boolean condition is true else nothing will execute. 


public class Main
{
	public static void main(String[] args) {
		int age = 18;
		
		if(age >= 18)
		   System.out.println("You are eligible to vote.");
	}
}
Output:
You are eligible to vote.

Example 2: if...else statement.

If the, if condition is true then the block of code present in the if block will get executed otherwise else block code will get executed. 


public class Main
{
	public static void main(String[] args) {
		int age = 17;
		
		if(age >= 18)
		   System.out.println("You are eligible to vote");
		else
		   System.out.println("You are not eligible to vote");
	}
}
Output:
You are not eligible to vote

Example 3: if-else if statement.

If we have more than one condition to check and the particular block of code gets executed whose condition is true. 


public class Main
{
	public static void main(String[] args) {
		
		int mark = 65;
		
		if(mark > 90)
		   System.out.println("Grade A");
		else if(mark > 70 && mark <= 90)
		   System.out.println("Grade B");
		else if(mark > 50 && mark <= 70)
		   System.out.println("Grade C");
		else
		   System.out.println("Fail");
	}
}
Output:
Grade C

Example 4: nested if-else statement.

In the nested if-else block, we get an if-else statement inside another if or else block of code. Inner condition is checked only if the other condition is true and nesting can be done up to any level. 

public class Main
{
	public static void main(String[] args) {
		
		int year = 2024;
		
		if(year % 4 == 0) {
		    if(year % 100 == 0) {  //check if the year is century
		        if(year % 400 == 0)  
		            System.out.println(year+" is a Leap Year");
		        else 
		            System.out.println(year+" is NOT a Leap Year");
		    }
		    else
		       System.out.println(year+" is a Leap Year");
		}
		else
		   System.out.println(year+" is NOT a Leap Year");
	}
}
Output:
2024 is a Leap Year

Operators in Java.

Operators in Java

To perform mathematical and logical manipulation of data we have to use Operators in Java Programming. 

Different types of Operators available in Java:


Operator Types Precedence
Unary Operator x++ x-- ++x --x ~ !
Arithmetic Operator * / % + -
Shift Operator << >> >>>
Relational Operator < > <= >= instanceof == !=
Bitwise Operator & ^ |
Logical Operator && ||
Ternary Operator ? :
Assignment Operator = += -= *= /= %= &= ^= |= <<= >>= >>>=


  • Unary Operator: Unary operators require only one operand to perform operations. 

Example


public class Main
{
	public static void main(String[] args) {
		int x = 10;
		int y = 20;
		boolean b = false;
		System.out.println(x++); //post increment
		System.out.println(x--); //post decrement
		System.out.println(++x); //pre increment
		System.out.println(--x); //pre decrement
		System.out.println(~y);  //minus of total positive value which starts from 0
		System.out.println(!b); //true
	}
}
Output:
10
11
11
10
-21
true

  • Arithmetic Operator: Arithmetic operators are used to performing addition, subtraction, multiplication, division, and modulo(remainder) operations. 

Example: 


public class Main
{
	public static void main(String[] args) {
		int x = 10;
		int y = 20;
		
		System.out.println(x+y); 
		System.out.println(y-x); 
		System.out.println(x*y); 
		System.out.println(y/x); 
		System.out.println(y%x); 
	}
}
Output:
30
10
200
2
0

  • Shift Operator: Shift operators are used to shifting all the bits in a value to the left or right side of a specified number of times based on the type of shift operation like left shift or right shift. 

Example:


public class Main
{
	public static void main(String[] args) {
		int x = 10; 
		int y = 2; 
		System.out.println(x<>y); //Right Shift Operator 10/2^2 = 10/4 = 2
	}
}
Output:
40
2

  • Relational Operator: Relational operators are used to define some kind of relation between two entities. There are two types of relational operators in Java, comparison operator and equality operator. 

Example: 


public class Main
{
	public static void main(String[] args) {
		int x = 10; 
		int y = 5;
		int a = 10;
		int b = 5;
		Main m = new Main();
		System.out.println(x < y);
		System.out.println(y < x);
		System.out.println(y > x);
		System.out.println(x > y);
		System.out.println(x >= a);
		System.out.println(y <= b);
		System.out.println(x == a);
		System.out.println(x != y);
		System.out.println(m instanceof Main);
	}
}
Output:
false
true
false
true
true
true
true
true
true

  • Bitwise Operator: There are three types of bitwise operators, bitwise AND (&) operator, bitwise inclusive (|) OR, and bitwise exclusive OR(XOR) (^). 

Example:


public class Main
{
	public static void main(String[] args) {        
        int a = 14;

    System.out.println("Bitwise AND:"+(a&a));
    System.out.println("Bitwise inclusive OR:"+(a|a));
    System.out.println("Bitwise exclusive OR(XOR):"+(a^a));

    }
}
Output:
Bitwise AND:14
Bitwise inclusive OR:14
Bitwise exclusive OR(XOR):0

  • Logical Operator: There are two types of logical operators, logical AND(&&) which return true when both the condition is true, and logical OR(||) which return true even if any one condition is true (it doesn't check the second condition if the first is true) operators.

Example: 

public class Main
{
	public static void main(String[] args) {
		int x = 10;
		int y = 20;
		int z = 30;
		System.out.println(x < y && x < z); 
		System.out.println(x < y && x > z);
		System.out.println(x < y || x > z);
		System.out.println(x > y || x < z);
		System.out.println(x > y || x > z);
	}
}
Output:
true
false
true
true
false

  • Ternary Operator: Ternary operator in Java can work as a replacement to an if-else statement and is very useful in Java programming. It is called ternary because it takes only three operands. 

Example: 


public class Main
{
	public static void main(String[] args) {
		int x = 10;
		int y = 20;
		int max = x < y ? y:x;
		System.out.println("Maximum: "+max);
	}
}
Output:
Maximum: 20

  • Assignment Operator: Assignment operators are used to assigning the value present on the right side to the operand present on the left side. 

Example: 


public class Main
{
	public static void main(String[] args) {
		int x = 10;
		System.out.println(x);
		x += 5;   //x = x+5
		System.out.println(x);
		x -= 5;  //x = x-5
		System.out.println(x);
		x *= 5;  //x = x*5
		System.out.println(x);
		x /= 5;  //x = x/5
		System.out.println(x);
		x %= 5;  //x = x%5
		System.out.println(x);
		x &= 5;  //x = x&5
		System.out.println(x);
		x |= 5;  //x = x | 5
		System.out.println(x);
		x ^= 5;  //x = x^5
		System.out.println(x);
		x>>=4;   //x = x>>4
		System.out.println(x);
	}
}
Output:
10
15
10
50
10
0
0
5
0
0


Precedence and Associativity in Java.

Precedence and associativity are used when we have to deal with more than one operator in a single equation. Precedence is used to determine the priority of the operators in an equation. If two operators have equal priority in the expression is evaluated through associativity. 

Category Operator Associativity
Postfix () [] .(dot operator) Left to Right
Unary ++ -- ! ~ Right to Left
Multiplicative * / % Left to Right
Additive + - Left to Right
Shift >> >>> << Left to Right
Relational >>= < <= Left to Right
Equality == != Left to Right
Bitwise AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR | Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Right to Left
Assignment = += -= /= %= >= <= &= ^= |= Right to Left
Comma , Left to Right

Type Casting in Java.

Implicit type casting in java

Implicit Casting: A lower size data type can be assigned to a higher size data type automatically. It is also called Widening.

byte -> short -> char -> int -> long -> float -> double

Example: char c = 'A';

                int i = c;

Explicit Casting: A higher size data type can be assigned to a lower size data type manually. It is also called Narrowing. 

double -> float -> long -> int -> char -> short -> byte

Example: long val = 10;

                 int x = (int)val;

Example of Implicit Casting.

public class Main
{
	public static void main(String[] args) {
		int x = 8;
		double y = x; //Implicit casting
		System.out.println(x);
		System.out.println(y);
		
	}
}
Output
8
8.0

Example of Explicit Casting.

public class Main
{
	public static void main(String[] args) {
		double x = 8.23;
		int y = (int)x; //Implicit casting
		System.out.println(x);
		System.out.println(y);
	}
}
Output:
8.23
8

Data Types in Java.

Java Data Types

Data types define the values a variable can hold in its lifetime. There are basically two types of data types available in Java:

  • Primitive data types: Primitive data types are the most basic data types that hold a scalar value. It includes boolean, char, short, int, byte, long, float, and double. 
  • Non-primitive (Reference) data types: Non-primitive data types are created by programmers that hold an object. It includes Arrays, Classes, and Interfaces.    
List of 8 primitive data types with their byte size and default value:

Data Type Size(in Bytes) Default Value
byte 1 0
short 2 0
int 4 0
long 8 0
float 4 0.0
double 8 0.0
char 2(UNICODE) '\u0000'
boolean depend on JVM false

  • The formula for Signed data type: -2n-1 to 2n-1-1
  • The formula for Unsigned data type: 0 to 2n-1
  • All integer and floating-point data types are Signed.
  • All character data type is unsigned. 

Byte data type: Byte data type value range between -128 to 127. Its default value is 0 and the minimum value it can hold is -128 and the maximum value it can hold is 127. It is used to store the value when memory saving is the most important requirement. 

Example: byte x = 5;

Short data type: Short data type values range between -32,768 to 32,767 and its default value is also 0. It is used to save the memory just like a byte data type. 

Example: short x = 2000;

Int data type: Int data type values range between -231 to 231-1 and its default value is 0. It is used to store integer types of data whose value is there in the given range.

Example: int a = 234534;

Long data type: Long data type values range between  -263 to 263-1 and its default value is 0. It is used when values go out of the integer range.

Example: long a = 100000L; 

Float data type: Float data type values range is unlimited and used to store floating-point number values. It is preferred to use a float data type instead of double when saving memory is important. Its default value is 0.0F. 

Example: float a = 130.0f;

Double data type: Double data type values range is also unlimited and like float, it is also used to store decimal type values. Its default value is 0.0d.

Example: double a  = 23.4;

Char data type: Char data type values are a single 16-bit Unicode character use to store characters. Its range is between '\u0000' to '\uffff'. 

Example: char ch = 'A';

Reference data types.

A reference variable can be used to refer to any object of the declared type or any compatible type. The value of any reference variable is null. 
Example: Employee emp = new Employee();

Introduction to Java Programming.

Introduction to Java Programming

Java Programming language is developed by James Gosling at Sun Micro System in the year 1995. It is a simple, portable, architecture-neutral, platform-independent, and object-oriented programming language. 

Why Java is Portable?

Java is known as a Portable language because we can execute the Java code on all major platforms. After compilation, your Java source code gets converted into byte code having a .class extension, and those files can be used on any Java-supported platform without any modification. 

Why Java is called an Architecture-neutral language?

Java is called Architecture neutral because the Java program can run on any processor irrespective of its vendor or architecture. It allows its application to compile on one hardware architecture and to execute on another hardware architecture. 

Why Java is called Platform Independent?

Java is called platform-independent because it can be executed on several platforms and does not depend on any type of platform. It is also known as (WORA) Write Once Run Anywhere. 

Why Java is an Object Oriented Programming language?

Java is an Object Oriented Programming language because without using class concepts we cannot write even a single program in Java. Object-Oriented Programming is faster, and easy to execute, and maintain. It also gives us a clear structure of our program. 

Java can run:

  • In a browser as an Applet. 
  • On the desktop as an Application. 
  • In a server to provide services (database access).
  • Embedded in a device. 
Java Editions:
  • Java Standard Edition (J2SE or JSE): Basic tools and libraries to build applications and applets (Standalone applications).
  • Java Enterprise Edition (J2EE or JEE): Tools and libraries to create servlets, Java server pages, etc (Web application).
  • Java Micro Edition (J2ME or JME): Libraries to create applications to run on hand-held devices such as PDAs and cellular phones (device programs and mobile applications).
The three core packages used in Java Programming are JVM, JRE, and JDK and all three are platform dependent because the configuration of each operating system is different but as we all know that Java is platform-independent. 
  • JDK stands for Java Development Kit and it includes development tools such as the Java compiler, Javadoc, Jar, and debugger. 
  • JRE stands for Java Runtime Environment and it contains the part of Java libraries required to run Java programs and is intended for end users. 
  • JVM stands for Java Virtual Machine. It is an abstract machine that provides a runtime environment in which Java bytecode can be executed. 
Any Java code first compiles into byte code (machine-independent code) then the byte code runs on JVM regardless of the architecture of that machine. 

Java Class File. 
  • A programming language such as C/C++ has 1 step execution. 

C++ compiler

  • Java Programming has two-step execution. 
Java Compiler working

How to write a program in Java?

Any code written in Java is written within a block termed a class. The main method in Java program acts as an entry point signature and all Java programs start their execution from the main method. 

A single Java programming language source file may contain one class or more than one class. If a .java file has more than one class then each class will compile into separate class files. 

Example:


class Student
{
  //block of code
}
class Teacher
{
  //block of code
}
class Hello
{
  public static void main(String[] args)  //main method
  {
    System.out.println("Hello World");
  }
}

After compilation, there will be three class files:- 

  • - Student.class
  • - Teacher.class
  • - Hello.class
The main method has to be declared as public static, takes String[] as an argument, and its return type should be void. 
  • To compile a java code type - javac Filename, java
  • To execute the code type- java Filename
Also read:

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson