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:

Decision Making Statements in Java.

Decision-making statements in any programming language help us in taking decisions base on certain conditions so we can execute a particular block of code and discard the remaining block of code to get our desired output. These are used to control the flow of the execution of the program. It works similarly like we take in real-life situations. 

Selection statements are available in Java. 

It might necessary to make a decision before arriving at a conclusion or to go on to the next step of processing, a selection statement is used in that case. 

  • Simple if: If is the most simple decision-making statement which is used to decide whether a statement or a block of code will be executed or not. If the condition is written inside if the statement is true then the block of code will be executed otherwise it will not be executed. 

if statement syntax

  • if statement only accepts the boolean value true or false and if the condition is written inside round brackets is true then the code inside the curly brackets will be executed. 

Here, Curly brackets are essential if there is more than one statement to execute. If you will write more than one statement inside if statement without curly brackets then only the first statement will execute when the condition is satisfied. 

Flowchart of if statement:

if statement flowchart

Example of if statement:

class AlgoLesson
{
  public static void main(String[] args)
  {
    int num = 4;
    if(num < 5)
    {
      int square = num * num;
      System.out.println(square);
    }
  }
}
Output:
16

  • if-else: In this statement, if the condition gets true then the code that is present in the if block will get executed, and if the condition gets false then the code that is present in the else block gets executed. It is different from simple if because here we know what to do when the condition will not satisfy. 
if-else syntax in java

 Flowchart for if-else statement:

if-else flowchart
Example of an if-else statement:

 
class AlgoLesson
{
  public static void main(String[] args)
  {
    int num = 6;
    if(num < 5)
    {
      int sum = num + num;
      System.out.println(sum);
    }
    else
    {
      int square = num * num;
      System.out.println(square);
    }
  }
}
Output:
36


  • nested if-else: It is used when one if statement triggers another if statement that is present inside the if block of code. We can check multiple conditions using nested if-else statements.

nested if-else syntax

Flowchart for nested if-else:

nested if-else Flowchart

Example of nested if-else:

class AlgoLesson
{
  public static void main(String[] args)
  {
    int a = 10;
    int b = 20;
    int c = 30;
    if(a > b)
    {
      if(a > c)
      {
        System.out.println("Biggest number: "+a);
      }
      else
      {
        System.out.println("Biggest number: "+b);
      }
    }
    else if(c > b)
    {
      System.out.println("Biggest number: "+c);
    }
    else
    {
      System.out.println("Biggest number: "+b);
    }
  }
}
Output:
Biggest number: 30

  • switch case: In the switch statement, we use a value of a variable or an expression to change the control flow of the program execution. Here we choose which block of code to execute base on the value we give as input and each block of code ends with a break statement. 

If non of the variable or expression matches with our desired value then the default block of code get executed. 

Some important points about switch case 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. 

switch case syntax

Flowchart for switch case statement:

switch statement flowchart

Example of switch statement:

public class AlgoLesson
{
	public static void main(String[] args) {
		int day = 6;
		switch(day)
		{
		    case 1:
		        System.out.println("Today is Monday");
		        break;
		    case 2:
		        System.out.println("Today is Tuesday");
		        break;
		    case 3:
		        System.out.println("Today is Wednesday");
		        break;
		    case 4:
		        System.out.println("Today is Thursday");
		        break;
		    case 5: 
		        System.out.println("Today is Friday");
		        break;
		    case 6: 
		        System.out.println("Today is Saturday");
		        break;
		    case 7:
		        System.out.println("Today is Sunday");
		        break;
		    default:
		        System.out.println("Invalid Input");
		}
	}
}
Output:
Today is Saturday

  • break: break statement is mostly used to terminate the switch sequence or to exit a loop. But if you are using a break statement inside a nested loop then only it will only break out of the innermost loop. 
Flowchart for break statement:
break statement flowchart
Example break statement:


public class AlgoLesson
{
	public static void main(String[] args) {
		
		for(int i = 1; i<=10; i++)
		{
		    //terminate the loop when i is 6
		    if(i == 6)
		      break;
		    System.out.println(i);    
		}
		System.out.println("Loop get Terminated");
	}
}
Output:
1
2
3
4
5
Loop get Terminated


  • continue: continue statement skips the current iteration of the loop and begin the next iteration of the loop. It is useful for the early iteration of a loop when a certain condition is met. 

Flowchart for continue statement:

continue statement flowchart

Example of continue statement:

//program to print even numbers
public class AlgoLesson
{
  public static void main(String[] args)
  {
    for(int i = 0; i < 10; i++)
    {
        if(i == 6)
        {
           continue;
        }
        System.out.println(i);    
     }
   }
}

Output:
0
1
2
3
4
5
7
8
9

  • return: return statement basically uses to return from a method. It can also use to return a value and the type of value it returns depends on the method return type. 

Example of return statement:

public class AlgoLesson
{
	public static void main(String[] args) {
		
		int a = 10, b = 10;
		
		System.out.println("Before return statement");
		if(a == b)
		   return;
		   
		System.out.println("This will not execute!");   
	}
}

Output:
Before return statement
Example:

public class AlgoLesson
{
    public static boolean returnExample(int a, int b)
    {
        if(a == b)
          return true;
        else
          return false;
    }
	public static void main(String[] args) {
		
		boolean result = returnExample(10, 20);
		System.out.println(result);
	}
}
Output:
false

Related post:

(getButton) #text=(Switch case statement in Java) #icon=(link) #color=(#2339bd)

(getButton) #text=(Do While Loop in Java) #icon=(link) #color=(#2339bd)

(getButton) #text=(For Loop in Java) #icon=(link) #color=(#2339bd)


Flowchart and Pseudocode Introduction.

Before writing the code for an application pre-planning the code is important and we can do this with the help of Flowcharts and Pseudocode. It helps us in writing good and efficient programs.  


What is a Flowchart?

A Flowchart is a diagrammatic representation of an algorithm, workflow, or process. It represents a step-by-step approach to solving a problem. The lines and arrows in it show the sequence of steps and the relationship among them. 


It uses different shapes and arrows to depict the sequence of actions and decision points in a program. Each shape in a flowchart represents a specific action, and arrows indicate the flow of control from one step to another.


Below are the Flowchart symbols commonly used:

  • Oval: Represents the start or end of the program.
  • Rectangle: Represents a process or action to be performed.
  • Diamond: Represents a decision point where a condition is evaluated.
  • Parallelogram: Represents input or output operations.
  • Arrows: Indicate the direction of flow between different steps.


Shapes Use in Flowchart

What is Pseudocode?

Pseudocode is an informal way of describing algorithms. It gives the programmer an idea about how the problem is going to solve. It is easily readable and does not require any strict programming language syntax to follow. 

One simple rule for writing pseudocode is that all the "dependencies" are intended, including while, for, do-while, if, if-else, and switch.  

Where Can I Write My Code?

In the previous post, we discussed what computer programming is and how a computer understands code. In this post, we are going to learn how we write codes.  

It is not like we can simply type words into text documents and automatically assume that the computer can translate them into machine code, read it and carry out a task like opening up a browser or running software.  


To properly send instructions to the computer we need programming languages. But we also can’t type in a certain language and expect the computer to understand. So how are we supposed to write code then?

Well, the answer is with an IDE, which stands for Integrated Development Environment allows the facilitation of code by a computer.  

IDEs are used to write code.

An IDE provides a graphic interface on your computer in which the programmer can easily write, run, and debug the code without having to worry about problems with the compilation or interpretation of the program.  

An IDE is like any other program on your computer such as a game, a browser, or even the file explorer, except we’ll be using it to write code. IDEs are able to turn your code into machine code and run it through the computer to produce results.    

IDE Example: NetBeans, IntelliJ, Visual Studios.  

Advantages of Using an IDE.

In addition to providing a place for programmers to develop their code, IDE’s provide some extremely useful tools for programmers to ease the job of writing code, such as built-in error checking, auto-fill in for frequently used words or phrases, and project hierarchy which will help you organize and manipulate the files within your project.  

“Back in olden days, before IDE’s, code used to be written on punch cards and then fed into computers which would take hours and causes a lot of pain.”  

IDEs are extremely powerful and will be used in almost 100% of your programming projects. So, through these IDE we are finally able to write and compile code smoothly without worrying about the computer not being able to understand it.  

How To Write code in IDE?

Each language has its own set of rules you must follow within an IDE. This is where a programming language syntax comes into play.  

Syntax: Rules you must have followed if you want your program to run correctly.  

Learning a computer language is very similar to learning a real language. It also has a set of rules you must follow when writing code in that language, similar to grammar in real-life languages.  


Breaking programming rules will result in an error.  

For example:

  • In Java, we must specify which type of variable we are defining and we also have to add a semicolon at the end of the line.  
  • In python, we just type what we want to create, we don’t even need to define that we are trying to create a variable, and just have we just have to type what we want to create.
  • In JavaScript, we specify we are making a variable but don’t define what type of variable we want to make.  

All these languages require that you follow this syntax because computers are extremely dumb, if you forgot one semicolon or misplace a character, the entire program will not run and send you back a syntax error.  


The IDE will tell you where in your code the error is and it also won’t let you run your program until the error has been fixed.  

So, it is always recommended that you learn the rules and syntax of a language before beginning to write complex programs in that language. 

(getButton) #text=(Visual Studio Code Setup) #icon=(link) #color=(#2339bd)

What is Computer Programming?

Dictionary Definition: Programming is the process of preparing an instructional program for a device.

But that’s a really confusing definition, so in layman’s terms what exactly does that mean? Essentially, it is attempting to get a computer to complete a specific task without mistakes.

Just, for example, you instruct your less than intelligent friend to build a Lego set. He lost the instructions so now he can only build based on your commands. Your friend is far from competent on his own and so you must have to give him EXACT instructions on how to build, even if there is one piece wrong the entire Lego set will be ruined.

Giving instructions to your friend is very similar to how programmers code.

An important thing to note is that computers are actually very dumb. We build them up to be this super-sophisticated piece of technology when in actuality a computer’s main functionality comes from how we manipulate it to serve our needs.

{"Computers are only smart because we program them to be"};

The language that Computer Understand.


Programming isn’t a simple as giving instructions to your friend since, in the case of programming, the computer doesn’t speak the same language as you. The computer only understands machine code, which is a numerical language known as a binary that is designed so that the computer can quickly read it and carry out its instructions.

Every instruction fed to the computer is converted into a string of 1’s and 0’s and then interpreted by the computer to carry out a task. Therefore, in order to talk to the computer, you must first translate your English instruction to Binary.

Directly translating what you want the computer to do into machine code is extremely difficult, in fact almost impossible, and would take a very long time to do if you could. This is where programming languages come into play.

Programming languages are fundamentally a middle man for translating a program into machine code-the series of 0’s and 1’s that the computer can understand. These languages are much easier for humans to learn than machine code, and are thus very useful for programmers.

{"A programming language is not English and not machine code, it is somewhere in the middle"};

How is Programming Language Vary?

There are many different programming languages out there that each has its own unique uses.

  • Java and Python: General Purpose languages.
  • HTML/CSS: Designed for specific tasks like web page design.

Each language also varies in how powerful it is:

  • JavaScript is a scripting language and isn’t used for big problems.
  • Java and Python can carry out a much more computationally taxing process.

We measure a programming language’s power level by how similar it is to machine code. Low-level programming languages such as Assembly or C are closer to binary than a high-level programming language such as Java or Python.

The basic idea is that the lower the level of your programming language, the more your code will resemble what the machine can interpret as instructions.

So, try different languages and decide which one’s rules, interface, and level of specification you like the best.  

DON'T MISS

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