Professional Documents
Culture Documents
J.MYILVAHANAN
Semester – II
ASSISTANT PROFESSOR
Academic Year : 2020-2021(EVEN) DEPARTMENT CSE
HIT
COIMBATORE
COURSE OBJECTIVE
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
FEATURES OF OOPS
INTRODUCTION TO JAVA
HISTORY OF JAVA
VERSION OF JAVA
BASIC OF JAVA
DATA TYPE
VARIABLE
ARRAY
OPERATOR
WHAT IS PROGRAMMING LANGUAGR
JDK Alpha and Beta (1995) J2SE 1.4 (6th Feb, 2002)
JDK 1.0 (23rd Jan, 1996) J2SE 5.0 (30th Sep, 2004)
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
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 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
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
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
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
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.
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
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
}
•
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
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
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
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.
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
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”:
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
}}
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
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
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 :
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
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
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
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 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
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
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[];
class AutoArray
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
}
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;
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
/ Division Divides left hand operand with right hand operator A/B=0
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.
++ :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;
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…
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.
Syntax :
expression1 ? expression2:expression3;
Java Conditional Operator
Syntax of a conditional operator:
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
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