0% found this document useful (0 votes)
16 views35 pages

Java Class

The document discusses key concepts in object-oriented programming (OOP) including classes, objects, inheritance, polymorphism, and encapsulation. It provides examples of classes like Motorcycle and objects like specific motorcycle models. Classes define attributes like color and behaviors like starting the engine. Inheritance allows classes to inherit attributes and behaviors from parent classes.

Uploaded by

kizahdanladi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views35 pages

Java Class

The document discusses key concepts in object-oriented programming (OOP) including classes, objects, inheritance, polymorphism, and encapsulation. It provides examples of classes like Motorcycle and objects like specific motorcycle models. Classes define attributes like color and behaviors like starting the engine. Inheritance allows classes to inherit attributes and behaviors from parent classes.

Uploaded by

kizahdanladi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

Java OOPs Concepts

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides
many concepts such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm where
everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities for example object, classes,
abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviours of a
parent object. It is an important part of OOPs (Object Oriented programming system).

1
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.

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.

Differences between Objects and Classes

No. Object Class


1) Object is an instance of a class. Class is a blueprint or template from
which objects are created.
2) Object is a real world entity such as Class is a group of similar objects.
pen, laptop, mobile, bed, keyboard, mouse,
chair etc.
3) Object is a physical entity. Class is a logical entity.

4) Object is created through new Class is declared using class


keyword mainly e.g. keyword e.g.
Student s1=new Student(); class Student{}

5) Object is created many times as per Class is declared once.


requirement.
6) Object allocates memory when it is Class doesn't allocated memory when
created. it is created.
7) There are many ways to create There is only one way to define class in
object in java such as new keyword, new java using class keyword.
Instance() method, clone() method, factory
method and deserialization.

2
Let's see some real life example of class and object in java to understand the difference well:

Class: Human

Object: Man, Woman

Class: Fruit

Object: Apple, Banana, Mango, Guava wtc.

Class: Mobile phone

Object: iPhone, Samsung, Moto

Class: Food

Object: Tuwo, Eba, Rice

Objects and Classes


Object-oriented programming is modeled on how, in the real world, objects are often made up of many kinds of
smaller objects. This capability of combining objects, however, is only one very general aspect of object-oriented
programming. Object-oriented programming provides several other concepts and features to make creating and
using objects easier and more flexible, and the most important of these features is that of classes.

A class is a template for multiple objects with similar features. Classes embody all the features of a particular set
of objects.When you write a program in an object-oriented language, you don’t define actual objects. You define
classes of objects.

An instance of a class is another word for an actual object. If classes are an abstract representation of an object,
an instance is its concrete representation. So what, precisely, is the difference between an instance and an object?
Nothing, really. Object is the more general term, but both instances and objects are the concrete representation
of a class. In fact, the terms instance and object are often used interchangeably in OOP language. An instance of a
tree and a tree object are both the same thing.

A class library is a set of classes

Behavior and Attributes


Every class you write in Java is generally made up of two components: attributes and behavior.
In this section, you’ll learn about each one as it applies to a theoretical class called Motorcycle.
3
Attributes
Attributes are the individual things that differentiate one object from another and determine the appearance,
state, or other qualities of that object. Let’s create a theoretical class called Motorcycle. The attributes of a
motorcycle might include the following:
Color: red, green, silver, brown
Style: cruiser, sport bike, standard
Make: Honda, BMW, Bultaco

Attributes of an object can also include information about its state; for example, you could have features for
engine condition (off or on) or current gear selected. Attributes are defined by variables; in fact, you can
consider them analogous to global variables for the entire object. Because each instance of a class can have
different values for its variables, each variable is called an instance variable.

Instance variables define the attributes of an object. The class defines the kind of attribute, and each instance
stores its own value for that attribute. Each attribute, as the term is used here, has a single corresponding
instance variable; changing the value of a variable changes the attribute of that object. Instance variables may be
set when an object is created and stay constant throughout the life of the object, or they may be able to change
at will as the program runs. In addition to instance variables, there are also class variables, which apply to the
class itself and to all its instances. Unlike instance variables, whose values are stored in the instance, class
variables’ values are stored in the class itself.

Behavior
A class’s behavior determines what instances of that class do when their internal state changes or when that
instance is asked to do something by another class or object. Behavior is the way objects can do anything to
themselves or have anything done to them. For example, to go back to the theoretical Motorcycle class, here are
some behaviors that the Motorcycle class might have:
Start the engine
Stop the engine
Speed up
Change gear
Stall

To define an object’s behavior, you create methods, which look and behave just like functions in other
languages, but are defined inside a class. Java does not have functions defined outside classes (as C++ does).

4
Methods are functions defined inside classes that operate on instances of those classes.
Methods don’t always affect only a single object; objects communicate with each other using methods as well. A
class or object can call methods in another class or object to communicate changes in the environment or to ask
that object to change its state. Just as there are instance and class variables, there are also instance and class
methods. Instance methods (which are so common they’re usually just called methods) apply and operate on an
instance; class methods apply and operate on a class (or on other objects).

Creating a Class
Up to this point, today’s lesson has been pretty theoretical. In this section, you’ll create a working example of the
Motorcycle class so that you can see how instance variables and methods are defined in a class. You’ll also
create a Java application that creates a new instance of the Motorcycle class and shows its instance variables.
Inheritance
Inheritance is one of the most crucial concepts in object-oriented programming, and it has a very direct effect on
how you design and write your Java classes. Inheritance is a powerful mechanism that means when you write a
class you only have to specify how that class is different from some other class, while also giving you dynamic
access to the information contained in those other classes. With inheritance, all classes—those you write, those
from other class libraries that you use, and those from the standard utility classes as well—are arranged in a
strict hierarchy .
Each class has a superclass (the class above it in the hierarchy), and each class can have one or more subclasses
(classes below that class in the hierarchy). Classes further down in the hierarchy are said to inherit from classes
further up in the hierarchy.
Variables

Recall that Java classes have only a single superclass, and they inherit variables and methods from that
superclass and all its superclasses. Although single inheritance makes the relationship between classes and the
5
functionality those classes implement easy to understand and to design, it can also be somewhat restricting—in
particular, when you have similar behavior that needs to be duplicated across different “branches” of the class
hierarchy. Java solves this problem of shared behavior by using the concept of interfaces.

An interface is a collection of method names, without actual definitions, that indicate that a class has a set of
behaviors in addition to the behaviors the class gets from its super classes.
Although a single Java class can have only one super class (due to single inheritance) that class can also
implement any number of interfaces. By implementing an interface, a class provides method implementations
(definitions) for the method names defined by the interface. If two very disparate classes implement the same
interface, they can both respond to the same method calls (as defined by that interface), although what each
class actually does in response to those method calls may be very different.

Packages in Java are a way of grouping together related classes and interfaces. Packages enable modular groups
of classes to be available only if they are needed and eliminate potential conflicts between class names in
different groups of classes.

Class: A template for an object, which contains variables and methods representing behavior and attributes.
Classes can inherit variables and methods from other classes.

Object: A concrete instance of some class. Multiple objects that are instances of the same class have access to the
same methods, but often have different values for their instance variables.

Instance: The same thing as an object; each object is an instance of some class.

Super class: A class further up in the inheritance hierarchy than its child, the subclass.

Subclass: A class lower in the inheritance hierarchy than its parent, the superclass. When you create a new
class, that’s often called sub classing.

Instance method: A method defined in a class, which operates on an instance of that class. Instance methods are
usually called just methods.

Class method: A method defined in a class, which can operate on the class itself or on any object.

Instance variable: A variable that is owned by an individual instance and whose value is stored in the instance.

6
Class variable: A variable that is owned by the class and all its instances as a whole, and is stored in the class.

Interface: A collection of abstract behavior specifications that individual classes can then implement.

Package: A collection of classes and interfaces. Classes from packages other than java.lang must be explicitly
imported or referred to by full package name.

History of Java

Java was originally designed for interactive television, but it was too advanced technology for the digital cable
television industry at the time. The history of java starts with Green Team. Java team members (also known
as Green Team), initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was suited for internet programming. Later, Java technology was incorporated by
Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured,
High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted and Dynamic".

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. There are
given the significant points that describe the history of Java.

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team. Firstly, it was called "Greentalk" by James Gosling, and file
extension was .gt. After that, it was called Oak and was developed as a part of the Green project. In 1995, Oak
was renamed as "Java" because it was already a trademark by Oak Technologies.

Features of Java

The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in
the popularity of this language. The features of Java are also known as java buzzwords.

A list of most important features of Java language is given below.

7
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Compile and Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

First Java Program | Hello World Example

In this page, we will learn how to write the simple program of java. We can write a simple hello java program
easily after installing the JDK.

To create a simple java program, you need to create a class that contains the main method. Let's understand the
requirement first.

The requirement for Java Hello World Example


For executing any java program, you need to

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the java program

8
o Compile and run the java program

Creating Hello World Example

Let's create the hello java program:

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

Test it Now

save this file as Simple.java

To compile: javac Simple.java

To execute: java Simple

Output:Hello Java

Compilation Flow:

When we compile Java program using javac tool, java compiler converts the source code into byte code.

Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

 class keyword is used to declare a class in java.


 public keyword is an access modifier which represents visibility. It means it is visible to all.
 static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main method is executed by the Java Virtual Machine (JVM) so it doesn't require to
create an object to invoke the main method. So it saves memory.
 void is the 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. We will learn it later.
 System.out.println() is used print statement. We will learn about the internal working of
System.out.println statement later.

9
Objects and Classes

When you write a computer program, you put it together from certain “building blocks”. In Java, you build
programs from objects. Each object has a particular behavior, and you can manipulate it to achieve certain
effects.

Classes
You encountered two objects:
• System.out
• “Hello, World!”
Each of these objects belongs to a different class. The System.out object belongs to the PrintStream class. The
“Hello, World!” object belongs to the String class. Of course, there are many more String objects, such as
“Goodbye” or “Mississippi”. They all have something in common––you can invoke the same methods on all
strings.
Using Objects
An object is an entity that you can manipulate by calling one or more of its methods.
A method consists of a sequence of instructions that can access the internal data of an object. When you call the
method, you do not know exactly what those instructions are, or even how the object is organized internally.
However, the behavior of the method is well defined, and that is what matters to us when we use it.

Java statements and expressions


A statement is the simplest thing you can do in Java; a statement forms a single Java operation.
All the following are simple Java statements:
int i = 1;
10
import java.awt.Font;
System.out.println(“This motorcycle is a “
+ color + “ “ + make);
m.engineState = true;

Statements sometimes return values—for example, when you add two numbers together or test to see whether
one value is equal to another. These kind of statements are called expressions. The most important thing to
remember about Java statements is that each one ends with a semicolon. Forget the semicolon and your Java
program won’t compile. Java also has compound statements, or blocks, which can be placed wherever a single
statement can. Block statements are surrounded by braces ({ }).

Variables and Data Types

A variable is a container which holds the value while the java program is executed. A variable is
assigned with a datatype.

Variable is a name of memory location. There are three types of variables in java: local, instance and
static.

There are two types of data types in java: primitive and non-primitive.

Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.

11
1. int data=50;//Here data is variable
1. int data=50;//Here data is variable

Types of Variables
There are three types of variables in java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

12
2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.

Example to understand the types of variables in java


1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class
1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class

Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java statement can go),
although they are most commonly declared at the beginning of the definition before they are used:

public static void main (String args []])


{
int count;
String title;
boolean isAsleep;
...
}

You can string together variable names with the same type:
int x, y, z;
String firstName, LastName;
13
You can also give each variable an initial value when you declare it:
int myAge, mySize, numShoes = 28;
String myName = “Laura”;
boolean isTired = true;
int a = 4, b = 5, c = 6;

If there are multiple variables on the same line with only one initializer (as in the first of the previous
examples), the initial value applies to only the last variable in a declaration. You can also group individual
variables and initializers on the same line using commas, as with the last example, above.

Local variables must be given values before they can be used (your Java program will not compile if you try to
use an unassigned local variable). For this reason, it’s a good idea always to give local variables initial values.
Instance and class variable definitions do not have this restriction (their initial value depends on the type of the
variable: null for instances of classes, 0 for numeric
variables, ‘\0’ for characters, and false for booleans).

Naming Convention in Java

Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc.

interface name should start with uppercase letter and be an adjective e.g. Runnable,
Remote, ActionListener etc.

method name should start with lowercase letter and be a verb e.g. actionPerformed(),
main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.

package name should be in lowercase letter e.g. java, lang, sql, util etc.

constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.

14
Declaring a Class
Line 4
begins a class declaration for class Welcome1. Every Java program consists of at least one class that you (the
programmer) define. The class keyword introduces a class declaration and is immediately followed by the
class name (Welcome1). Keywords (sometimes called reserved words) are reserved for use by Java and are
always spelled with all lowercase letters.
The complete list of keywords.
Class Names and Identifiers
By convention, class names begin with a capital letter and capitalize the first letter of each word they include
(e.g., SampleClassName). A class name is an identifier—a series of characters consisting of letters, digits,
underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces. Some valid
identifiers are Welcome1, $value, _value, m_inputField1 and button7. The name 7button is not a valid identifier
because it begins with a digit, and the name input field is not a valid identifier because it contains a space.
Normally, an identifier that does not begin with a capital letter is not a class name. Java is case sensitive—
uppercase and lowercase letters are distinct—so value and Value are different (but both valid) identifiers.
every class we define begins with the public keyword. For now, we simply require this keyword.
For our application, the file name is Welcome1.java.
We also have public and non-public classes.
A public class must be placed in a file that has the same name as the class (in terms of both spelling and
capitalization) plus the .java extension; otherwise, a compilation error occurs.
For example, public class Welcome must be placed in a file named Welcome.java.
A left brace {, begins the body of every class declaration. A corresponding right brace }, must end each class
declaration. Lines are indented in Java.

Using End-of-Line Comments on Right Braces for Readability


We include an end-of-line comment after a closing brace that ends a method declaration and after a closing
brace that ends a class declaration. For example, line 10 indicates the closing brace of method main, and line 11
15
indicates the closing brace of class Welcome1. Each comment indicates the method or class that the right brace
terminates.
Program 1

Program 2

Escape Sequence

16
Program 4:Displaying Text with printf

Operators in Java

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise ^
exclusive OR

bitwise inclusive |
OR
Logical logical AND &&

logical OR ||

17
Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<=


>>= >>>=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
18
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:

22
21

Java Unary Operator Example: ~ and !


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}

Output:

-11
9
false
true
19
Java Arithmetic Operators
Java arithmatic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.

Java Arithmetic Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression


1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}

Output:

20
21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.

Java Left Shift Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}

Output:

40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move left operands value to right by the number of bits
specified by the right operand.

Java Right Shift Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2

21
6. }}

Output:

2
5
2

Java Shift Operator Example: >> vs >>>


1. class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}

Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


The logical && operator doesn't check second condition if first condition is false. It checks second
condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false

22
7. System.out.println(a<b&a<c);//false & true = false
8. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}

Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}

Output:

false
10
false
11

23
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}

Output:

true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in java
programming. it is the only conditional operator which takes three operands.

24
Java Ternary Operator Example
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Another Example:

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Java Assignment Operator


Java assignment operator is one of the most common operator. It is used to assign the value on its
right to the operand on its left.

25
Java Assignment Operator Example
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}

Output:

14
16

Java Assignment Operator Example


1. class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}
1. class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);

26
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}

Output:

13
9
18
9

Java Assignment Operator Example: Adding short


1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}

Output:

Compile time error

After type cast:

1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
27
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}

Output:

20
Another Application: Adding Integers
Our next application reads (or inputs) two integers (whole numbers, such as –22, 7, 0 and 1024) typed by a
user at the keyboard, computes their sum and displays it. This program must keep track of the numbers
supplied by the user for the calculation later in the program.
Programs remember numbers and other data in the computer’s memory and access that data through program
elements called variables.

Program 4: Addition of Numbers

Import Declarations
28
These classes are grouped into Packages name groups of related classes and are collectively referred to as the
Java Class library or Java Application Programming Interface (Java API).

The above is am import declaration that helps the compiler locate a class that is used in this program.It
indicates that this example uses Java predefined Scanner class from java.util package.

Loops in Java

In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.

o for loop
o while loop
o do-while loop

Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.

There are three types of for loops in java.

o Simple For Loop


o For-each or Enhanced For Loop
o Labeled For Loop

Java Simple For Loop

29
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:

1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Syntax:

1. for(initialization;condition;incr/decr)
2. {
3. //statement or code to be executed
4. }

Flowchart:

Example:

1. //Java Program to demonstrate the example of for loop


2. //which prints table of 1
3. public class ForExample
4. {
5. public static void main(String[] args)
6. {
7. //Code of Java for loop
8. for(int i=1;i<=10;i++)
30
9. {
10. System.out.println(i);
11. }
12. }
}

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability
of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior of
the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}

31
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}

Can we overload java main() method?


Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's see the
simple example:

1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with String[]");}
3. public static void main(String args){System.out.println("main with String");}
4. public static void main(){System.out.println("main without args");}
5. }

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
4. //Java Program to demonstrate why we need method overriding
5. //Here, we are calling the method of parent class with child
6. //class object.
7. //Creating a parent class
8. class Vehicle{
9. void run(){System.out.println("Vehicle is running");}
10. }
32
11. //Creating a child class
12. class Bike extends Vehicle{
13. public static void main(String args[]){
14. //creating an instance of child class
15. Bike obj = new Bike();
16. //calling the method with child class instance
17. obj.run();
18. }
19. }

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late Binding).

33
Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

1. int data=30;

Here data variable is a type of int.

2) References have a type


1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }

3) Objects have a type


An object is an instance of particular java class,but it is also an instance of its superclass.

1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding

1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}

34
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding


1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
In the above example object type cannot be determined by the compiler, because the instance
of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.

35

You might also like