Javanotes
Javanotes
Javanotes
Concept in Java
As the name suggests, Object-Oriented Programming or OOPs refers to languages that
uses objects in programming. Object-oriented programming aims to implement real-
world entities like inheritance, hiding, polymorphism etc in programming. The main
aim of OOP is to bind together the data and the functions that operate on them so that
no other part of the code can access this data except that function.
Let us do discuss pre-requisites by polishing concepts of methods declaration and
passing. Starting off with the method declaration, it consists of six components:
Access Modifier: Defines access type of the method i.e. from where it can
be accessed in your application. In Java, there 4 type of the access
specifiers.
public: accessible in all class in your application.
protected: accessible within the package in which it is defined
and in its subclass(es)(including subclasses declared outside the
package)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier): accessible
within same class and package within which its class is defined.
The return type: The data type of the value returned by the method or void
if does not return a value.
Method Name: the rules for field names apply to method names as well, but
the convention is a little different.
Parameter list: Comma separated list of the input parameters are defined,
preceded with their data type, within the enclosed parenthesis. If there are
no parameters, you must use empty parentheses ().
Exception list: The exceptions you expect by the method can throw, you
can specify these exception(s).
Method body: it is enclosed between braces. The code you need to be
executed to perform your intended operations.
Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a
procedure and therefore will invoke a function in the receiving object that generates
the desired results. Message passing involves specifying the name of the object, the
name of the function and the information to be sent.
Now with basic prerequisite to step learning 4 pillar of OOPS is as follows. Let us
start with learning about the different characteristics of an Object-Oriented
Programming language
OOPs Concepts are as follows:
1. Class
2. Object
3. Method and method passing
4. Pillars of OOPS
Abstraction
Encapsulation
Inheritance
Polymorphism
Compile-time polymorphism
Run-time polymorphism
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for
details).
2. Class name: The name should begin with a initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement
more than one interface.
5. Body: The class body surrounded by braces, { }.
Object is a basic unit of Object Oriented Programming and represents the real life
entities. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of:
1. State : It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the
response of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to
interact with other objects.
4. Method: A method is a collection of statements that perform some specific
task and return result to the caller. A method can perform some specific task
without returning anything. Methods allow us to reuse the code without
retyping the code. In Java, every method must be part of some class which
is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the
code.
Let us now discuss 4 pillars of OOPS:
Pillar 1: Abstraction
Data Abstraction is the property by virtue of which only the essential details are
displayed to the user.The trivial or the non-essentials units are not displayed to the
user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and
behaviours of an object differentiate it from other objects of similar type and also help
in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of car or applying brakes will stop the car but
he does not know about how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve
100% abstraction using interfaces.
Pillar 2: Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. Another way to think about
encapsulation is, it is a protective shield that prevents the data from being accessed by
the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from
any other class and can be accessed only through any member function of
own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is
also known as data-hiding.
Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of
variables.
Pillar 3: Inheritence
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and
methods) of another class.
Let us discuss some of frequent used important terminologies:
Super Class: The class whose features are inherited is known as
superclass(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as subclass(or a
derived class, extended class, or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
Pillar 4: Polymorphism
It refers to the ability of OOPs programming languages to differentiate between
entities with the same name efficiently. This is done by Java with the help of the
signature and declaration of these entities.
Note: Polymorphism in Java are mainly of 2 types:
1. Overloading
2. Overriding
Example
Java
Output:
30
60
31.0
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is
a paradigm that provides many concepts, such as inheritance, data
binding, polymorphism, etc.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-
Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
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
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
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.
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.
Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
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.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It
arises when classes are aware of each other. If a class has the details information of
another class, there is strong coupling. In Java, we use private, protected, and public
modifiers to display the visibility level of a class, method, and field. You can use
interfaces for the weaker coupling because there is no concrete implementation.
Cohesion
Cohesion refers to the level of a component which performs a single well-defined
task. A single well-defined task is done by a highly cohesive method. The weakly
cohesive method will split the task into separate parts. The java.io package is a highly
cohesive package because it has I/O related classes and interface. However, the
java.util package is a weakly cohesive package because it has unrelated classes and
interfaces.
Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association
between the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
Let's understand the relationship with real-time examples. For example, One country
can have one prime minister (one to one), and a prime minister can have many
ministers (one to many). Also, many MP's can have one prime minister (many to one),
and many ministers can have many departments (many to many).
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship
where one object contains other objects as a part of its state. It represents the weak
relationship between objects. It is also termed as a has-a relationship in Java. Like,
inheritance represents the is-a relationship. It is another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents
the relationship where one object contains other objects as a part of its state. There
is a strong relationship between the containing object and the dependent object. It is
the state where containing objects do not have an independent existence. If you
delete the parent object, all the child objects will be deleted automatically.
All the classes, interfaces, packages, methods and fields of Java programming
language are given according to the Java naming convention. If you fail to follow
these conventions, it may generate confusion or erroneous code.
Variable It should start with a lowercase letter such as id, name. class Employee
It should not start with the special characters like & {
(ampersand), $ (dollar), _ (underscore). // variable
If the name contains multiple words, start it with the int id;
lowercase letter followed by an uppercase letter such as //code snippet
firstName, lastName. }
Avoid using one-character variables such as x, y, z.
If the name is combined with two words, the second word will start with uppercase
letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
In this page, we will learn about Java objects and classes. In object-oriented
programming technique, we design a program using objects and classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example
of an intangible object is the banking system.
Object Definitions:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
File: Student.java
1. //Java Program to illustrate how to define a class and fields
2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }
Test it Now
Output:
0
null
We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has main() method.
File: TestStudent1.java
1. //Java Program to demonstrate having the main method in
2. //another class
3. //Creating Student class.
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
15. }
Test it Now
Output:
0
null
1. By reference variable
2. By method
3. By constructor
File: TestStudent2.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12. }
Test it Now
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference
variable.
File: TestStudent3.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);
17. System.out.println(s2.id+" "+s2.name);
18. }
19. }
Test it Now
Output:
101 Sonoo
102 Amit
File: TestStudent4.java
1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19. }
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area. Here,
s1 and s2 both are reference variables that refer to the objects allocated in memory.
3) Object and Class Example: Initialization through a
constructor
We will learn about constructors in Java later.
File: TestEmployee.java
1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23. }
24. }
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
File: TestRectangle1.java
1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. }
10. class TestRectangle1{
11. public static void main(String args[]){
12. Rectangle r1=new Rectangle();
13. Rectangle r2=new Rectangle();
14. r1.insert(11,5);
15. r2.insert(3,15);
16. r1.calculateArea();
17. r2.calculateArea();
18. }
19. }
Test it Now
Output:
55
45
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
Anonymous object
Anonymous simply means nameless. An object which has no reference is known as
an anonymous object. It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach. For
example:
1. new Calculation();//anonymous object
Calling method through a reference:
1. Calculation c=new Calculation();
2. c.fact(5);
1. new Calculation().fact(5);
1. class Calculation{
2. void fact(int n){
3. int fact=1;
4. for(int i=1;i<=n;i++){
5. fact=fact*i;
6. }
7. System.out.println("factorial is "+fact);
8. }
9. public static void main(String args[]){
10. new Calculation().fact(5);//calling method with anonymous object
11. }
12. }
Output:
Factorial is 120
1. int a=10, b=20;
1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
1. //Java Program to illustrate the use of Rectangle class which
2. //has length and width data members
3. class Rectangle{
4. int length;
5. int width;
6. void insert(int l,int w){
7. length=l;
8. width=w;
9. }
10. void calculateArea(){System.out.println(length*width);}
11. }
12. class TestRectangle2{
13. public static void main(String args[]){
14. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
15. r1.insert(11,5);
16. r2.insert(3,15);
17. r1.calculateArea();
18. r2.calculateArea();
19. }
20. }
21. Output:
22. 55
23. 45
1. //Java Program to demonstrate the working of a banking-system
2. //where we deposit and withdraw amount from our account.
3. //Creating an Account class which has deposit() and withdraw() methods
4. class Account{
5. int acc_no;
6. String name;
7. float amount;
8. //Method to initialize object
9. void insert(int a,String n,float amt){
10. acc_no=a;
11. name=n;
12. amount=amt;
13. }
14. //deposit method
15. void deposit(float amt){
16. amount=amount+amt;
17. System.out.println(amt+" deposited");
18. }
19. //withdraw method
20. void withdraw(float amt){
21. if(amount<amt){
22. System.out.println("Insufficient Balance");
23. }else{
24. amount=amount-amt;
25. System.out.println(amt+" withdrawn");
26. }
27. }
28. //method to check the balance of the account
29. void checkBalance(){System.out.println("Balance is: "+amount);}
30. //method to display the values of an object
31. void display(){System.out.println(acc_no+" "+name+" "+amount);}
32. }
33. //Creating a test class to deposit and withdraw amount
34. class TestAccount{
35. public static void main(String[] args){
36. Account a1=new Account();
37. a1.insert(832345,"Ankit",1000);
38. a1.display();
39. a1.checkBalance();
40. a1.deposit(40000);
41. a1.checkBalance();
42. a1.withdraw(15000);
43. a1.checkBalance();
44. }}
Test it Now
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0
Constructors in Java
1. Types of constructors
0. Default Constructor
1. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value?
4. Copying the values of one object into another
5. Does constructor perform other tasks instead of the initialization
Every time an object is created using the new() keyword, at least one constructor is
called.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
1. //Java Program to create and call a default constructor
2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Output:
Bike is created
The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.
Output
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.
1. //Java Program to demonstrate the use of the parameterized constructor.
2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }
Output
Guess?
A constructor is used to initialize the state of an object. A method is used to expose the behavior
of an object.
A constructor must not have a return type. A method must have a return type.
The constructor name must be same as the class name. The method name may or may not be
same as the class name.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using
Java constructor.
1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }
Test it Now
Output:
111 Karan
111 Karan
1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Test it Now
Output:
111 Karan
111 Karan
o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
Suppose there are 500 students in my college, now all instance data members will
get memory each time when the object is created. All students have its unique rollno
and name, so instance data member is good in such case. Here, "college" refers to
the common property of all objects. If we make it static, this field will get the
memory only once.
Output:
1. //Java Program to demonstrate the use of an instance variable
2. //which get memory each time when we create an object of the class.
3. class Counter{
4. int count=0;//will get memory each time when the instance is created
5.
6. Counter(){
7. count++;//incrementing value
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //Creating objects
13. Counter c1=new Counter();
14. Counter c2=new Counter();
15. Counter c3=new Counter();
16. }
17. }
Test it Now
Output:
1
1
1
1. //Java Program to illustrate the use of static variable which
2. //is shared with all objects.
3. class Counter2{
4. static int count=0;//will get memory only once and retain its value
5.
6. Counter2(){
7. count++;//incrementing the value of static variable
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //creating objects
13. Counter2 c1=new Counter2();
14. Counter2 c2=new Counter2();
15. Counter2 c3=new Counter2();
16. }
17. }
Test it Now
Output:
1
2
3
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Test it Now
Output:Compile Time Error
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since
JDK 1.7, it is not possible to execute a Java class without the main method.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Test it Now
Output:
Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Features of Java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are also
some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C+
+, etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in
which a program runs.
There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security
by separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any machine on the
internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.
What is JRE?
Java Run-time Environment (JRE) is the part of the Java Development Kit (JDK). It is a
freely available software distribution which has Java Class Library, specific tools, and a
stand-alone JVM. It is the most common environment available on devices to run java
programs. The source Java code gets compiled and converted to Java bytecode. If you wish to
run this bytecode on any platform, you require JRE. The JRE loads classes, verify access to
memory, and retrieves the system resources. JRE acts as a layer on the top of the operating
system.
It also includes:
o Technologies which get used for deployment such as Java Web Start.
o Toolkits for user interface like Java 2D.
o Integration libraries like Java Database Connectivity (JDBC) and Java Naming and
Directory Interface (JNDI).
o Libraries such as Lang and util.
o Other base libraries like Java Management Extensions (JMX), Java Native Interface
(JNI) and Java for XML Processing (JAX-WS).
JRE has an instance of JVM with it, library classes and development tools. To
understand the working of JRE let us see an example of a simple "Hello World"
program.
In this chapter, we’ll set the scene by describing the Java language (which
programmers write their applications in), the Java Virtual Machine (which
executes those applications), and the Java ecosystem (which provides a lot
of the value of the programming environment to development teams).
We’ll briefly cover the history of the Java language and virtual machine,
before moving on to discuss the lifecycle of a Java program and clear up
some common questions about the differences between Java and other
environments.
At the end of the chapter, we’ll introduce Java security, and discuss some
of the aspects of Java which relate to secure coding.
At the time that Java was initially developed, this split was considered
novel, but recent trends in software development have made it more
commonplace. Notably, Microsoft’s .NET environment, announced a few
years after Java, adopted a very similar approach to platform architecture.
One of the main reasons for the success of Java is that this ecosystem is a
standardized environment. This means there are specifications for the
technologies that comprise the environment. These standards give the
developer and consumer confidence that the technology will be compatible
with other components, even if they come from a different technology
vendor.
This brings up the JVM as an operating system process that provides the
Java runtime environment, and then executes our program in the context of
the freshly started (and empty) virtual machine.
The design of the JVM built on many years of experience with earlier
programming environments, notably C and C++, so we can think of it as
having several different goals—which are all intended to make life easier
for the programmer:
Comprise a container for application code to run inside
Provide a secure execution environment as compared to C/C+
+
Take memory management out of the hands of developers
Provide a cross-platform execution environment
These objectives are often mentioned together when discussing the
platform.
We’ve already mentioned the first of these goals, when we discussed the
JVM and its bytecode interpreter—it functions as the container for
application code.
We’ll discuss the second and third goals in Chapter 6, when we talk about
how the Java environment deals with memory management.
The fourth goal, sometimes called “write once, run anywhere” (WORA), is
the property that Java class files can be moved from one execution
platform to another, and they will run unaltered provided a JVM is
available.
This means that a Java program can be developed (and converted to class
files) on an Apple Mac machine running OS X, and then the class files can
be moved to Linux or Microsoft Windows (or other platforms) and the
Java program will run without any further work needed.
NOTE
The Java environment has been very widely ported, including to platforms that
are very different from mainstream platforms like Linux, Mac, and Windows. In
this book, we use the phrase “most implementations” to indicate those platforms
that the majority of developers are likely to encounter. Mac, Windows, Linux,
Solaris, BSD Unix, AIX, and the like are all considered “mainstream platforms” and
count within “most implementations.”
Software research in the 1970s and 1980s revealed that the runtime
behavior of programs has a large amount of interesting and useful patterns
that cannot be deduced at compile time. The JVM was the first truly
mainstream platform to make use of this research.
A key example is the runtime fact that not all parts of a Java program are
equally likely to be called during the lifetime of the program—some
portions will be called far, far more often than others. The Java platform
takes advantage of this fact with a technology called just-in-time (JIT)
compilation.
In the HotSpot JVM (which was the JVM that Sun first shipped as part of
Java 1.3, and is still in use today), the JVM first identifies which parts of
the program are called most often—the “hot methods.” Then, the JVM
compiles these hot methods directly into machine code—bypassing the
JVM interpreter.
The standard that describes how a properly functioning JVM must behave
is called the JVM Specification.
The benefits of Java do not end there, however. Since Java’s inception, an
extremely large ecosystem of third-party libraries and components has
grown up. This means that a development team can benefit hugely from
the existence of connectors and drivers for practically every technology
imaginable—both proprietary and open source.
Java 7 (2011)
The first release of Java under Oracle’s stewardship included a
number of major upgrades to the language and platform. The
introduction of try-with-resources and the NIO.2 API enabled
developers to write much safer and less error-prone code for
handling resources and I/O. The Method Handles API provided a
simpler and safer alternative to reflection—and opened the door
for invokedynamic (the first new bytecode since version 1.0 of Java).
Java 8 (2014)
This latest release of Java introduces potentially the most significant
changes to the language since Java 5 (or possibly ever). The
introduction of lambda expressions promises the ability to
significantly enhance the productivity of developers; the Collections
have been updated to make use of lambdas, and the machinery
required to achieve this provides a fundamental change in Java’s
approach to object orientation. Other major updates include an
implementation of JavaScript that runs on the JVM (Nashorn), new
date and time support, and Java profiles (which provide for different
versions of Java that are especially suitable for headless or server
deployments).
In fact, bytecode is not very similar to machine code that would run on a
real hardware processor. Computer scientists would call bytecode a type of
“intermediate representation”—a halfway house between source code and
machine code.
Is javac a compiler?
Compilers usually produce machine code, but javac produces bytecode,
which is not that similar to machine code. However, class files are a bit
like object files (like Windows .dll files, or Unix .so files)—and they are
certainly not human readable.
In theoretical computer science terms, javac is most similar to the “front
half” of a compiler—it creates the intermediate representation that can
then be used to produce (emit) machine code.
Is bytecode optimized?
In the early days of the platform, javac produced heavily optimized
bytecode. This turned out to be a mistake. With the advent of JIT
compilation, the important methods are going to be compiled to very fast
machine code. It’s therefore very important to make the job of the JIT
compiler easier—as there are much bigger gains available from JIT
compilation than there are from optimizing bytecode, which will still have
to be interpreted.
Java Security
Java has been designed from the ground up with security in mind; this
gives it a great advantage over many other existing systems and platforms.
The Java security architecture was designed by security experts and has
been studied and probed by many other security experts since the inception
of the platform. The consensus is that the architecture itself is strong and
robust, without any security holes in the design (at least none that have
been discovered yet).
In particular, the release of Java 8 was delayed, at least partly, due to the
discovery of a number of security problems that required considerable
effort to fix.
In all likelihood, security flaws will continue to be discovered (and
patched) in Java VM implementations.
However, it is also worth noting that the majority of Java’s recent security
issues have been closely linked to Java as a desktop technology. For
practical server-side coding, Java remains perhaps the most secure
general-purpose platform currently available.
Java Compared to C
Java is object oriented; C is procedural.
Java is portable as class files; C needs to be recompiled.
Java provides extensive instrumentation as part of the runtime.
Java has no pointers and no equivalent of pointer arithmetic.
Java provides automatic memory management via garbage
collection.
Java has no ability to lay out memory at a low level (no structs).
Java has no preprocessor.
Important Points to keep in mind while working with Java Source File
Below are the points that we should keep in our mind while working with Java:
1. Number of classes in a Java source file:
A Java program can contain any number of classes, and at most, one of them can be
declared as a public class.
Explanation: Java allows us to create any number of classes in a program. But out of
all the classes, at most, one of them can be declared as a public class. In simple words,
the program can contain either zero public class, or if there is a public class present, it
cannot be more than one.
The correctness proof of the statement: Let us create a program in our local IDE and
compile it with the help of the Javac compiler.
For example, In the below program, we have created three empty classes (Geeks,
Learning, and Programming).
Source Code:
Java
// Declaring classes
class Geeks {
class Learning {
class Programming {
We have saved the above java source file with the name GeeksforGeeks.java.
Let us now compile the program with the help of the javac compiler through the
command prompt:
javac GeeksforGeeks.java
Output:
Fig 2: Compiler Verdict
// Declared as public
}
class Learning {
class Programming {
We have saved the above java source file with the name GeeksforGeeks.java.
Let us now compile the program with the help of the javac compiler through the
command prompt:
Output:
We get the compilation error. Compiler asks to save the Java source file name
with Geeks.java only as Geeks class is declared as public.
fig 5: File Name
Let us now compile the program with the help of the javac compiler through the
command prompt again:
javac Geeks.java
Output:
class GeeksforGeeks {
class Programming {
class Coding {
We have saved the above java source file with the name GeeksforGeeks.java.
Let us now compile the program with the help of the javac compiler through the
command prompt:
javac GeeksforGeeks.java
Output:
The program compiles successfully without any errors, and since we have three
classes defined in the GeeksforGeeks.java program
hence, Coding.class, GeeksforGeeks.class, Programming.class byte code files are
generated.
4. Combined functioning:
Layout: We can understand the structure by considering the following code snippet:
Java
// File name: GeeksforGeeks.java
// Package declaration
package myPackage;
// import statements
import classes;
// Class declaration
class Class2 {
class Class3 {
In order to understand the combined working of Java file structure, consider the
following program:
We have created three empty classes: GeeksforGeeks, Programming, and Coding, out
of which GeeksforGeeks class is declared as a public class.
Java
// Package statement
package myPackage;
class Programming {
class Coding {
We have saved the above Java source file with the name GeeksforGeeks.java as
GeeksforGeeks class is declared as public. Naming this file with a different name will
give us a compile-time error, as we have seen before.
Let us now compile the program with the help of the javac compiler through the
command prompt:
javac GeeksforGeeks.java
Output:
fig 10: Compiler Verdict
As you can see above, it compiles successfully without any errors, and three-byte code
files (.class) is generated: Coding.class, GeeksforGeeks.class, Programming.class.
We must understand the differences between JDK, JRE, and JVM before proceeding
further to Java. See the brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtual Machine, move to the next
page. Firstly, let's see the differences between the JDK, JRE, and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each
other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
More Details.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing
Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files
that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun
Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such
as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.
For example, an Employee class may contain all the employee details in the form of
variables and methods. If the class is instantiated i.e. if an object of the class is
created (say e1), we can access all the methods or properties of the class.
43.2M
700
Syntax:
1. <access specifier> class class_name
2. {
3. // member variables
4. // class methods
5. }
Java Class Example
Example 1:
Let's consider the following example to understand how to define a class in Java and
implement it with the object of class.
Calculate.java
1. // class definition
2. public class Calculate {
3.
4. // instance variables
5. int a;
6. int b;
7.
8. // constructor to instantiate
9. public Calculate (int x, int y) {
10. this.a = x;
11. this.b = y;
12. }
13.
14. // method to add numbers
15. public int add () {
16. int res = a + b;
17. return res;
18. }
19.
20. // method to subtract numbers
21. public int subtract () {
22. int res = a - b;
23. return res;
24. }
25.
26. // method to multiply numbers
27. public int multiply () {
28. int res = a * b;
29. return res;
30. }
31.
32. // method to divide numbers
33. public int divide () {
34. int res = a / b;
35. return res;
36. }
37.
38.
39. // main method
40. public static void main(String[] args) {
41. // creating object of Class
42. Calculate c1 = new Calculate(45, 4);
43.
44. // calling the methods of Calculate class
45. System.out.println("Addition is :" + c1.add());
46. System.out.println("Subtraction is :" + c1.subtract());
47. System.out.println("Multiplication is :" + c1.multiply());
48. System.out.println("Division is :" + c1.divide());
49.
50.
51. }
Output:
Example 2:
In the following example, we are creating two classes Employee and EmployeeClass.
The Employee class fetches and displays the employee details. In the EmployeeClass,
we create the objects of Employee class and use its methods. Here, we are initializing
the objects using the class constructor.
EmployeeClass.java
1. // class to get the employee details
2. class Employee {
3. // declaring variables
4. int emp_id;
5. String name;
6. String dept;
7. float salary;
8.
9. // method to initialize the variables
10. void add_info (int id, String n, String d, float sal) {
11. this.emp_id = id;
12. this.name = n;
13. this.dept = d;
14. this.salary = sal;
15. }
16.
17. // method to display the employee details
18. void display() {
19. System.out.println("Employee id: " + emp_id );
20. System.out.println("Employee name: " + name );
21. System.out.println("Employee department: " + dept );
22. System.out.println("Employee salary: " + salary );
23. }
24. }
25.
26. public class EmployeeClass {
27. public static void main(String[] args) {
28. // creating objects of class Employee
29. Employee e1 = new Employee();
30. Employee e2 = new Employee();
31. Employee e3 = new Employee();
32.
33. // calling the methods
34. e1.add_info (101, "Naman", "Salesforce", 45000);
35. e2.add_info (102, "Riya", "Tax", 25000);
36. e3.add_info (103, "Anu", "Development", 55000);
37.
38. e1.display();
39. e2.display();
40. e3.display();
41. }
42. }
Output:
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java:
local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a
name of the memory location. It is a combination of "vary + able" which means its
value can be changed.
1. int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.
Output:
20
Output:
10
10.0
Output:
10.5
10
Output:
130
-126
Output:
20
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Example:
1. Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.
Example:
1. byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
1. short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
1. int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.
Example:
1. long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never
be used for precise values, such as currency. Its default value is 0.0F.
Example:
1. float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:
1. double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.
Example:
1. char letterA = 'A'
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. The \u0000 is the
lowest range of Unicode system. To get detail explanation about Unicode visit next
page.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.
4.9M
59
Competitive questions on Structures
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be
accessed from outside the package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg
method of this package is declared as protected, so it can be accessed from outside
the class only through inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The default modifier is more restrictive than protected. That is why, there is a
compile-time error.
Methods are used to perform certain actions, and they are also known
as functions.
Why use methods? To reuse code: define the code once, and use it many
times.
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined
methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:
Example
Create a method inside Main:
// code to be executed
}
Example Explained
Java Methods
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
Example
Inside main, call the myMethod() method:
myMethod();
Example
public class Main {
myMethod();
myMethod();
myMethod();
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, /
etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
4.9M
Output:
10
12
12
10
Output:
22
21
Java Unary Operator Example: ~ and !
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}
Output:
-11
9
false
true
Output:
15
5
50
2
0
Output:
21
Output:
40
80
80
240
2
5
2
Output:
5
5
-5
1073741819
The bitwise & operator always checks both conditions whether first condition is true
or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}
Output:
false
10
false
11
The bitwise | operator always checks both conditions whether first condition is true
or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
Output:
true
true
true
10
true
11
Output:
Another Example:
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
Output:
14
16
Output:
13
9
18
9
Output:
1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
Output:
20
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean expression and
control the program flow depending upon the result of the condition provided.
There are two types of decision-making statements in Java, i.e., If statement and
switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program
is diverted depending upon the specific condition. The condition of the If statement
gives a Boolean value, either true or false. In Java, there are four types of if-
statements given below.
00:00/05:45
40.3M
916
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates
a Boolean expression and enables the program to enter a block of code if the
expression evaluates to true.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java
code.
Student.java
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }
Output:
x + y is greater than 20
2) if-else statement
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }
Output:
Delhi
4. Nested if-statement
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if(address.endsWith("India")) {
6. if(address.contains("Meerut")) {
7. System.out.println("Your city is Meerut");
8. }else if(address.contains("Noida")) {
9. System.out.println("Your city is Noida");
10. }else {
11. System.out.println(address.split(",")[0]);
12. }
13. }else {
14. System.out.println("You are not living in India");
15. }
16. }
17. }
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on
the variable which is being switched. The switch statement is easier to use instead of
if-else-if statements. It also enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
Consider the following example to understand the flow of the switch statement.
Student.java
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }
Output:
2
While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value. The switch
permits only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the
set of instructions in a repeated order. The execution of the set of instructions
depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
Calculation.java
1. public class Calculattion {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }
Output:
1. for(data_type var : array_name/collection_name){
2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop
in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10. }
Output:
Java
C
C++
Python
JavaScript
It is also known as the entry-controlled loop since the condition is checked at the
start of the loop. If the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }
Output:
0
2
4
6
8
10
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop
in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e., break
and continue.
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the
for loop.
BreakExample.java
1. public class BreakExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:
0
1
2
3
4
5
6
Calculation.java
1. public class Calculation {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. System.out.println(k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }
Output:
0
1
2
3
4
5
1. public class ContinueExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C+
+, we need to use the sizeof operator.
00:00/04:58
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We can
store primitive values or objects in an array in Java. Like C/C++, we can also create
single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
1. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Test it Now
Output:
10
20
70
40
50
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
1. //Java Program to illustrate the use of declaration, instantiation
2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}
Test it Now
Output:
33
3
4
5
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}
Output:
33
3
4
5
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any
array.
Let's see the simple example to get the minimum number of an array using a
method.
1. //Java Program to demonstrate the way of passing an array
2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}
Test it Now
Output:
1. //Java Program to demonstrate the way of passing an anonymous array
2. //to method.
3. public class TestAnonymousArray{
4. //creating a method which receives an array as a parameter
5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
9.
10. public static void main(String args[]){
11. printArray(new int[]{10,22,44,66});//passing anonymous array to method
12. }}
Test it Now
Output:
10
22
44
66
1. //Java Program to return an array from the method
2. class TestReturnArray{
3. //creating method which returns an array
4. static int[] get(){
5. return new int[]{10,30,50,90,60};
6. }
7.
8. public static void main(String args[]){
9. //calling method which returns an array
10. int arr[]=get();
11. //printing the values of an array
12. for(int i=0;i<arr.length;i++)
13. System.out.println(arr[i]);
14. }}
Test it Now
Output:
10
30
50
90
60
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length
of the array in negative, equal to the array size or greater than the array size while
traversing the array.
1. //Java Program to demonstrate the case of
2. //ArrayIndexOutOfBoundsException in a Java Array.
3. public class TestArrayException{
4. public static void main(String args[]){
5. int arr[]={50,60,70,80};
6. for(int i=0;i<=arr.length;i++){
7. System.out.println(arr[i]);
8. }
9. }}
Test it Now
Output:
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
1. int[][] arr=new int[3][3];//3 row and 3 column
1. //Java Program to illustrate the use of multidimensional array
2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Test it Now
Output:
1 2 3
2 4 5
4 4 5
1. //Java Program to illustrate the jagged array
2. class TestJaggedArray{
3. public static void main(String[] args){
4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
7. arr[1] = new int[4];
8. arr[2] = new int[2];
9. //initializing a jagged array
10. int count = 0;
11. for (int i=0; i<arr.length; i++)
12. for(int j=0; j<arr[i].length; j++)
13. arr[i][j] = count++;
14.
15. //printing the data of a jagged array
16. for (int i=0; i<arr.length; i++){
17. for (int j=0; j<arr[i].length; j++){
18. System.out.print(arr[i][j]+" ");
19. }
20. System.out.println();//new line
21. }
22. }
23. }
Test it Now
Output:
0 1 2
3 4 5 6
7 8
1. //Java Program to get the class name of array in Java
2. class Testarray4{
3. public static void main(String args[]){
4. //declaration and initialization of array
5. int arr[]={4,4,5};
6. //getting the class name of Java array
7. Class c=arr.getClass();
8. String name=c.getName();
9. //printing the class name of Java array
10. System.out.println(name);
11.
12. }}
Test it Now
Output:
1. public static void arraycopy(
2. Object src, int srcPos,Object dest, int destPos, int length
3. )
Example of Copying an Array in Java
1. //Java Program to copy a source array into a destination array in Java
2. class TestArrayCopyDemo {
3. public static void main(String[] args) {
4. //declaring a source array
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
6. 'i', 'n', 'a', 't', 'e', 'd' };
7. //declaring a destination array
8. char[] copyTo = new char[7];
9. //copying array using System.arraycopy() method
10. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
11. //printing the destination array
12. System.out.println(String.valueOf(copyTo));
13. }
14. }
Test it Now
Output:
caffein
1. //Java Program to clone the array
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. System.out.println("Printing original array:");
6. for(int i:arr)
7. System.out.println(i);
8.
9. System.out.println("Printing clone of the array:");
10. int carr[]=arr.clone();
11. for(int i:carr)
12. System.out.println(i);
13.
14. System.out.println("Are both equal?");
15. System.out.println(arr==carr);
16.
17. }}
Output:
1. //Java Program to demonstrate the addition of two matrices in Java
2. class Testarray5{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
8. //creating another matrix to store the sum of two matrices
9. int c[][]=new int[2][3];
10.
11. //adding and printing addition of 2 matrices
12. for(int i=0;i<2;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=a[i][j]+b[i][j];
15. System.out.print(c[i][j]+" ");
16. }
17. System.out.println();//new line
18. }
19.
20. }}
Test it Now
Output:
2 6 8
6 8 10
1. //Java Program to multiply two matrices
2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11. //multiplying and printing multiplication of 2 matrices
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=0;
15. for(int k=0;k<3;k++)
16. {
17. c[i][j]+=a[i][k]*b[k][j];
18. }//end of k loop
19. System.out.print(c[i][j]+" "); //printing matrix element
20. }//end of j loop
21. System.out.println();//new line
22. }
23. }}
Test it Now
Output:
6 6 6
12 12 12
18 18 18
Reference of programs
https://www.javatpoint.com/array-in-java