You are on page 1of 211

SUBJECT :JAVA FUNDAMENTALS

SUBJECT CODE :20CS424


MODULE :I
PREPARED BY,

J.MYILVAHANAN
Semester – II
ASSISTANT PROFESSOR
Academic Year : 2020-2021(EVEN) DEPARTMENT CSE
HIT
COIMBATORE
COURSE OBJECTIVE

This course will enable students to,


 To understand Object Oriented Programming concepts and basic characteristics of Java
 To gain knowledge about basic Java language syntax and semantics to write Java programs and use
concepts such as variables, conditional and iterative execution methods etc.
 To understand the fundamentals of object-oriented programming in Java, including defining classes,
objects, invoking methods etc and exception handling mechanisms.
 To understand the principles of inheritance, packages and interfaces.
 To Understand the basics of Exception Handling & Multi threading and how to handle events
COURSE OUTCOME
 Understand Object Oriented Programming concepts to solve the problems
Demonstrate Java application programs using OOP principles and proper program structuring
Solve the inter-disciplinary applications using the concept of Inheritance
Demonstrate the concepts of Packages and inheritance
Analysis the error handling techniques using exception handling
Develop application using multi-threading and java swing
Syllabus
Unit I INTRODUCTION TO OOP
Introduction to OOP and its basic features, Classes, objects, data types,data members, abstraction, member
functions, Polymorphism, Types of Inheritance and Interface – JVM Architecture - Basics of Java
programming, Data types, Variables, Operators, Arrays.
Laboratory Sessions/ Experimental learning:
A professor in college will allow a student to be excused from the final exam if either of the following is
true:
• They have a 90% average or higher in the class and have missed 3 or less class lectures.
• They have a 80% average or higher in the class and have not missed any class lectures. The program
below will determine whether a student can get out of the exam or not. Rewrite the program so only one if
statement is used.
• Applications: Arrays in mathematical vectors, matrices.
• Video link / Additional online information (related to module if any): Differences between JVM vs
JRE vs JDK in Java:
• https://www.youtube.com/watch?v=5Bp6GLU6HKE
TEXT BOOKS:

1. Herbert Schildt, Java The Complete Reference, 7 /9th Edition, Tata McGraw Hill, 2007.

2. Core Java Volume-I Fundamentals, Eleventh Edition, Horstmann & Cornell, Pearson
Education.

REFERENCE BOOK
3. KEN ARNOLD, Java Programming Language, Addison Wesely, 2000

4. John R Hubbard, Programming with Java, Tata Mcgraw Hill, 1998

5. E Balagurusamy, Programming with Java A primer, Tata McGraw Hill companies


CONTENT
 INTRODUCTION TO OOPS

 FEATURES OF OOPS

 INTRODUCTION TO JAVA

 HISTORY OF JAVA

 VERSION OF JAVA

 BASIC OF JAVA

 DATA TYPE

 VARIABLE

 ARRAY

 OPERATOR
WHAT IS PROGRAMMING LANGUAGR

 A programming language is a vocabulary and set of grammatical rules for instructing a


computer or computing device to perform specific tasks. The term programming language
usually refers to high level language.
By
Vangie Beal
Why You Should Learn Java

 Java is Easy to Learn


 Java has a Large Community
 Java has an abundant API
 Java has multiple Open Source Libraries
 Java has Powerful Development Tools
 Java is Free of Cost
 Java is Platform Independent
 Java has great Documentation Support
 Java is Versatile
Difference between procedural and object oriented language
S.No Object Oriented Programming Procedural Oriented Programming
1 In object oriented programming, program is In procedural programming, program is
divided into small parts called objects. divided into small parts called functions.
2 Object oriented programming follows Procedural programming follows top down
bottom up approach approach.
3 Object oriented programming have access There is no access specifier in procedural
specifiers like private, public, protected etc. programming.
4 Adding new data and function is easy. Adding new data and function is not easy.
5 Object oriented programming provides data Procedural programming does not have any
hiding so it is more secure. proper way for hiding data so it is less secure.
6 In object oriented programming, data is In procedural programming, function is more
more important than function. important than data.
7 Object oriented programming is based on Procedural programming is based on unreal
real world. world.
8 C++, Java, Python,etc.. C, FORTRAN, Pascal,etc..
Difference between C and JAVA

 C is structure/procedure oriented programming language whereas Java is object oriented


programming language.
 C language program design is top down approach whereas Java is using bottom up approach.
 C language is middle level language whereas Java is high level language.
 Exception handling is not present in C programming language. Whereas exception handling is present
in Java.
 Polymorphism, virtual function, inheritance, Operator overloading, namespace concepts are not
available in C programming language. Whereas Java supports all these concepts and features.
Introduction
What is Java?

Java is a programming language and computing platform first released by Sun


Microsystems in 1995
Like any programming language, the Java language has its own structure, syntax rules, and
programming paradigm
The Java language's programming paradigm is based on the concept of OOP, which the
language's features support
 The Java language is a C-language derivative, so its syntax rules look much
like C's
History
 Java was developed by James Gosling, Patrick Naughton, Mike Sheridan at Sun Microsystems Inc.
in 1991. It took 18 months to develop the first working version.
 The initial name was Oak but it was renamed to Java in 1995 as OAK was a registered trademark
of another Tech company.
 Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995
Java Versions

 JDK Alpha and Beta (1995)  J2SE 1.4 (6th Feb, 2002)

 JDK 1.0 (23rd Jan, 1996)  J2SE 5.0 (30th Sep, 2004)

 JDK 1.1 (19th Feb, 1997)  Java SE 6 (11th Dec, 2006)

 J2SE 1.2 (8th Dec, 1998)  Java SE 7 (28th July, 2011)

 J2SE 1.3 (8th May, 2000)  Java SE 8 (18th March, 2014)


Features

 Simple  Portable
 Object-Oriented  Dynamic
 Platform independent
 Interpreted
 Secured
 High Performance
 Robust
 Multithreaded
 Architecture neutral
 Distributed
JAVA BYTE CODE
 There are a lot of processes that go on while a program in Java gets executed.
 One such concept is Bytecode in JAVA which is one of the reasons how JAVA becomes platform-
independent.
 ‘What is Bytecode in Java’ will help you in understanding Java Bytecode along with its working and
advantages.
What is Bytecode in Java?
 Bytecode in Java is the reason java is platform-independent, as soon as a Java program is compiled
bytecode is generated.
 To be more precise a Java bytecode is the machine code in the form of a .class file.
How does Bytecode Work

When a Java code is executed, the compiles that piece of code and a Source code

Bytecode is generated for each method in that program in the form of


Compiler
a .class file.
We can run this bytecode on any other platform as well. But the bytecode Bytecode

is a non-runnable code that requires or relies on an interpreter . This is


JVM
where JVM plays an important part.

Machine code
Advantages of Bytecode
 Following are a few advantages of Bytecode:
 It helps in achieving platform-independence which is one of the reasons why James Gosling started
the formation of java.
 The set of instructions for a JVM may differ from system to system but can all interpret Bytecode.
 Bytecodes are non-runnable codes that rely on the availability of an interpreter, this is where JVM
comes into play.
 It is a machine-level language code that runs on the JVM.
 It adds portability to Java which resonates with the saying, “write once, read anywhere”.
JDK,JRE and JVM
JDK [Java Development Kit]
 Java Development Kit contains two parts. One part contains the utilities like javac,
debugger, jar which helps in compiling the source code (.java files) into byte code (.class files) and
debug the programs
 The other part is the JRE, which contains the utilities like java which help in running/executing the
byte code. If we want to write programs and run them, then we need the JDK installed
 Java Compiler (javac): javac is the executable/application which compiles the .java source files into
the byte code (.class files). javac is included inJDK
JRE [Java Run-time Environment ]

 Java Run-time Environment helps in running the programs. JRE contains the JVM, the java
classes/packages and the run-time libraries
 If we do not want to write programs, but only execute the programs written by others,
then JRE alone will be sufficient
JVM [Java Virtual Machine]
 Java Virtual Machine is important part of the JRE, which actually runs the programs (.class files),
it uses the java class libraries and the run-time libraries to execute those programs
 Every operating system(OS) or platform will have a different JVM
 Just In Time Compiler (JIT): JIT is a module inside the JVM which helps in compiling certain
parts of byte code into the machine code for higher performance.
 Note that only certain parts of byte code will be compiled to the machine code, the other parts are
usually interpreted and executed
Java Program Execution

Java source file


Ex. one.java javac Bytecode JVM
Ram.java
Java Buzzwords
The following are Java buzzwords:
1. Simple
2. Object Oriented
3. Robust
4. Platform Independent
5. Portable
6. Multithreaded (Or Parallel Execution)
7. Distributed (Or Networking)
8. Secure
9. Dynamic
Simple
Java is a simple language because of the following reasons:
 Java is syntactically related to C++ which is a direct decedent from C (i.e., C++ is evolved from
C). Most of the syntax and characters are inherited from these two languages.
 Some of the most confusing concepts in C/C++ are either left out of java or implemented in a
cleaner way.
 For example: Pointers are completely eliminated from java. The disadvantage with pointers are
overriding memory and corrupting data. In java, the memory management is implemented in a
cleaner way using Garbage Collector (GC)
Object Oriented
 Java language follows Object Oriented Programming (OOP) paradigm.
 The OOP principles are Encapsulation, Inheritance, and Polymorphism.
 Every Program in java is an Object Oriented Program. Java is a fully object oriented language but
not pure object oriented language because of the existence of primitive data types. Small talk is a
pure object oriented language. Literally everything in smalltalk is an object.
Robust (Means Reliable)

 Java is intended for writing reliable programs. Java provides Exception Handling mechanism which
puts lots of emphasis on early checking for possible errors and dynamic checking.
 Java automatically handles Memory Management using Garbage collection. Java eliminates
pointers.
Platform Independent

 Write once, Run on any platform, Any time, Forever. Java is a platform independent language
because of the bytecode.
 The compiled bytecode is common across all operating systems (platforms).
 The Java source files are compiled to a bytecode, where as C/C++ source files are directly compiled
to a native code.
Platform Independent
Cont…
Portable

 The size of the primitive data types are fixed on all platforms.
 Also, binary data is stored in a fixed format, eliminating the “big endian | Little Endian”
confusion.
Parallel Execution ( or Multithreading)
 Reduces the execution time I,e., improves execution speed
Networking (Or Distributed)
 Java has become one of the most popular language for N/W programming due to two salient
features: Platform independent & Multithreading.
Secure
 Java provides several layers of protection from dangerous code, virus, Trojan horses.
 Java security is provided from the Java Architecture itself. Also, Java security can be provided using
security API.

Dynamic
 It was designed to adapt to an evolving environment.
Types of Java Applications

 Different ways to write/run a Java codes are:

 Application - A stand-alone program that can be invoked from command line . A program that
has a “MAIN” method

 Applet - A program embedded in a web page , to be run when the page is browsed . A program
that contains no “main” method
 Application -Java interpreter
 Applets- Java enabled web browser (Linked to HTML via <APPLET> tag. in html file)
Main Packages

 java.lang
 java.util
 java.io
 java.awt
 java.awt.image
 java.applet
 java.net
Object Oriented Languages -a Comparison
Objective C
Feature C++ Ada Java

Encapsulation Yes Yes Yes Yes


Inheritance Yes Yes No Yes
Multiple Inherit. Yes Yes No No
Polymorphism Yes Yes Yes Yes
Binding (Early/Late) Both Both Early Late
Concurrency Poor Poor Difficult Yes
Garbage Collection No Yes No Yes
Genericity Yes No Yes No
Class Libraries Yes Yes Limited Yes
Programming Paradigms
A programming paradigm is a style, or “way,” of programming.
Some Common Paradigms
 Imperative: Programming with an explicit sequence of commands that update state.
 Declarative: Programming by specifying the result you want, not how to get it.
 Structured: Programming with clean, goto-free, nested control structures.
 Procedural: Imperative programming with procedure calls.
 Functional (Applicative): Programming with function calls that avoid any global state.
 Function-Level (Combinator): Programming with no variables at all.
 Object-Oriented: Programming by defining objects that send messages to each other. Objects have
their own internal (encapsulated) state and public interfaces.
Programming Paradigms
 Object orientation can be:
 Class-based: Objects get state and behavior based on membership in a class.
 Prototype-based: Objects get behavior from a prototype object.
 Event-Driven: Programming with emitters and listeners of asynchronous actions.
 Flow-Driven: Programming processes communicating with each other over predefined channels.
 Logic (Rule-based): Programming by specifying a set of facts and rules. An engine infers the
answers to questions.
 Constraint: Programming by specifying a set of constraints. An engine finds the values that meet
the constraints.
 Aspect-Oriented: Programming cross-cutting concerns applied transparently.
 Reflective: Programming by manipulating the program elements themselves.
 Array: Programming with powerful array operators that usually make loops unnecessary.
Cont…
Programming paradigms

Imperative Programming Declarative


paradigms Programming paradigms

Procedural Programming Logic Programming


paradigms paradigms

Object oriented Functional programming


Programming

Parallel process Database process approach


approach
Imperative programming paradigm:

 Control flow in imperative programming is explicit: commands show how the computation takes
place, step by step. Each step affects the global state of the computation.
 It is one of the oldest programming paradigm.
 It features close relation to machine architecture.
 It is based on Von Neumann architecture.
 It works by changing the program state through assignment statements.
 It performs step by step task by changing state.
 The main focus is on how to achieve the goal.
 The paradigm consist of several statements and after execution of all the result is stored.
Imperative programming paradigm:

 Advantage:
 Very simple to implement
 It contains loops, variables etc.
 Disadvantage:
 Complex problem cannot be solved
 Less efficient and less productive
 Parallel programming is not possible
Declarative programming paradigm:

 Control flow in declarative programming is implicit: the programmer states only what the result
should look like, not how to obtain it.
 it is divided as Logic, Functional, Database. In computer science the declarative programming is a
style of building programs that expresses logic of computation without talking about its control flow.
It often considers programs as theories of some logic.
 It may simplify writing parallel programs. The focus is on what needs to be done rather how it
should be done basically emphasize on what code is actually doing.
 It just declare the result we want rather how it has be produced.
 This is the only difference between imperative (how to do) and declarative (what to do)
programming paradigms.
 Getting into deeper we would see logic, functional and database.
Quiz
1) Which of the following option leads to the portability and security of Java?
A. Use of exception handling B. The applet makes the Java code secure and portable
C. Byte code is executed by JVM Dynamic binding between objects
ANSWER : Bytecode is executed by JVM

2) Which of the following is not a Java features?


A. Dynamic B. Architecture Neutral C. Use of pointers D. Object-oriented
ANSWER : Use of pointers

3) _____ is used to find and fix bugs in the Java programs?


A. JVM B. JRE C. JDK D. JDB
ANSWER : JDB
Recalling topics

 Basic information about java


 Compression of PO and OOP
 Java,JAR,JVM

 Programming Paradigms
Object-oriented programming
 What is Object-oriented programming?
 The main aim of object-oriented programming is to implement real-world entities, for example,
object, classes, abstraction, inheritance, polymorphism, etc.
 OOP stands for Object-Oriented Programming.
 Procedural programming is about writing procedures or methods that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
methods.
 Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some concepts:
OBJECT-ORIENTED PROGRAMMING
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
 Coupling
 Cohesion
 Association
 Aggregation
 Composition
Object-oriented programming
Object
Object

 Any entity that has state and behavior is known as an object.


 For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
 An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or
code. The only necessary thing is the type of message accepted and the type of response returned by
the objects.
 Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors
like wagging the tail, barking, eating, etc.
Class

 In Java everything is encapsulated under classes. Class is the core of Java language.
 Class can be defined as a template/ blueprint that describe the behaviors /states of a particular entity.
 A class is declared using class keyword. A class contain both data and code that operate on that data.
 The data or variables defined within a class are called instance variables and the code that operates
on this data is known as methods
Rules for Java Class
 A class can have only public or default(no modifier) access specifier
 It can be either abstract, final or concrete (normal class)
 It must have the class keyword, and class must be followed by a legal identifier
 It may optionally extend one parent class. By default, it will extend java.lang.Object
 It may optionally implement any number of comma-separated interfaces.
 The class's variables and methods are declared within a set of curly braces {}
 Each .java source file may contain only one public class. A source file may contain any number of
default visible classes
 Finally, the source file name must match the public class name and it must have a .java suffix
Inheritance

 When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
 THE OOP, computer programs are designed in such a way where everything is an object that
interact with one another. Inheritance is one such concept where the properties of one class can be
inherited by the other.
 It helps to reuse the code and establish a relationship between different classes.
Inheritance
 As we can see in the image, a child inherits the properties from his father. Similarly, in Java, there
are two classes:
1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived class )
 A class which inherits the properties is known as Child Class whereas a class whose properties are
inherited is known as Parent class.
Inheritance
 Single Inheritance:
 In single inheritance, one class inherits the properties of another. It enables a derived class to
inherit the properties and behavior from a single parent class. This will in turn enable code
reusability as well as add new features to the existing code.
 Here, Class A is your parent class and Class B is your child class which inherits the properties and
behavior of the parent class.
Class A
{
---
}
Class B extends A {
---
}
Multilevel Inheritance:
 When a class is derived from a class which is also derived from another class, i.e. a class having
more than one parent class but at different levels, such type of inheritance is called Multilevel
Inheritance.
 class B inherits the properties and behavior of class A and class C inherits the properties of class B.
Here A is the parent class for B and class B is the parent class for C. So in this case class C
implicitly inherits the properties and methods of class A along with Class B. That’s what is
multilevel inheritance.
Multilevel Inheritance:

Class A
{
---
}
Class B extends A
{
---
}
Class C extends B
{
---
}
Hierarchical Inheritance:
 When a class has more than one child classes (sub classes) or in other words, more than one child
classes have the same parent class, then such kind of inheritance is known as hierarchical.
 If we talk about the flowchart, Class B and C are the child classes which are inheriting from the
parent class i.e Class A. Class A{
---
}
Class B extends
A{
---
}
Class C extends
A{
---
}
Hybrid Inheritance:
 Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance. Since
multiple inheritance is not supported in Java as it leads to ambiguity, so this type of inheritance can
only be achieved through the use of the interfaces.
 If we talk about the flowchart, class A is a parent class for class B and C, whereas Class B and C
are the parent class of D which is the only child class
Polymorphism
 If one task is performed in different ways, it is known as polymorphism. For example: to convince
the customer differently, to draw something, for example, shape, triangle, rectangle, etc.
 In Java, we use method overloading and method overriding to achieve polymorphism.
 Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Polymorphism
 Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. It
is the ability of a variable, function or object to take on multiple forms. In other words,
polymorphism allows you define one interface or method and have multiple implementations.
 Polymorphism in Java is of two types:
 Run time polymorphism
 Compile time polymorphism
 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.
Polymorphism
 Let’s understand this by taking a real-life example and how this concept fits into Object oriented
programming.
Encapsulation
 Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
 A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
 Encapsulation is a mechanism where you bind your data and code together as a
single unit. It also means to hide your data in order to make it safe from any
modification.
 What does this mean? The best way to understand encapsulation is to look at the
example of a medical capsule, where the drug is always safe inside the capsule.
Similarly, through encapsulation the methods and variables of a class are well
hidden and safe.
Abstraction
 Hiding internal details and showing functionality is known as abstraction.
 For example phone call, we don't know the internal processing.
 In Java, we use abstract class and interface to achieve abstraction.
Abstraction
 Hiding internal details and showing functionality is known as abstraction.

 For example phone call, we don't know the internal processing.

 In Java, we use abstract class and interface to achieve abstraction.

 Abstraction refers to the quality of dealing with ideas rather than events.

 It basically deals with hiding the details and showing the essential things to the user. If you look
at the image here, whenever we get a call, we get an option to either pick it up or just reject it.

 But in reality, there is a lot of code that runs in the background. So you don’t know the internal
processing of how a call is generated, that’s the beauty of abstraction.
Abstraction
 Therefore, abstraction helps to reduce complexity. You can achieve abstraction in two ways:
 a) Abstract Class
 b) Interface
Abstract class:
Abstract class in Java contains the ‘abstract’ keyword. Now what does the abstract keyword mean? If a
class is declared abstract, it cannot be instantiated, which means you cannot create an object of an
abstract class. Also, an abstract class can contain abstract as well as concrete methods.
Interface: Interface in Java is a blueprint of a class or you can say it is a collection of abstract methods
and static constants. In an interface, each method is public and abstract but it does not contain any
constructor. Along with abstraction, interface also helps to achieve multiple inheritance in Java
QUIZ
1) Which statement is true regarding an object?
A) An object is what classes instantiated are from B) An object is an instance of a class
C) An object is a variable D) An object is a reference to an attribute
ANSWER : An object is an instance of a class
2) In object-oriented programming, new classes can be defined by extending existing classes.
This is an example of:
A)Encapsulation B) Interface C) Composition D) Inheritance
ANSWER : Inheritance

3) Object-oriented inheritance models the


A) “is a kind of” relationship B) “has a” relationship C) “want to be” relationship
D) “contains” of relationship
ANSWER : “is a kind of” relationship
Recalling topics
Basic oops concepts
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC
Simple JAVA Program
 Creating a Hello World Program in Java is not a single line program.
 It consists of various other lines of code. Since Java is a Object-oriented language so it require to
write a code inside a class.
 Let us look at simple java program.

class Hello

public static void main(String[] args)

System.out.println ("Hello World java program");

}

Cont…
 Lets understand what above program consists of and its keypoints.
 class : class keyword is used to declare classes in Java
 public : It is an access specifier. Public means this function is visible to all.
 static : static is again a keyword used to make a function static. To execute a static function you do
not have to create an Object of the class. The main() method here is called by JVM, without
creating any object for class.
 void : It is the return type, meaning this function will not return anything.
Cont…

 main : main() method is the most important method in a Java program. This is the method which is
executed, hence all the logic must be inside the main() method. If a java class is not having a main()
method, it causes compilation error.
 String[] args : This represents an array whose type is String and name is args. We will discuss more
about array in Java Array section.
 System.out.println : This is used to print anything on the console like printf in C language.
Steps to Compile and Run your first Java program

Step 1: Open a text editor and write the code as above.


Step 2: Save the file as Hello.java
Step 3: Open command prompt and go to the directory where you saved your first java program
assuming it is saved in C drive.
Step 4: Type javac Hello.java and press Return(Enter KEY) to compile your code. This command will
call the Java Compiler asking it to compile the specified file. If there are no errors in the code the
command prompt will take you to the next line.
Step 5: Now type java Hello on command prompt to run your program.
Step 6: You will be able to see Hello world program printed on your command prompt.
Simple Java programs
 BASIC STRUCTURE OF JAVA PROGRAM.
 A Java program involves the following sections:
Documentation Section
Package Statement
Import Statements
Interface Statement
Class Definition
Main Method Class
Main Method Definition
BASIC STRUCTURE OF JAVA PROGRAM
Section Description
You can write a comment in this section. Comments are beneficial for the
Documentation programmer because they help them understand the code. These are optional, but
Section we suggest you use them because they are useful to understand the operation of
the program, so you must write comments within the program.
You can create a package with any name. A package is a group of classes that are
defined by a name. That is, if you want to declare many classes within one
element, then you can declare it within a package. It is an optional part of the
Package
program, i.e., if you do not want to declare any package, then there will be no
statement
problem with it, and you will not get any errors. Here, the package is a keyword
that tells the compiler that package has been created. It is declared as:
package package_name;
This line indicates that if you want to use a class of another package, then you can
Import do this by importing it directly into your program.
statements import calc.add;
BASIC STRUCTURE OF JAVA PROGRAM

Interfaces are like a class that includes a group of method declarations. It's an
Interface
optional section and can be used when programmers want to implement multiple
statement
inheritances within a program.
A Java program may contain several class definitions. Classes are the main and
Class Definition
essential elements of any Java program.
Every Java stand-alone program requires the main method as the starting point of the
Main Method program. This is an essential part of a Java program. There may be many classes in a
Class Java program, and only one class defines the main method. Methods contain data
type declaration and executable statements.
CONT…
//Name of this file will be
"Hello.java"
public class Hello
{
OUTPUT
public static void main(String[] Hello Java
args)
{
System.out.println("Hello Java");
}
}
CONT…
Here are the most important points to note about the Java programs:
 You have to keep in mind that, Java code is case sensitive.
 To write a Java program, you must have to define class first.
 The name of the class in Java (which holds the main method) is the name of the Java program, and
the same name will be given in the filename. As mentioned above in the sample program; The
name of the class is "Hello" in which the main method is, then this file will be named "Hello.Java".
VARIOUS PART OF JAVA PROGRAM
 This creates a class called Hello.
public class
 All class names must start with a capital letter.
Hello
 The public word means that it is accessible from any other classes.
The compiler ignores comment block. Comment can be used anywhere in the
/* Comments
program to add info about the program or code block, which will be helpful for
*/
developers to understand the existing code in the future easily.
Two curly brackets {...} are used to group all the commands, so it is known that the
Braces
commands belong to that class or method.
VARIOUS PART OF JAVA PROGRAM

When the main method is declared public, it means that it can also be used by code outside
of its class, due to which the main method is declared public.
 The word static used when we want to access a method without creating its object, as
public
we call the main method, before creating any class objects.
static
 The word void indicates that a method does not return a value. main() is declared as void
void
because it does not return a value.
main
 main is a method; this is a starting point of a Java program.
 You will notice that the main method code has been moved to some spaces left. It is
called indentation which used to make a program easier to read and understand.
VARIOUS PART OF JAVA PROGRAM

This statement is used to print text on the screen as output, where the system is a predefined
System.
class, and out is an object of the PrintWriter class defined in the system. The
out.pri
method println prints the text on the screen with a new line. You can also use print() method
ntln();
instead of println() method. All Java statement ends with a semicolon.

It is an array where each element of it is a string, which has been named as "args". If your
String[]
Java program is run through the console, you can pass the input parameter, and main()
args
method takes it as input.
How to Create First Java Program
• Steps to Compile and Run first Java program
• Step 1) Open Notepad from Start menu by selecting Programs > Accessories > Notep
CONT…
 Step 2) Create a Source Code for your Program
 Declare a class with name A.
 Declare the main method public static void main(String args[]){
 Now Type the System.out.println("Hello World"); which displays the text Hello World.
CONT…
Step 3) Save the file as FirstProgram.java make sure to select file type as all files while saving the file
in our working folder C:\workspace
CONT…
Step 4) Open the command prompt. Go to Directory C:\workspace. Compile the code using
command, javac FirstProgram.java
CONT…
Step 5) If you look in your working folder, you can see that a file named A.class has been created.
CONT…
Step 6) To execute the code, enter the command java followed by the class name, as expected output
Hello World is displayed now.
 java A
 Note: Java is case sensitive Programming language. All code, commands, and file names should
is used in consistent casing. FirstProgram is not same as firstprogram.
CONT…
Step 7) If you copy and paste the same code in IDE like Eclipse the compiling and execution is done
with the click of a button Using IDE is convenient and improves your efficiency but since you are
learning Java, we recommend you stick to notepad.
Setting path
There are two ways to set the path in Java:
• Temporary
• Permanent
How to set the Temporary Path of JDK in Windows
• To set the temporary path of JDK, you need to follow the following steps:
• Open the command prompt
• Copy the path of the JDK/bin directory
• Write in command prompt: set path=copied_path
For Example:
- set path = C:\Program Files\Java\jdk1.6.0_23\bin
CONT…
SIMPLE JAVA PROGRAMS
Display message on computer screen.
Public class First
{
public static void main(String[] arguments)
{
System.out.println("Let's do something using Java
technology.");
}
}
SIMPLE JAVA PROGRAMS
Public class Integers
{
public static void main(String[] arguments)
{
int g;
for (g = 1; g <= 10; g++)
{
System.out.println(g);
}
}
}
SIMPLE JAVA PROGRAMS

Public class ifCondition


{
public static void main(String[] args)
{
boolean raman = true; Output
MVJ Java programmer
if (raman) {
System.out.println(“MVJ Java programmer");
}
else {
System.out.println("What are you doing here in MVJ?");
}
}
}
SIMPLE JAVA PROGRAMS
class Alphabets
{
public static void main(String args[])
{
char x;

for (x = 'a'; x<= 'z'; x++)


// For upper case use 'A' and 'Z'
System.out.println(x);
}
}
To find or calculate the area of a triangle
import java.util.Scanner;
Public class AreaOfTriangle
{ public static void main(String args[])
{ Output
Scanner s= new Scanner(System.in); Enter the width of the Triangle:10
System.out.println("Enter the width of the Triangle:"); Enter the height of the
double b= s.nextDouble(); Triangle:20
Area of Triangle is:100.0
System.out.println("Enter the height of the Triangle:");
double h= s.nextDouble();
//Area = (width*height)/2
double area=(b*h)/2;
System.out.println("Area of Triangle is: " + area);
}}
Recalling topics

 Basic structure about java


 File creation of Java, save, compile and execution
 Setting path to program
 Different parts in java program

 Sample java Program.


JAVA DATA TYPES
 Data type specifies the size and type of values that can be stored in an identifier. The Java language
is rich in its data types.
 Different data types allow you to select the type appropriate to the needs of the application.
Data types in Java are classified into two types:
 Primitive—which include Integer, Character, Boolean, and Floating Point.
 Non-primitive—which include Classes, Interfaces, and Arrays.
 Primitive Data Types: A primitive data type is pre-defined by the programming language. The size
and type of variable values are specified, and it has no additional methods.
 Non-Primitive Data Types: These data types are not actually defined by the programming language
but are created by the programmer. They are also called “reference variables” or “object references”
since they reference a memory location which stores the data.
JAVA DATA TYPES

Type Size Range of values that can be stored


byte 1 byte −128 to 127
short 2 bytes −32768 to 32767
int 4 bytes −2,147,483,648 to 2,147,483,647
9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807
float 4 bytes 3.4e−038 to 3.4e+038
double 8 bytes 1.7e−308 to 1.7e+038
Boolean Data Type
 A Boolean data type comprises of a bit of information and can store only true or false values. This
data type is used to track true/false conditions. Now let’s write a small program and understand how
it works. public class boolDataType
{
public static void main(String args[])
{
// Setting the values for boolean data type
boolean Java = true;
boolean Python = false;
System.out.println(Java); // Output will
be true
System.out.println(Python); // Output
will be false
}}
Byte data type
 It is an 8-bit signed two’s complement integer. It stores whole numbers that lie between -128 to 127.
A byte data type is helpful for saving memory in large amounts.
Public class ByteExample
{
public static void main(String[] args)
{
byte n, a;
n = 127;
a=177;
System.out.println(n); // prints 127
System.out.println(a);
// throws an error because it cannot store more than
127 bits
}
}
Char data type

 This data type is used to store a single character. The character must be enclosed within single
quotes, like ‘E’ or ‘e’.
 Alternatively, you can also use ASCII values to display certain characters

char alpha = 'J';


char a = 65, b = 66, c = 67;
System.out.println(alpha); // prints J
System.out.println(a); // Displays 65
System.out.println(b); // Displays 66
System.out.println(c); // Displays 67
short data type
 A short data type is greater than byte in terms of size and less than a integer.
 It stores the value that ranges from -32,768 to 32767. class ShortExample {

 The default size of this data type: 2 bytes. public static void main(String[] args)
{
short n= 3435,
System.out.println(n);
// prints the value present in n i.e. 3435
}
}
int data type

 This data type can store whole numbers from -2147483648 to 2147483647.
 Generally, int is the preferred data type when you create variables with a numeric value.

int num = 5464564;


System.out.println(num); // prints 5464564
long data type

 his data type is a 64-bit two’s complement integer. By default, the size of a long data type is 64 bit
and its value ranges from -263 to 263-1

long num = 15000000000L;


System.out.println(num); // prints 15000000000
Floating Data types

float data type


 This data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value
with an “f”. Let’s take a small example and understand this data type in a detailed manner.

float num =67;


System.out.println(num); // prints the floating number value
double data type

 The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
 Note that you should end the value with a “d”:

double num = 79.678d;


System.out.println(num); // prints double value

 That was all about Double data type and this brings us to the end of Primitive Datatypes.
 Now let’s figure out the difference between primitive and non-primitive data types.
Non-Primitive Data types
Non –primitive data type
String

Array

Classes
Interfaces

Strings: String is a sequence of characters. But in Java, a string is an object that represents a sequence
of characters. The java.lang.String class is used to create a string object. If you wish to know more
about Java Strings, you can refer to this article on String in java.
CONT…
 Arrays: Arrays in Java are homogeneous data structures implemented in Java as objects. Arrays
store one or more values of a specific data type and provide indexed access to store the same. A
specific element in an array is accessed by its index. If you wish to learn Arrays in detail, then
kindly check out this article on java arrays .
 Classes: A Classes in javais a blueprint which includes all your data. A class contains
fields(variables) and methods to describe the behavior of an object.
 Interface: Like a class, an interface can have methods and variables, but the methods declared
in interface are by default abstract (only method signature, no body).
Difference between primitive and non-primitive data types
The difference between primitive and non-primitive data types are as follows:
 Primitive types are predefined in Java. Non-primitive types are created by the programmer and is not
defined by Java.
 Non Primitive types can be used to call methods to perform certain operations, while primitive types
cannot.
 A primitive type always has a value, whereas non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types start with an uppercase
letter.
 The size of a primitive type depends on the data type, while non-primitive types have all the same
size.
Summary

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127


short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
Stores whole numbers from -9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values
Example
Public class raman {
public static void main(String args[])
{
char a = 'G';
int i = 89;
byte b = 4;
short s = 56; Output:
double d = 4.355453532; char: G
float f = 4.7333434f; integer: 89
System.out.println("char: " + a); byte: 4
System.out.println("integer: " + i); short: 56
System.out.println("byte: " + b); float: 4.7333436
System.out.println("short: " + s); double: 4.355453532
System.out.println("float: " + f);
System.out.println("double: " + d);
}
}
Example

Public class ByteExample


Public class BooleanExample
{
{
public static void main(String[] args)
public static void main(String[] args)
{ {
boolean flag = true;
byte range;
System.out.println(flag);
range = 124;
}
} System.out.println(range);

}}
Example
class DoubleExample
{
public static void main(String[] args)
{
Output:
char myChar = ‘G'; G
Java 7
char newLine = '\n';
String myString = "Java 7";
System.out.println(myChar);
System.out.println(newLine);
System.out.println(myString);
}}
Example
Public class DoubleExample
{
public static void main(String[] args)
{ Output
double myDouble = 3.4;
3.4
float myFloat = 3.4F; // 3.445*10^2 double 3.4
myDoubleScientific = 3.445e2; 344.5
:
System.out.println(myDouble);
System.out.println(myFloat);
System.out.println(myDoubleScientific); }
}
QUIZ
1. What is the range of short data type in Java?
a) -128 to 127 b) -32768 to 32767 c) -2147483648 to 2147483647 d) None of the mentioned
Answer: b - -32768 to 32767

2. Which data type value is returned by all transcendental math functions?


a) int b) float c) double d) long
Answer: c) double

3. Which of these values can a boolean variable contain?


a) true & false b) 0&1 c) true d) any integer value
Answer: a) true & false
Recalling topics
 What is data and data type?

 Basic data type in java

 Primitive data type

 Non primitive data type

 Sample program and execution

 Example Program.

Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC
Java Variables
 A variable is a name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable effects
that memory location.
 In Java, all the variables must be declared before use.

What is a Variable?
A variable can be thought of as a container which holds value for you, during the life of a Java
program. Every variable is assigned a data type which designates the type and quantity of value it
can hold.
Declaring (Creating) Variables
In order to use a variable in a program you to need to perform 2 steps

1.Variable Declaration
2.Variable Initialization

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:
Syntax
type variable_NAME = value;
 Where type is one of Java's types (such as int or String), and
variable is the name of the variable (such as x or name).
 The equal sign is used to assign values to the variable.
Example
 Create a variable called name of type String and assign it the value "John":
String name = "John";
System.out.println(name);
 Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
System.out.println(myNum);
 Declare a variable without assigning the value, and assign the value later:
int myNum = 15;
int myNum; myNum = 20;
myNum = 15; // myNum is now 20
System.out.println(myNum);
System.out.println(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value :
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.

int data=50;//Here data is variable


Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
Variable Initialization:

Example of other Valid Initializations are


pi =3.14f;
do =20.22d;
a=’v’;
Declare Many Variables
 We can combine variable declaration and initialization

Example :
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;
RULES FOR VARIABLE DECLARATION IN JAVA

 A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and two special

characters such as underscore and dollar Sign.

 The first character must be a letter.

 Blank spaces cannot be used in variable names.

 Java keywords cannot be used as variable names.

 Variable names are case-sensitive.


Rules for naming variables:
 All variable names must begin with a letter of the alphabet, an underscore, or ( _ ), or a dollar sign
($).
 The convention is to always use a letter of the alphabet. The dollar sign and the underscore are
discouraged.
 After the first initial letter, variable names may also contain letters and the digits 0 to 9. No spaces or
special characters are allowed.
 The name can be of any length, but don't get carried away. Remember that you will have to type this
name.
 Uppercase characters are distinct from lowercase characters. Using ALL uppercase letters are
primarily used to identify constant variables. Remember that variable names are case-sensitive.
 You cannot use a java keyword (reserved word) for a variable name.
Types of Variables/ Scope Of Variables In Java

There are three types of variables in Java:


 local variable
 instance variable
 static variable
TYPES OF VARIABLES
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.
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
Local Variables:
 A variable defined within a block or method or constructor is called local variable.
 These variable are created when the block in entered or the function is called and destroyed after exiting
from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is declared. i.e. we can
access these variable only within that block.
 Initialization of Local Variable is Mandatory.
Example
public class StudentDetails
Public class A
{ public void StudentAge()
{ {
// local variable age
int data=50;//instance variable
int age = 0;
static int m=100;//static variable age = age + 5;
System.out.println("Student age is : " + age);
void method() }
{ public static void main(String args[])
{
int n=90;//local variable StudentDetails obj = new StudentDetails();
} obj.StudentAge();
}
}//end of class }

Student age is : 5
Instance Variables
 Instance variables are non-static variables and are declared in a class outside any method,
constructor or block.
 As instance variables are declared in a class, these variables are created when an object of the class
is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables.
 If we do not specify any access specifier then the default access specifier will be used.
 Initialization of Instance Variable is not Mandatory.
 Its default value is 0
 Instance Variable can be accessed only by creating objects.
Sample Program:
import java.io.*;
Public class Marks
{
// These variables are instance variables.
// These variables are in a class
// and are not inside any function
int engMarks;
int mathsMarks;
int phyMarks;
}
class MarksDemo
{
public static void main(String args[])
{ // first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;
CONT…
// second object
Marks obj2 = new Marks();
obj2.engMarks = 80;
obj2.mathsMarks = 60;
obj2.phyMarks = 85; Output:
// displaying marks for first object Marks for first object:
System.out.println("Marks for first object:"); 50
System.out.println(obj1.engMarks); 80
System.out.println(obj1.mathsMarks); 90
System.out.println(obj1.phyMarks); Marks for second object:
// displaying marks for second object 80
System.out.println("Marks for second object:"); 60
System.out.println(obj2.engMarks); 85
System.out.println(obj2.mathsMarks);
System.out.println(obj2.phyMarks);
}
}
Static Variables
 Static variables are also known as Class variables. These variables are declared similarly as instance
variables, the difference is that static variables are declared using the static keyword within a class
outside any method constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class irrespective of how
many objects we create.
 Static variables are created at the start of program execution and destroyed automatically when
execution ends.
 Initializations of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like Instance variable (through an object), the compiler will show the
warning message and it won’t halt the program. The compiler will replace the object name to class
name automatically.
CONT…
 If we access the static variable without the class name, Compiler will automatically append the class
name.
 To access static variables, we need not create an object of that class, we can simply access the
variable as
class_name.variable_name;
Sample Program:
import java.io.*;
class Emp
{
// static variable salary
public static double salary;
public static String name = “Raman";
}
public class EmpDemo
Raman average salary:100000.0
{
public static void main(String args[])
{
// accessing static variable without object
Emp.salary = 100000;
System.out.println(Emp.name + "'s average salary:"+ Emp.salary);
}
}
Instance variable Vs Static variable
 Each object will have its own copy of instance variable whereas We can only have one copy of a static
variable per class irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other objects as each
object has its own copy of instance variable. In case of static, changes will be reflected in other
objects as static variables are common to all object of a class.
 We can access instance variables through object references and Static Variables can be accessed
directly using class name.
 Syntax for static and instance variables: class Example
{ static int a;
int b; //instance
variable
}
Sample Program:
class A
{
int amount = 100;
//instance variable static int pin = 2315;
//static variable public static void main(String[] args)
{
int age = 35;
//local variable
}
}
Sample Program:
public class Example Example eg = new Example();
{ int salary; // Instance Variable eg.show();
public void show() }
}
{
int value = 2;// Local variable
value = value + 10;
System.out.println("The Value is : " + value);
salary = 10000;
System.out.println("The salary is : " + salary);
} public static void main(String args[])
{
Display Variables

 The println() method is often used to display variables.


 To combine both text and a variable, use the + character:
Example
String name = "John";
System.out.println("Hello " + name);
You can also use the + character to add a variable to another variable:

Example
String firstName = "John "; String lastName = "Doe";
String fullName = firstName + lastName; System.out.println(fullName);
CONT…
 For numeric values, the + character works as a mathematical operator (notice that we use int (integer)
variables here):
Example
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y

 From the example above, you can expect:


 x stores the value 5
 y stores the value 6
 Then we use the println() method to display the value of x + y, which is 11
Java Identifiers

All Java variables must be identified with unique names.


 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
 Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:

Example
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
Rules for constructing names for variables are:

 Names can contain letters, digits, underscores, and dollar signs

 Names must begin with a letter

 Names should start with a lowercase letter and it cannot contain whitespace

 Names can also begin with $ and _ (but we will not use it in this tutorial)

 Names are case sensitive ("myVar" and "myvar" are different variables)

 Reserved words (like Java keywords, such as int or boolean) cannot be used as names
QUIZ
1) Which of these can be returned by the operator &?
a) Integer b) Boolean c) Character d) Integer or Boolean
Answer: d) Integer or Boolean

2) Literal can be of which of these data types?


a) integer b) float c) Boolean d) all of the mentioned
Answer: d) all of the mentioned

3) Which of these can not be used for a variable name in Java?


a) identifier b) keyword c) identifier & keyword d) none of the mentioned
Answer: b) keyword
Recalling topics

 What is variable?
 Basic information about variable.
 How to declare variable
 Different types of variable
 Identifier
 Difference between variable and identifier
 Rules for variable and identifier creation

 Example Program.
ARRAYS in JAVA
ARRAYS

 An Array is a data structure which defines an ordered collection of a fixed number of homogeneous

data elements
 The size of an array is fixed and cannot increase to accommodate more elements.
 Arrays in Java are objects and can be of primitive data types or reference variable type.
 All elements in the array must be of the same data type.
 Java checks the boundary of an array while accessing an element in it.
ARRAYS

Array Declaration:
 One dimensional array
int[] a;
int []a;
int a[];
 Instantiation of an array
int[] a = new int[10]; //declaration and instantiation
ARRAYS

Array Initialization:
int[] a = {1, 2, 3, 4, 5}; //declaration, instantiation and initialization
int b[] = {6, 7, 8, 9, 10};
int[] c = new int[] {11, 12, 13, 14, 15};
int d[] = new int[] {16, 17, 18, 19, 20};
int e[];
e = new int[]{1,2,3,4,5};
ARRAYS

Example:
Public class Test
{
public static void main(String[] args)
{
int[] arr={10,20,30,40};
for(int x:arr)
{
System.out.println(x);
}
}
}
PASSING ARRAY TO FUNCTION

Public class Test


{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
TWO DIMENSIONAL ARRAY

 In such case, data is stored in row and column based index (also known as matrix form)
 When you allocate memory for a multi-dimensional array, you need only specify the memory for the
first(leftmost) dimension
Syntax:
int[][] a; (or)
int [][]a; (or)
int a [][]; (or)
int []a[];

int[][] a=new int[3][3];//3 row and 3 column


TWO DIMENSIONAL ARRAY
2D - ARRAY
class Test
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
ARRAY COPY

 It means to copy data from one array to another


 The precise way to copy data from one array to another is
 public static void arraycopy(Object source, int srcIndex, Object dest,int destIndex, int length)
ARRAY COPY

public class ArrayCopyDemo


{
public static void main(String[] args)
{
char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'};
char[] copyTo = new char[5];
System.arraycopy(copyFrom, 2, copyTo, 0, 5);
System.out.println(new String (copyTo));
}
}
Example Programs
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}}
Example Programs

// An improved version of the previous program.

class AutoArray

public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };

System.out.println("April has " + month_days[3] + " days.");

}
Example Programs
// Average an array of values.
fclass Average
{
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}}
Example Programs
// Demonstrate a two-dimensional array.
Public class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0; Output
for(i=0; i<4; i++)
01234
for(j=0; j<5; j++)
{ 56789
twoD[i][j] = k; 10 11 12 13 14
k++; 15 16 17 18 19
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
} } }
Example Programs
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][]; Output
twoD[0] = new int[1]; 0
twoD[1] = new int[2]; 12
twoD[2] = new int[3]; 345
twoD[3] = new int[4]; 6789
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}}
Example Programs
// Initialize a two-dimensional array.
public Class Matrix
{ public static void main(String args[])
{ double m[][] = { { 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 }, Output
{ 0*2, 1*2, 2*2, 3*2 },
0.0 0.0 0.0 0.0
{ 0*3, 1*3, 2*3, 3*3 } }; 0.0 1.0 2.0 3.0
int i, j; 0.0 2.0 4.0 6.0
for(i=0; i<4; i++) { 0.0 3.0 6.0 9.0
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}}}
Alternative Array Declaration Syntax

 type[ ] var-name;

 int al[] = new int[3];

 int[] a2 = new int[3];

The following declarations are also equivalent:

 char twod1[][] = new char[3][4];

 char[][] twod2 = new char[3][4];

 This alternative declaration form is included mostly as a convenience.


Recalling topics

 What is array?
 Basic information about array.
 How to declare array variable.
 Different types of array and use.
 Types of array.
 Applications of array.

 Example Program.
JAVA OPERATORS

 Operators are special symbols (characters) that carry out operations on operands (variables and
values).
 For example, + is an operator that performs addition.
 In the previous tutorial, you learn about Java Variables.
 You learn to declare variables and assign values to variables. Now, you will learn to use operators
to manipulate variables.
 Operators are the constructs which can manipulate the values of the operands. Consider the
expression 2 + 3 = 5, here 2 and 3 are operands and + is called operator.
 In this article on Java operators, the goal is to get you the expertise required to get started and
work with operators in Java.
Java supports the following types of operators
 Arithmetic Operators
 Assignment Operators
 Logical Operators
 Relational Operators
 Unary Operators
 Bitwise Operators
 Ternary Operators
 Shift Operators
Arithmetic Operators in Java
 Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra.
 The following table lists the arithmetic operators
Operator Description Example
+ Addition Adds values on either side of the operator A+B=30

Subtracts the right-hand operator with left-hand


– Subtraction A-B=-10
operator

* Multiplication Multiplies values on either side of the operator A*B=200

/ Division Divides left hand operand with right hand operator A/B=0

Divides left hand operand by right hand operand


% Modulus A%B=0
and returns remainder
Java Arithmetic Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15 Output:
System.out.println(a-b);//5 15
5
System.out.println(a*b);//50 50
2
System.out.println(a/b);//2 0
System.out.println(a%b);//0
}}
Java Arithmetic Operator Example: Expression

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

Output:
21
// basic arithmetic operators. System.out.println("e = " + e);
class BasicMath {
// arithmetic using doubles
public static void main(String args[]) {
System.out.println("\\nFloating Point
// arithmetic using integers
Arithmetic");
System.out.println("Integer Arithmetic");
double da = 1 + 1;
int a = 1 + 1;
int b = a * 3; double db = da * 3;

int c = b / 4; double dc = db / 4;
int d = c - a; double dd = dc - a;
int e = -d; double de = -dd;
System.out.println("a = " + a); System.out.println("da = " + da);
System.out.println("b = " + b); System.out.println("db = " + db);
System.out.println("c = " + c); System.out.println("dc = " + dc);
System.out.println("d = " + d);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
Output
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2
db = 6
dc = 1.5
dd = -0.5
de = 0.5
Example
class ArithmeticOperator
{
public static void main(String[] args)
{
double number1 = 12.5, number2 = 3.5, result; Output:
// Using addition operator number1 + number2 = 16.0
number1 - number2 = 9.0
result = number1 + number2;
number1 * number2 = 43.75
System.out.println("number1 + number2 = " + result);
number1 / number2 = 3.5714285
System.out.println("number1 - number2 = " + result); number1 % number2 = 2.0
System.out.println("number1 * number2 = " + result);
System.out.println("number1 / number2 = " + result);
System.out.println("number1 % number2 = " + result);
}
}
The Modulus Operator
 The modulus operator, %, returns the remainder of a division operation.
 It can be applied to floating-point types as well as integer types.

// Demonstrate the % operator.


class Modulus {
public static void main(String args[]) Output
{ x mod 10 = 2
y mod 10 = 2.3
int x = 42;
double y = 42.3;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}}
Example
public class Test
System.out.println("b-- = " + (a--) );
{
public static void main(String args[]) // Check the difference in d++ and ++d
{ System.out.println("d++ = " + (d++) );
int a = 10; System.out.println("++d = " + (++d) );
int b = 20;
}
int c = 25;
int d = 25; }
System.out.println("a + b = " + (a + b) ); Output
System.out.println("a - b = " + (a - b) ); a + b = 30
a - b = -10
System.out.println("a * b = " + (a * b) ); a * b = 200
System.out.println("b / a = " + (b / a) ); b/a=2
System.out.println("b % a = " + (b % a) ); b%a=0
c%a=5
System.out.println("c % a = " + (c % a) ); a++ = 10
System.out.println("a++ = " + (a++) ); b-- = 11
d++ = 25
++d = 27
Assignment Operators
 An Assignment Operator is an operator used to assign a new value to a variable. Assume A = 10
and B = 20 for the below table.
Operator Description Example
Assigns values from right side operands to left side
= c=a+b
operand
It adds right operand to the left operand and assigns the
+= c += a
result to left operand
It subtracts right operand from the left operand and assigns
-= c -= a
the result to left operand
It multiplies right operand with the left operand and
*= c *= a
assigns the result to left operand
It divides left operand with the right operand and assigns
/= c /= a
the result to left operand
It takes modulus using two operands and assigns the result
%= c %= a
to left operand
Performs exponential (power) calculation on operators and
^= c ^= a
assign value to the left operand
Assignment Operators
 There are assignment operators for all of the arithmetic, binary operators. Thus, any statement of the
form
- va r = var op expression; can be rewritten as
- var op= expression;
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
Output
int b = 2; a=6
int c = 3; b=8
a += 5; c=3
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}}
public class Test { System.out.println("c /= a = " + c );
public static void main(String args[]) { a = 10;
int a = 10; c = 15;
c %= a ;
int b = 20;
System.out.println("c %= a = " + c );
int c = 0; c <<= 2 ;
c = a + b; System.out.println("c <<= 2 = " + c );
System.out.println("c = a + b = " + c ); c >>= 2 ;
c += a ; System.out.println("c >>= 2 = " + c );
System.out.println("c += a = " + c ); c >>= 2 ;
System.out.println("c >>= a = " + c );
c -= a ;
c &= a ;
System.out.println("c -= a = " + c ); System.out.println("c &= 2 = " + c );
c *= a ; c ^= a ;
System.out.println("c *= a = " + c ); System.out.println("c ^= a = " + c );
a = 10; c |= a ;
c = 15; System.out.println("c |= a = " + c );
}
c /= a ;
}
Increment and Decrement Operators
operator Description Example
increments the value by 1.There is post-
++ a++ and ++a
increment and pre-increment operators
decrements the value by 1.There is post
-- a-- or --a
decrement and pre decrement operators

 ++ :Increment operator, used for incrementing the value by 1. There are two varieties of
increment operator.
 Post-Increment : Value is first used for computing the result and then incremented.
 Pre-Increment : Value is incremented first and then result is computed.
 — : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operator.
 Post-decrement : Value is first used for computing the result and then decremented.
 Pre-Decrement : Value is decremented first and then result is computed.
Cont…
 For example, this statement:
x = x + 1;
 can be rewritten like this by use of the increment operator:
x++;
 Similarly, this statement:
x = x - 1;
 is equivalent to
x—;
 For example:

x = 42;
y = ++x;
Demonstrates the increment operator
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
output
int c; a=2
int d; b=3
c = ++b; c=4
d = a++; d=1
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}}
Bitwise Operators and Bit Shift Operators
 Bitwise operations directly manipulate bits. In all computers, numbers are represented with bits, a
series of zeros and ones.
 In fact, pretty much everything in a computer is represented by bits.
 Assume that A = 10 and B = 20 for the below table.

Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
CONT…
 In this case, y is set to 43 as you would expect, because the increment occurs before x is
assigned to y.
 Thus, the line y = ++x; is the equivalent of these two statements:
 x = x + 1;

 y = x;

 However, when written like this,


 x = 42;

 y = x++;
public class operators {
public static void main(String[] args)
{ // Logical not operator
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30; System.out.println("Value of !
boolean condition = true; condition ="+ !condition);
// pre-increment operator }
// a = a+1 and then c = a; }
c = ++a;
System.out.println("Value of c (++a) = " + c);
// post increment operator Output:
// c=b then b=b+1 Value of c (++a) = 21
c = b++; Value of c (b++) = 10
System.out.println("Value of c (b++) = " + c); Value of c (--d) = 19
// pre-decrement operator Value of c (e--) = 40
// d=d-1 then c=d
c = --d;
System.out.println("Value of c (--d) = " + c);
// post-decrement operator
// c=e then e=e-1
c = e--;
System.out.println("Value of c (e--) = " + c);
AND Operator Example
Logical && and Bitwise &
 he 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

class OperatorExample{
public static void main(String args[]){ Output:
int a=10; false
false
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Logical && vs Bitwise &
Output:
class OperatorExample
false
{ 10
false
public static void main(String args[]){
11
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}
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.

class OperatorExample{
public static void main(String args[]){
int a=10; Output:
int b=5; true
int c=20; true
System.out.println(a>b||a<c);//true || true = true true
System.out.println(a>b|a<c);//true | true = true 10
System.out.println(a>b||a++<c);//true || true = true true
System.out.println(a);//10 because second condition is not checked 11
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}
Demonstrates the bitwise logical operators
Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110","0111", "1000", "1001",
"1010", "1011", "1100", "1101", "1110","1111"};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
CONT…

System.out.println(" a|b = " + binary[c]); Output


System.out.println(" a&b = " + binary[d]); a = 0011
System.out.println(" a^b = " + binary[e]); b = 0110
System.out.println("~a&b|a&~b = " + binary[f]); a|b = 0111
System.out.println(" ~a = " + binary[g]); a&b = 0010
a^b = 0101
}
~a&b|a&~b = 0101
} ~a = 1100
Operator Shifting
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.
class OperatorExample{
public static void main(String args[]) Output:
{ 40
System.out.println(10<<2);//10*2^2=10*4=40 80
System.out.println(10<<3);//10*2^3=10*8=80 80
System.out.println(20<<2);//20*2^2=20*4=80 240
System.out.println(15<<4);//
15*2^4=15*16=240 }
}
Left Shift Operator
// Left shifting a byte value.
class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
Output
int i; Original value of a: 64
i = a << 2; i and b: 256 0

b = (byte) (a << 2);


System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
Since a is promoted to int for the purposes of evaluation, left-shifting the
} value 64 (01000000) twice results in i containing the value 256 (1 0000
} 0000). However, the value in b contains 0 because after the shift, the low-
order byte is now zero. Its only 1 bit has been shifted out.
Left Shift Operator
Output:
// Left shifting as a quick way to multiply by 2.
536870908
class MultByTwo { 1073741816
2147483632
public static void main(String args[]) {
-32
int i;
The starting value was
int num = 0xFFFFFFE; carefully chosen so that
for(i=0; i<4; i++) { after being shifted left 4
bit positions, it would
num = num << 1; produce -32. As you can
System.out.println(num); see, when a 1 bit is shifted
into bit 31, the number is
} interpreted as negative.
}
}
The Right Shift
 The right shift operator, >>, shifts all of the bits in a value to the right a specified numberof times.
Its general form is shown here:

value >> num


 Here, num specifies the number of positions to right-shift the value in value. That is, the >> moves
all of the bits in the specified value to the right the number of bit positions specified by num.
 The following code fragment shifts the value 32 to the right by two positions, resulting in a being
set to 8:

int a = 32;
a = a >> 2; // a now contains 8
CONT…
 When a value has bits that are "shifted off," those bits are lost. For example, the next code fragment
shifts the value 35 to the right two positions, which causes the two low order bits to be lost, resulting
again in a being set to 8.
 int a = 35;
 a = a >> 2; // a still contains 8
 Looking at the same operation in binary shows more clearly how this happens:
 00100011 35
 >> 2
 00001000 8
EXAMPLE
// Masking sign extension.
class HexByte {
static public void main(String args[]) { OUTUT
char hex[] = {
b = 0xf1
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
byte b = (byte) 0xf1;
System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b &0x0f]);
}
}
Java Right Shift Operator Example
class OperatorExample
{
public static void main(String args[])
{ Output:

System.out.println(10>>2);//10/2^2=10/4=2 2
5
System.out.println(20>>2);//20/2^2=20/4=5
2
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Java Shift Operator Example: >> vs >>>

class OperatorExample
{
public static void main(String args[])
Output:
{
5
//For positive number, >> and >>> works same
5
System.out.println(20>>2);
–5
System.out.println(20>>>2);
1073741819
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Unsigned Right Shift
// Unsigned shifting a byte value.
class ByteUShift {
static public void main(String args[]) {
char hex[] = { OUTPUT
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f‘ }; b = 0xf1
b >> 4 = 0xff
byte b = (byte) 0xf1;
b >>> 4 = 0xff
byte c = (byte) (b >> 4); (b & 0xff) >> 4 = 0x0f
byte d = (byte) (b >>> 4);
byte e = (byte) ((b & 0xff) >> 4);
System.out.println(" b = 0x"+ hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
System.out.println(" b >> 4 = 0x"+ hex[(c >> 4) & 0x0f] + hex[c & 0x0f]);
System.out.println(" b >>> 4 = 0x"+ hex[(d >> 4) & 0x0f] + hex[d & 0x0f]);
System.out.println("(b & 0xff) >> 4 = 0x"+ hex[(e >> 4) & 0x0f] + hex[e &
0x0f]);
}}
Bitwise Operator Assignments
 All of the binary bitwise operators have a shorthand form similar to that of the algebraic operators,
which combines the assignment with the bitwise operation.
 a = a >> 4;
 a >>= 4;
 Likewise, the following two statements, which result in a being assigned the bitwise
 expression a OR b, are equivalent:
 a = a | b;
 a |= b;
EXAMPLE
class OpBitEquals {
public static void main(String args[])
{
int a = 1;
int b = 2;
int c = 3;
a |= 4; OUTPUT
b >>= 1; a=3
c <<= 1; b=1
a ^= c;
c=6
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Relational Operators
 The relational operators determine the relationship that one operand has to the other. Specifically,
they determine equality and ordering.
 The equality and relational operators determine the relationship between the two operands. It
checks if an operand is greater than, less than, equal to, not equal to and so on. Depending on the
relationship, it is evaluated to either true or false.

variable relation_operator value


Relational Operators

Operator Description Example


== equal to 5 == 3 is evaluated to false
!= not equal to 5 != 3 is evaluated to true
> greater than 5 > 3 is evaluated to true
< less than 5 < 3 is evaluated to false
>= greater than or equal to 5 >= 5 is evaluated to true
<= less than or equal to 5 <= 5 is evaluated to true
Equality and Relational Operators
class RelationalOperator
{
public static void main(String[] args)
{
int number1 = 5, number2 = 6;
if (number1 > number2)
{
System.out.println("number1 is greater than number2.");
}
else
{
System.out.println("number2 is greater than number1.");
}
Output:
}
number2 is greater than number1.
}
EXAMPLE
// Java program to illustrate
// relational operators
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10;
String x = "Thank", y = "Thank";
int ar[] = { 1, 2, 3 };
int br[] = { 1, 2, 3 };
boolean condition = true;
// various conditional operators
System.out.println("a == b :" + (a == b));
System.out.println("a < b :" + (a < b));
System.out.println("a <= b :" + (a <= b));
System.out.println("a > b :" + (a > b));
CONT…
System.out.println("a >= b :" + (a >= b)); Output: a != b :true
System.out.println("a != b :" + (a != b)); a == b :false x == y : false
a < b :false condition==true :true
a <= b :false
// Arrays cannot be compared with
a > b :true
// relational operators because objects a >= b :true
// store references not the value
System.out.println("x == y : " + (ar == br));
System.out.println("condition==true :"+ (condition == true));
}
}
Java Conditional Operator
 The Java Conditional Operator selects one of two expressions for evaluation, which is based on the
value of the first operands. It is also called ternary operator because it takes three arguments.
 The ternary conditional operator is used to shorten the code of if statement. It is a special type of
operator with three parts i.e. question ? answer1 : answer2
 The conditional operator is used to handling simple situations in a line.

Syntax :

expression1 ? expression2:expression3;
Java Conditional Operator
Syntax of a conditional operator:

Meaning of the above syntax.


 In the above syntax, the expression1 is a Boolean condition that can be either true or false value.
 If the expression1 results into a true value, then the expression2 will execute.
 The expression2 is said to be true only when it returns a non-zero value.
 If the expression1 returns false value then the expression3 will execute.
 The expression3 is said to be false only when it returns zero value.
Java Conditional Operator
Examples:
1.val == 0 ? you are right : you are not right;
2. 3. public class condiop
{
public static void main(String[] args)
{
String out; int a = 6, b = 12;
out = a==b ? "Yes":"No";
System.out.println("Ans: "+out);
 In the above example, the }
condition given in }
expression1 is false because
the value of a is not equal to Output
the value of b. Ans: No
Java Conditional Operator – Examples
 Ternary Conditional Operator
import java.util.Scanner;
public class TernaryOpDemo
{
public static void main(String[] args)
{
//Checking if marks greater than 35 or not
String status;
int marks;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your Marks (between 0 to 100) >> ");
marks = inputDevice.nextInt();
status= marks>=35 ?"You are Passed":"You are failed";
System.out.println("Status= " + status);
}
}
// Java code to illustrate ternary operator
import java.io.*;
class Ternaryop
{
public static void main(String[] args)
{ // variable declaration
int n1 = 5, n2 = 10, res; Output:
System.out.println("First num: " + n1); First num: 5
System.out.println("Second num: " + n2); Second num: 10
// Performing ternary operation Result = -5
res = (n1 > n2) ? (n1 + n2) : (n1 - n2);
// Print the largest number
System.out.println("Result = " + res);
}
}
Java Conditional Operator – Examples
public class Test
{
public static void main(String args[])
{
int a, b; a = 10;
Output
b = (a == 1) ? 20: 30;
Value of b is: 30
System.out.println("Value of b is: " + b); Value of b is: 20
b = (a == 10) ? 20: 30;
System.out.println(“Value of b is: " + b);
}
}
Java Conditional Operator – Examples
public class Example
{
public static void main(String[] args)
{
int A = 10; Output:
int B = 20; B is greater

String result = A> B ? "A is greater" : "B is greater";


System.out.println(result);
}
}
Java Conditional Operator – Examples
// Demonstrate ?.
class Ternary
{ public static void main(String args[])
{
int i, k; i = 10;
k = i < 0 ? -i : i; // get absolute value of i
Output :
System.out.print("Absolute value of ");
Absolute value of 10 is 10
System.out.println(i + " is " + k);
Absolute value of -10 is 10
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Java Operator Precedence and Associativity
Operators Precedence Associativity
postfix increment and
++ -- left to right
decrement
prefix increment and
++ -- + - ~ ! right to left
decrement, and unary
multiplicative */% left to right
additive +- left to right
shift << >> >>> left to right
relational < > <= >= instanceof left to right
equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right
bitwise inclusive OR | left to right
logical AND && left to right
logical OR || left to right
ternary ?: right to left
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= left to right
Using Parentheses
 Parentheses raise the precedence of the operations that are inside them. This is often necessary
to obtain the result you desire.
 For example, consider the following expression:
a >> b + 3
 This expression first adds 3 to b and then shifts a right by that result. That is, this expression can
be rewritten using redundant parentheses like this:
a >> (b + 3)
 However, if you want to first shift a right by b positions and then add 3 to that result, you will
need to parenthesize the expression like this:
(a >> b) + 3

 One other point: parentheses (redundant or not) do not degrade the performance of your
program.
 Therefore, adding parentheses to reduce ambiguity does not negatively affect your program.
QUIZ
1) Which of the following can be operands of arithmetic operators?
a) Numeric b) Boolean c) Characters d) Both Numeric & Characters
Answer: d) Both Numeric & Characters

2) Modulus operator, %, can be applied to which of these?


a) Integers b) Floating – point numbers c) Both Integers and floating – point numbers
d) None of the mentioned
Answer: c) Both Integers and floating – point numbers

3) Which of these is not a bitwise operator?


a) & b) &= c) |= d) <=
Answer: d) <=
Recalling topics

 What is an operator?
 Basic information about operator.
 How to use the operator.
 Different types operator and use.
 Compression of operators .
 How to computing operators(operator precedence) .

 Example Program.
THANK YOU

Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC

You might also like