Sunday, October 28, 2018

OOP concepts

Hello friends! In here I am going to describe background to Object Oriented concepts and them.

Do you know about these things?

Simula - the first object - oriented programming language
smalltalk - the first pure object - oriented language
other - ex: Java, C#, PHP, Phython, C++

The main objective of oop is to implement real  world entities.Before that lets see what is a class  and an object .

What is an object in oop ?
An Object is a real world entities with state and behaviors . ex:pen,chair,car
It is an instance of a class. An object has an address and take some memory in space.

ex: object - baby
      state/data/attributes             - name ,age ,weight,date of birth
      behaviors/methods              -  laughs,drinks,sleeps,cries

In here state are descriptive characteristics. Behaviors tell us what object can do.

What is a class in oop?
A class is a collection of objects.It is logical entity. On the one hand it is a category or group of things that have similar attributes and common behaviors.On the other hand it is a blueprint from which individual objects are created.


Then we are going to talk about concepts which are associated with oop.

1.Inheritance("is-a" relationship)
non-private members of the super class inherit to the sub class.

It is the process by which one class acquire  the properties and behaviors of another class(parent class).It provides code re usability.



Lets see  examples for inheritance.

public class Dog{
public static void main (String[]args){

}
}

public class Puppy extends Dog{
}

All the states and behaviors can have puppy.Also  the states and behaviors which are  specific to puppy can have. The reality is "puppy is a dog". In here you can see "is-a relationship " between puppy and dog.

class Parent{
int height =120;
void sing(){
System.out.println("classical");
}

}
class Child extends Parent{

}

class Test{
public static void main(String[]args){
Parent p = new Parent (); // creating parent type object
p.sing();
System.out.println(p.height);
Child c =new Child(); // creating child type object
c.sing();
System.out.println(c.height);
}
}

output
classical
120
classical
120

According to above example Parent can sing ("sing()"method ) and height is 120.They are not private variables or methods.When Child extends to the Parent ,super   class (attributes and behaviors of super class  ) inherits to the sub class.

ex:
class Bird {
public String reproduction = "egg";
public String outerCovering = "feather";

public void flyUp() {
System.out.println("Flying up...");
}
public void flyDown() {
System.out.println("Flying down...");
}
}

class Eagle extends Bird {
public String name = "eagle";
public int lifespan = 15;
}


class TestEagle {
public static void main(String[] args) {
Eagle myEagle = new Eagle();

System.out.println("Name: " + myEagle.name);
                System.out.println("Reproduction: " + myEagle.reproduction);
System.out.println("Outer covering: " + myEagle.outerCovering);
System.out.println("Lifespan: " + myEagle.lifespan);
myEagle.flyUp();
myEagle.flyDown();
}
}

output
Reproduction:  egg
Outer covering: feather
Lifespan: 15
Flying up...
Flying down...

2.Encapsulation (hide the implementation)
The wrapping up data and methods into a single unit(class) is known as encapsulation.
Ex: capsule (it is wrapped with different medicine)
 Usage

Data hide(security purposes)

For avoid entering wrong data (ex: In a system you have to enter your age in one field, If you give  negative , zero or sometimes value is more than 100 in there , If value  map with age but it can not practically happen. )


class Student{

private int id;
private String name;
private  int age;

public void setId(int id){
this.id =id;}

public int getId(){
return id;
}

public void setName(String name){
this.name =name;}

public String getName(){
return name;
}

public void setAge(int age){
this.age =age;}

public int getAge(){
return age;

}}


class Test{
 public static void main(String[] args) {
        Student s =new Student();
        s.setName("uresha");
        s.setAge(22);
        s.setId(7);
        System.out.println(s.getName());
        System.out.println(s.getId());
        System.out.println(s.getAge());
    }

}

output
uresha
7
22

3.Polymorphism
when one task is performed by different ways we can use this. we use following two things two achieve this.


  • method overriding (dynamic polymorphism)
  • method overloading (static polymorphism)
Method overloading (static polymorphism)
  • class has multiple methods in same name with different parameters
  • two ways to overload a method (by changing data type ,by changing no. of arguments)
  • advantage - increases the readability of the program


class Bird {
public void fly() { //no parameter
System.out.println("The bird is flying.");
}
public void fly(int height) { // int parameter
System.out.println("The bird is flying " + height + " feet high.");
}
public void fly(String name, int height) { //string and int parameters
System.out.println("The " + name + " is flying " + height + " feet high.");
}
}

class TestBird {
public static void main(String[] args) {
Bird myBird = new Bird();

myBird.fly(); // call no parameter
myBird.fly(10000); // call int parameter
myBird.fly("eagle", 10000); // call string and int parameters
}
}


output
The bird is flying.
The bird is flying 10000 feet high.
The eagle is flying 10000 feet high.

Method overriding (dynamic polymorphism)


  •  can override the methods of the parent class from its child class.            

class Animal {
public void eat() {
System.out.println("This animal eats insects.");
}
}

class Bird extends Animal {

public void eat() {
System.out.println("This bird eats seeds.");
}

}

class TestBird {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.eat();

Bird myBird = new Bird();
myBird.eat();
}
}

output
This animal eats insects.
This bird eats seeds.

4.Abstraction

Hide complexity from the users and show them only the relevant information .
ex: if you want to drive a car , you do not need to know about its internal working process.

We can hide internal implementation details using abstract classes (can achieve partial abstraction )or interfaces(total abstraction).

abstract method-  has only method signature
concrete method - has method body

abstract class Animal {
// abstract methods
abstract void move();
abstract void eat();

// concrete method
void label() {
System.out.println("Animal's data:");
}
}



class Bird extends Animal {

void move() {
System.out.println("Moves by flying.");
     }
void eat() {
System.out.println("Eats birdfood.");
}
}

class Fish extends Animal {
void move() {
System.out.println("Moves by swimming.");
     }
void eat() {
System.out.println("Eats seafood.");
}
}

class TestBird {
public static void main(String[] args) {
Animal myBird = new Bird();

myBird.label();
myBird.move();
myBird.eat();
}
}

class TestFish {
public static void main(String[] args) {
Animal myFish = new Fish();
                myFish.label();
myFish.move();
myFish.eat();
}
}


 output of TestBird
Animal's data:
Moves by flying.
Eats birdfood.

output of TestFish
Animal's data:
Moves by swimming.
Eats seafood.

**Interfaces

Java interfaces  use for implement multiple inheritance.A class can implement any no. of interfaces.
Classes can access an interface using implements keyword.

interface Animal {
public void eat(); // abstract method
public void sound();  // abstract method
}

interface Bird {
int numberOfLegs = 2;  // static field
String outerCovering = "feather";   // static field

public void fly();  // abstract method
}

class Eagle implements Animal, Bird {
//it defines own functionality for 3 abstract methods eat(),sound() and fly()
public void eat() {
System.out.println("Eats reptiles and amphibians.");
}
public void sound() {
System.out.println("Has a high-pitched whistling sound.");
}
public void fly() {
System.out.println("Flies up to 10,000 feet.");
}
}

class TestEagle {
public static void main(String[] args) {
Eagle myEagle = new Eagle();

myEagle.eat();
myEagle.sound();
myEagle.fly();
                                                                                //in here static object does not belong to  specific object but belongs to whole class.So we use Bird interface .
System.out.println("Number of legs: " + Bird.numberOfLegs);
System.out.println("Outer covering: " + Bird.outerCovering);
}
}

output of TestEagle
Eats reptiles and amphibians.
Has a high-pitched whistling sound.
Flies up to 10,000 feet.
Number of legs: 2
Outer covering: feather


Let us try to understand a little about all these, through a simple example.

 Human Beings are living forms, broadly categorized into two types, Male and Female. Right? Its true. Every Human being(Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are body parts that are common for Male and Female, but then there are some specific body parts, present in a Male which are not present in a Female, and some body parts present in Female but not in Males.

All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs some
common functions, but there are some specifics to both, which is not valid for the other.
For example : A Female can give birth, while a Male cannot, so this is only for the Female.

Class

Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its properties and its functions.
 Like Human Being, having body parts, and performing various actions.

Inheritance

Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat, see etc.
 Male and Female are also classes, but most of the properties and functions are included in HumanBeing, hence they can inherit
everything from class HumanBeing using the concept of Inheritance.

Objects

My name is Abhishek, and I am an instance/object of class Male.When we say, Human Being, Male or Female, we just mean a kind, you, your friend, me we are the forms of these classes.
 We have a physical existence while a class is just a logical definition. We are the objects.

Abstraction

Abstraction means, showcasing only the required things to the outside world while hiding the details.
 Continuing our example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world.
 We can take our skin as the Abstraction factor in our case, hiding the inside mechanism.

Encapsulation

This concept is a little tricky to explain with our example.
Our Legs are binded to help us walk. Our hands, help us hold things.
 This binding of the properties to functions is called Encapsulation.

Polymorphism

Polymorphism is a concept, which allows us to redefine the way something works,
by either changing how it is done or by changing the parts using which it is done. Both the ways have different terms for them.

If we walk using our hands, and not legs, here we will change the parts used to perform something.
 Hence this is called Overloading.

And if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else.Then I can walk like I want, this will be called as Overriding.







Thursday, October 18, 2018

Access Modifiers In Java

Hi! friends, In here I am going to describe  access modifiers ,access levels and somewhat about package hierarchy in java.

There are 3 access modifiers in Java.
1.public
2.protected
3.private

Also there are 4 access level in Java.

1.public - with public keyword
2.protected - with protected keyword
3.default - no keyword here
4.private - with private keyword



 According to above image , "public " can use within the class, within the package , outside package by sub class only and outside package.

"private" can only use within the class

"default " can use within class and package.

"public" can use in above all places.

These things can easily understand with variables and methods...

Package Hierarchy

A package can exist inside another package.
According to this case there are 3 packages exist.
  - pack1
  -pack1.pack2
  -pack1.pack2.pack3

If we getting only packages as pack2 and pack3 they are not packages.We should use complete name of them as above.

ex: class A presents in the package pack1
      class B presents in the package pack1.pack2




package pack1;
class A{
public static void main(String[]args){
System.out.println("A");
}
}


package pack1.pack2;
class B{
public static void main(String[]args){
System.out.println("B");
}
}

package pack1.pack2.pack3;
class C{
public static void main(String[]args){
System.out.println("C");
}
}


Wednesday, October 3, 2018

Control Statements

Hi! guys , through this part  I am going to explain control statements which we can see in Java. These  control statements's behaviors are common for any programming language. But for further purposes you should need basic understand about these things.

Lets discuss about them step by step.

Under this topic we can see two kind of control statements.(control structures in java)
1.Selection Structure
2.Repetition  Structure


  • Selection Structure

 Under this one we can see ,

                                        single selection - if
                                        double selection - if else
                                        multiple selection - switch

If statement

 In here , in if statement  a condition is tested, and if the condition meets the test , the relevant code is executed.

public class IfExample {
public static void main(String[]args){
int age =30;
if (age>18){
System.out.println("Age is grater than 18");
}
}
}


If Else statement


In here a different code is executed if the condition fails the test.

public class IfElseExample{
public static void main(String[]args){
int age =12;
if (age>=18){
System.out.println("You can vote");
}else{
System.out.println("You can't vote");
}
}
}

In above examples we declared a variable and initialized it. That means we created a variable called "age" int type  and assign value 18 to it.

 Can't we do this using keyboard input?
Yes.  We can.
 For that you should import  under java.util.package classes  , java.util.Scanner  class .

Let's see how we write if-else statement using Scanner.

import java.util.Scanner;
public class Vote{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
System.out.println("Enter your age : ");
 // you should give keyboard input at here. The cursor will wait for you when you run your program until you enter int value  as your age.
int age = s.nextInt();
// In here we convert our input to int value whether it is String .We can talk about these things further under  Wrapper Class topic
if (age>=18){
System.out.println("You are eligible for voting");
}else{
System.out.println("You are ineligible for voting");
}
}
}

If-Else-If statement

In here a different codes are executed if the condition fails again and again.

import java.util.Scanner;
public class IfElseIfExample{
public static void main(String[]args){
 Scanner s = new Scanner (System.in);
System.out.println("Enter your marks : ");
int marks = s.nextInt();
if ((marks<55 ) {
System.out.println("You have no grade");
}
else if ((marks>= 55) &&  (marks<65) ) {
System.out.println("Your grade is C");
}
else if ((marks>= 65) && (marks<75) ) {
System.out.println("Your grade is B");
}
else if ((marks>= 75) && (marks<=100) ) {
System.out.println("Your grade is A");
}
else ((marks>100 ) {
System.out.println("Invalid input");
}
}
}

Nested If Statement
In here we can see if block within another if block. Also you can use else part here.

import java.util.Scanner;
public class NestedIfExample{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
System.out.println("Enter your age : ");
System.out.println("Enter your weight : ");
 int age = s.nextInt();
int weight = s.nextInt();
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood ");
}else{
System.out.println("Your weight is not enough for donate blood");
}
else {
System.out.println("Your age is not enough  for donate blood");
}
}
}


For multiple selection you can use switch statement.

 In here if the value  of the control expression does not match any of the values then the default case is executed.

Switch  Statement

import java.util.Scanner;
public class SwitchExample{
public static void main(String[]args){

Scanner s = new Scanner(System.in);
     
                  System.out.println("enter value of the day");

                 int day = s.nextInt();

                 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");
                 }
}}



  • Repetition Structure
Sometimes we want to repeat certain  things many times.
ex: Printing a list of names.
      Generating a series of random numbers
Under this topic we can identify loops.Let's see  about them.

For Loop

for(initiate action; boolean expression;action after each iteration)
{Statements to be repeated ; }
 
Inside main method , try to get output of the following for loops.


ex 1 :             for(int i=0;i<5;i++){
                       System.out.println("loop "+i);
                        }


                        for(int i=5;i>0;i--){
                       System.out.println("loop "+i);
                       }


                        for(char ch='a';ch <='z';ch++){
                        System.out.println(ch);
                        }
     
    

                      int array[] ={34,67,78};
                    for(int i=0;i<array.length;i++){
                    System.out.println(array[i]);
                    }

While Loop

This one continually executes a block of statements  while a particular condition is true.

                     
                     int i=2;

                     while(i<7){
                     System.out.println("while loop " + i);
                         i++;
                       }



Do while Loop

 In here the statements within the do block  are always executed at least once.

                       int i=10;

                        do{
                        System.out.println("do while loop " + i);
                        i--;
                         }
                      while(i>0);
    

Break

This one is used to exit from loop.



                         for(int i=10;i>0;i--){
                         System.out.println("loop " +i);
                          if(i==5){
                         break;}
                           }

In above example it will print from loop 10 to loop 5 without others. Because we have put break when i ==5 . So loop will exit from that place.


Sunday, September 30, 2018

What is Java ?

Hello ! guys I am an undergraduate at  university of Moratuwa. Through this blog I am going to explain about java programming language and how to solve problems using it. Basically I suppose to present this series as short form manner. So, If there is someone who hope to participate an exam in near future he or she can catch up those things and memorize them easily .

Our topic is What is java?
Under this I am going to explain following things .

  1. History of  Java
  2. Features of Java
  3. JDK ,JRE and JVM
  4. Simple Java Program
  5.  Java variables
  6. Java Data Type
  7.  Java Operators
Before moving to history of java It is better t know about the history of programming languages.

What is programming?

It is series of instructions to a computer to accomplish a task.Programming languages are used to write programs.

What is  a programming language?

Set of commands for programming computers.

Programming language generations

1st generation

  • Machine level programming languages
  • Fast and efficient,executed directly on the cpu
  • Difficult for humans to read,write and debug

2nd generation
Assembly languages
  • Simple instructions
  • Assembler translates into machine code

3rd generation
High level,general purpose
  • Easier for humans to read,write.debug
  • compiler translates into machine code before running
  • Interpreter translates into machine code at run time

4th generation
Specification languages,query languages, report generators,system engineering


5th generation
Solve problems using rules/constraints rather than algorithms used in Artificial Intelligence


Programming language Paradigms


1.Procedural :procedures,sequential execution of code are  basic building blocks of program
ex: FORTRAN,Pascal,C
2. Object-Oriented :Program is designed around the objects required to solve the problem.
ex: Simula ,Smalltalk ,C++,Java,C#
3.Functional :Program is designed around the evaluation of functions
ex: Haskell
4.Logic : Program is declarative , based on mathematical logic
ex: Prolog
5.Scripting : used for text processing
ex: PHP,Python,Ruby


Steps of building a program

 1.Developing the algorithm
2. Writing the program
3.Documenting the program
4.Testing and debugging the program
           Alpha testing - Testing within the organization
           Beta testing - Testing by sophisticated users from outside the organization.


Object Oriented Languages(according to Alan kay)


Everything is an object. A program is a bunch of objects telling each other what to do, by sending
messages. each object has its own memory.Every object has a type(class). All objects of the same type can receive the same message.

1)What is Java?

 Java is an object -oriented programming language. But it is not  a pure OOP language.
Also it is  a platform.(java run time environment and API)

James Gosling has introduced this through Green Project.

Usage of Java

  • Desktop Applications (ex: media player,antivirus)
  • Web Applications (ex: banking applications)
  • Mobile
  • Smart Card
  • Games
Types of Java Application

1. Standalone Application (desktop/window-based applications)
2. Web applications (servlet,JSP,spring)
3.Enterprise Application(ex: banking application, in jave use EJB for this)
4.Mobile Application (Android and Java ME)


2) Characteristics Of  Java

  • Simple (based on c++ but very simpler than c++)
  • Object oriented
  • Distributed (allow network functionalities)
  • Robust (compile time and run time error handling)
  • Secure
  • Architecture -Natural (write once run anywhere) with JVM you  can write one program that will run on any platform .
  • Portable (programs can run on any platform without being recompiled)
 3) JDK

Java Development kit - tools needed to develop java programs

JRE   

Java run time environment  - to run programs
The target of the JRE is execution of java files/ Java development
JRE = JVM+Java package class (lang,math,util) +run time libraries

JRE contains  JVM class libraries and other supporting files. Doesn't contain any development tools(compiler,debugger etc)

Actually JRE is a set of software tools which are used for developing java apps used to provide run time environment. It is the implementation of the  JVM. It physically exist. Contains set of libraries and other files  that JVM uses at run time.

JDk =Tools+JRE
Tools = compiler (javac) + application launcher(java) +applet+viewer
  Here application launcher opens JRE , load class  and main method

Java  Code ---------->compiler -----------> Byte code

JDK is software development environment which is used to develop java apps and applets. 

JVM
 JVM runs programs . It uses classes , libraries and other supporting files provided  by JRE. IT is designed by sun micro systems.
 Byte code ---------->JVM ------------>machine code

Also JVM called  virtual (abstract machine - doesn't physically exist)........ It means write once run anywhere .
It provides machine interface which doesn't depend on platform (os, machine.hardware)

JVM  ,
  • loads code
  • verifies code
  • execute code
  • provide run time environment

Basic parts of Java Virtual Machine

  • A set of registers
  • A  stack
  • A garbage collected heap
  • An execution environment
  • An instruction set
  • A constant pool
  • A method storage area


MyProgram.java
-----------------------------------------
API
-----------------------------------------
JVM
----------------------------------------

Hardware -Based platform


API  -large collection of ready -made software components  that provide many useful  capabilities.

Source code ........>compiler ........> byte code......> interpreter ..........>screen
 x.java                       javac                   x.class            java



What is java byte code?

 It is the result of the compilation of a java program , an intermediate  representation of that program
 which is machine independent. Ii gets processed by the JVM.


5 ) Simple Java Program


  • One public class per source code file
  • Statement should terminated by semi colon
  • File name should similar to public class name
  • File may have many non public classes
  • Every java application should have main method and it  starts the program execution
  •  Class name should be  start with capital  and can use CamelCase for further purpose
  • Methods/variables should start with simple ( ex: methodName)
  • Constants shod be capital ( ex : CONSTANT_MAX)
  • Java is case sensitive.
  • There are reserved words in java. You can't use those words(keywords) as a class name,variable or method in java


package today1;

public class Today1 {
public static void main(String[] args) {
     System.out.println("Hello Uresha");
   
    }
 
}

output : Hello  Uresha

  • class keyword is used to declare a class in java
  • public keyword is an access modifier which represents visibility. (visible to all)
  • static is a keyword.(no need to create an object  to invoke  the static method)
  • void is return type of the method. It means it doesn't return any value.
  • main represents the starting point of the program
  • String[]args is used for command line argument.
  • System.out.println() is used to print statement. 


Difference between System.out.print() and System.out.println()

public class Test{
public static void main(String[] args){
System.out.println("Hello friends"); // This prints next line
System.out.print ("My name is  "); //  This prints in the same line 
System.out.print("uresha");

}
}

output
Hello friends
My name is uresha

5) Java Variables
A variable is a name of  memory location.(in RAM)
It should be declared before it used.
It has name and data type.
There are 3 types of variables in java. (local , instance and static )

Local Variables - declare inside  a method . visible only inside of the method.

Instance Variable - any variable which is defined in class body and outside  method's body and doesn't  have static modifier.

Static Variable (class variable) - use static modifier. Only copy of the variables shared with all instance of class




There are two stages in a variable.

1. Declare the variable.
ex: int x (here int is data type and x is variable name) 

2.Initialize  the variable (assigning value for it)

ex: int x= 10

Types of variable in java

ex:
public class A {
int  i =45; // instance variable
static int n = 100; //  static variable
void method (){
int a = 60; //local variable
}   
}


Write a java program to add two integers and get summation of those two numbers.

public class Sum{
public static void main(String[]args){
int x = 10;
int y =20;
System.out.println("The summation of two integers is :" +( x+ y));

}
}


6 )Data Types in  java

 Mainly there are two data types in java .
  • Primitive types - simple ,fixed sized
  • Reference types - complex 




According to above image there are 8 primitive data types in java. Out of the integer and  floating point are numeric and others are non numeric.

Specially "String " is not primitive in java.
Also you can see data type and it's size from bits as follows.
  •  byte  - 8
  • short - 16
  • int -32
  • long -64
  • float-32
  • double -64
  • char - 16
  • boolean -1    
Data conversion (assignment/promotion/type casting)

Widening Conversion(narrow to border /implicit casting )
In here value is converted from lower size data type to Upper size data type without loss of information.

ex:
 int a = 100;
double b = a;
System.out.println(b);

 Narrowing Conversion (explicit cast)
 In here value is converted from Upper size data type to Lower size data type with loss   of information.

ex: 

double a = 100;
int b = (int ) a;
System.out.println(b);

My next question is  "Is Java a pure object oriented  language"

No.

Java is not pure object oriented language . Because it supports primitive data types such as int, byte, long etc. to be used which are not objects. When we consider about pure object oriented language like smalltalk , there are no primitive types. Boolean , int and methods are all objects.

7. Java Operators

  • Unary -take one argument
  • Binary - take two arguments
  • Ternary - take three argument



 When we consider about the usage of    Unary  operators as follows.

*incrementing / decrementing a value by one

int x =12;
System.out.println(x );  //12
System.out.println(x ++); // 12 (post - increment )
System.out.println(x );   // 13
System.out.println( ++ x ); //14 (pre -increment)
System.out.println( -- x );  // 13 (pre - decrement)
System.out.println(x );  // 13
System.out.println(x --);  // 13  (post -decrement)
System.out.println(x );   //12

*boolean values

boolean a =true ;
boolean b = false;

System.out.println(a);  // true
System.out.println(b);  //false
System.out.println(!a);  // false
System.out.println(!b);  // true


Arithmetic Operators

int a = 10;
int b = 5 ;
System.out.println(a + b);  // 15  - addition
System.out.println(a - b);   // 5 - subtraction
System.out.println(a / b);   // 2 - division
System.out.println(a * b);  // 50 - multiplication
System.out.println(a % b);  // 0 - modulus

Left Shift Operator

System.out.println(20<<2);  //20 *2^2 =20*4 = 80
System.out.println(10<<3);  // 10 * 2^3 =10*8 =80

Right Shift Operator

System.out.println(20>>2);  //20/2^2 = 20/4 =5
System.out.println(80>>3);  // 80/2^3 = 80/8 =10

>> vs >>>

For positive numbers it works as same
System.out.println(20>>2 ); //  5
System.out.println(20>>>2 ); //  5

For negative number it works as different.Try with this

System.out.println(-20>>2 ); //  -5
System.out.println(-20>>>2 ); //  ?

Bitwise Operators

a   b       AND(a & b)            OR(a | b)                        XOR(a^ b)           
0   0               0                         0                                          0
0   1               0                         1                                          1
1   0               0                         1                                          1
1   1               1                         1                                          0


A                 0011  1100
B                 0000  1101

A& B          0000  1100
A | B           0011  1101
A^B            0011  0001

Logical Operators

&& - only check second condition if the first condition is true.
||     -  only check second if first is not true,


 int a =5 ,b = 8;
   if(a>3 &&  b>4) {
       System.out.println(" both conditions are correct");
   }
   if (a>10 && b>2){
     System.out.println("only second one correct");
   }

if (a>2 || b>5){
     System.out.println("both conditions are correct");
   }
if (a>2 || b>10){
     System.out.println("only first one is  correct");
   }
 
output

run:
both conditions are correct
both conditions are correct
only first one is  correct
BUILD SUCCESSFUL (total time: 0 seconds)


Difference between bitwise and logical operators (short -circuit )

From name you can guess bitwise operators at bit level and perform AND logical operation to each bit, while logical operators operate an boolean variables only.

Main difference is there short circuit behavior , which means  if there are two  or more conditions , which are joined using && , ||  operators then not all conditions are  tested.

Ternary Operator

int a =10;
int b=  3;
int max= (a>b)?a:b;
 System.out.println(max);

In here firstly check the condition(a>b) , then if it is true print a otherwise b.

Java Tokens





I hope to meet you with very essential part of java from next topic. Thank you guys !