Differentiate Between & and && in Java Programming: If They Use As Logical AND

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

https://www.javatpoint.

com

1. Differentiate between & and && in java


programming

& <-- verifies both operands


&& <-- stops evaluating if the first operand evaluates to false since the
result will be false

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x >
1) then do the &. the problem is that for x=0 this will throw an exception.
(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is
true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe
and won't throw any exception if (x != 0) evaluates to false the whole thing
directly evaluates to false without evaluating the (1/x > 1).

For integer arguments, the single ampersand ("&")is the "bit-wise AND"
operator. The double ampersand ("&&") is not defined for anything but two
boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional)


"logical AND" operator while the double ampersand ("&&") is the "conditional
logical AND" operator. That is to say that the single ampersand always
evaluates both arguments whereas the double ampersand will only evaluate
the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should
occur.

There are two differences between & and &&.


If they use as logical AND
& and && can be logical AND, when the & or && left and right expression
result all is true, the whole operation result can be true.
when & and && as logical AND, there is a difference:
when use && as logical AND, if the left expression result is false, the right
expression will not execute.

Take the example :

String str = null;

if(str!=null && !str.equals("")){ // the right expression will not execute

}
If using &:
String str = null;
if(str!=null & !str.equals("")){ // the right expression will execute, and
throw the NullPointerException

}
An other more example:

int x = 0;
int y = 2;
if(x==0 & ++y>2){
System.out.print(“y=”+y); // print is: y=3
}

int x = 0;
int y = 2;
if(x==0 && ++y>2){
System.out.print(“y=”+y); // print is: y=2
}
& can be used as bit operator
& can be used as Bitwise AND operator, && can not.
The bitwise AND " &" operator produces 1 if and only if both of the bits in its
operands are 1. However, if both of the bits are 0 or both of the bits are
different then this operator produces 0. To be more precise bitwise AND " &"
operator returns 1 if any of the two bits is 1 and it returns 0 if any of the bits
is 0.

2. Define the following java terminologies


Classes and Objects in Java

Classes and Objects are basic concepts of Object Oriented Programming


which revolve around the real life entities.
Class
A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to
all objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers : A class can be public or has default access (Refer this for
details).
2. Class name: The name should begin with a initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented
by the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that
provides the state of the class and its objects, and methods are used to
implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications
such as nested classes, anonymous classes, lambda expressions.

Object
It is a basic unit of Object Oriented Programming and represents the real life
entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects
the response of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object
to interact with other objects.

Example of an object : dog

Objects correspond to things found in the real world. For example, a


graphics program may have objects such as “circle”, “square”, “menu”. An
online shopping system might have objects such as “shopping cart”,
“customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All
the instances share the attributes and the behavior of the class. But the
values of those attributes, i.e. the state are unique for each object. A single
class may have any number of instances.
Example :
Method Description
Properties() It creates an empty property list with no default
values.
Properties(Properties It creates an empty property list with the
defaults) specified defaults.

As we declare variables like (type name;). This notifies the compiler that we
will use name to refer to data whose type is type. With a primitive variable,
this declaration also reserves the proper amount of memory for the variable.
So for reference variable, type must be strictly a concrete class name. In
general, we can’t create objects of an abstract class or an interface.

Dog tuffy;

If we declare reference variable(tuffy) like this, its value will be


undetermined(null) until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object.

The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.

It can be used to get property value based on the property key. The
Properties class provides methods to get data from the properties file and
store data into the properties file. Moreover, it can be used to get the
properties of a system.

Constructors of Properties class

Methods of Properties class

The commonly used methods of Properties class are given below.

Method Description
public void load(Reader r) It loads data from the Reader
object.

public void load(InputStream is) It loads data from the InputStream


object

public void It is used to load all of the


loadFromXML(InputStream in) properties represented by the XML
document on the specified input
stream into this properties table.

public String getProperty(String It returns value based on the key.


key)

public String getProperty(String It searches for the property with


key, String defaultValue) the specified key.

public void setProperty(String key, It calls the put method of


String value) Hashtable.

public void list(PrintStream out) It is used to print the property list


out to the specified output stream.

public void list(PrintWriter out)) It is used to print the property list


out to the specified output stream.

public Enumeration<?> It returns an enumeration of all the


propertyNames()) keys from the property list.

public Set<String> It returns a set of keys in from


stringPropertyNames() property list where the key and its
corresponding value are strings.

public void store(Writer w, String It writes the properties in the writer


comment) object.

public void store(OutputStream It writes the properties in the


os, String comment) OutputStream object.

public void It writes the properties in the writer


storeToXML(OutputStream os, object for generating XML
String comment) document.

public void storeToXML(Writer w, It writes the properties in the writer


String comment, String encoding) object for generating XML document
with the specified encoding.

Example of Properties class to get information from the properties


file

To get information from the properties file, create the properties file first.

db.properties

1. user=system
2. password=oracle

An Advantage of the properties file

Recompilation is not required if the information is changed from a


properties file: If any information is changed from the properties file, you
don't need to recompile the java class. It is used to store information which
is to be changed frequently.

Methods in Java

A method is a collection of statements that perform some specific task and


return the result to the caller. A method can perform some specific task
without returning anything. Methods allow us to reuse the code without
retyping the code. In Java, every method must be part of some class which
is different from languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping
the code.
Method Declaration
In general, method declarations has six components :
 Modifier-: Defines access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 type of the access
specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in
its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible
within same class and package within which its class is defined.
 The return type : The data type of the value returned by the method
or void if does not return a value.
 Method Name : the rules for field names apply to method names as
well, but the convention is a little different.
 Parameter list : Comma separated list of the input parameters are
defined, preceded with their data type, within the enclosed parenthesis.
If there are no parameters, you must use empty parentheses ().
 Exception list : The exceptions you expect by the method can throw,
you can specify these exception(s).
 Method body : it is enclosed between braces. The code you need to be
executed to perform your intended operations.

Method signature: It consists of the method name and a parameter list


(number of parameters, type of the parameters and order of the
parameters). The return type and exceptions are not considered as part of it.
Method Signature of above function:
max(int x, int y)
How to name a Method?: A method name is typically a single word that
should be a verb in lowercase or multi-word, that begins with a verb in
lowercase followed by adjective, noun….. After the first word, first letter of
each word should be capitalized. For example, findSum,
computeMax, setX and getX
Generally, A method has a unique name within the class in which it is
defined but sometime a method might have the same name as other method
names within the same class as method overloading is allowed in Java.
Calling a method
The method needs to be called for using its functionality. There can be three
situations when a method is called:
A method returns to the code that invoked it when:
 It completes all the statements in the method
 It reaches a return statement
 Throws an exception

Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?

Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class
when you create a new class. You can use the same fields and
methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.

In the terminology of Java, a class which is inherited is called a parent or


superclass, and the new class is called child or subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee


is the superclass. The relationship between the two classes is Programmer
IS-A Employee. It means that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through
interface only. We will learn about interfaces later.

Encapsulation in Java

Encapsulation in Java is a process of wrapping code and data together


into a single unit, for example, a capsule which is mixed of several
medicines.

We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter methods to
set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.


Advantage of Encapsulation in Java

By providing only a setter or getter method, you can make the class read-
only or write-only. In other words, you can skip the getter or setter
methods.

It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the logic
inside the setter method. You can write the logic not to store the negative
numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and
setters. So, it is easy and fast to create an encapsulated class in Java.

Simple Example of Encapsulation in Java

Let's see the simple example of encapsulation that has only one field with its
setter and getter methods.

File: Student.java

1. //A Java class which is a fully encapsulated class.


2. //It has a private data member and getter and setter methods.
3. package com.javatpoint;
4. public class Student{
5. //private data member
6. private String name;
7. //getter method for name
8. public String getName(){
9. return name;
10. }
11. //setter method for name
12. public void setName(String name){
13. this.name=name
14. }
15. }

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract


class in Java. It can have abstract and non-abstract methods (method with
the body).
Before learning the Java abstract class, let's understand the abstraction in
Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing


only functionality to the user.

Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you type the text and send
the message. You don't know the internal processing about the message
delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can


have abstract and non-abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.

Points to Remember

o An abstract class must be declared with an abstract keyword.

o It can have abstract and non-abstract methods.

o It cannot be instantiated.

o It can have constructors and static methods also.

o It can have final methods which will force the subclass not to change
the body of the method.

Example of abstract class


1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.
Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

Polymorphism in Java

Polymorphism in Java is a concept by which we can perform a single


action in different ways. Polymorphism is derived from 2 Greek words: poly
and morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism


and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in


which a call to an overridden method is resolved at runtime rather than
compile-time.
In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting. For example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface
type. For Example:

1. interface I{}
2. class A{}
3. class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A
Object.

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor
class extends Bike class and overrides its run() method. We are calling the
run method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the
subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known
as runtime polymorphism.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
Test it Now

Output:

running safely with 60km.

Java Runtime Polymorphism Example: Bank

Consider a scenario where Bank is a class that provides a method to get the
rate of interest. However, the rate of interest may differ according to banks.
For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and
9.7% rate of interest.

Note: This example is also given in method overriding but there was no
upcasting.

1. class Bank{
2. float getRateOfInterest(){return 0;}
3. }
4. class SBI extends Bank{
5. float getRateOfInterest(){return 8.4f;}
6. }
7. class ICICI extends Bank{
8. float getRateOfInterest(){return 7.3f;}
9. }
10. class AXIS extends Bank{
11. float getRateOfInterest(){return 9.7f;}
12. }
13. class TestPolymorphism{
14. public static void main(String args[]){
15. Bank b;
16. b=new SBI();
17. System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
18. b=new ICICI();
19. System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
20. b=new AXIS();
21. System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
22. }
23. }
Test it Now

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

You might also like