0% found this document useful (0 votes)
17 views44 pages

UNIT-1 Introduction - NOTES Java

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

UNIT-1 Introduction - NOTES Java

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

Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File

Structure,
and Compilation. Fundamental,
Programming Structures in Java: Defining Classes in Java, Constructors, Methods, Access
Specifies, Static Members, Final Members, Comments, Data types, Variables, Operators,
Control
Flow, Arrays & String.
Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class, Overriding,
Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and Abstract Class.
Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files for Library
Packages, Import and Static Import Naming Convention For Packages processor evolution and
types, microprocessor architecture and operation of its components, addressing modes,
interrupts, data transfer schemes, instruction and data flow, timer and timing diagram,
Interfacing

Introduction To Java
Java is an object-oriented, class-based programming language. The language is
designed to have as few dependencies implementations as possible. The intention of
using this language is to give relief to the developers from writing codes for every
platform. The term WORA, write once and run everywhere is often associated with this
language. It means whenever we compile a Java code, we get the byte code (.class file),
and that can be executed (without compiling it again) on different platforms provided
they support Java. In the year 1995, Java language was developed. It is mainly used to
develop web, desktop, and mobile devices. The Java language is known for its
robustness, security, and simplicity features. That is designed to have as few
implementation dependencies as possible.

History
The Java language has a very interesting history. Patrick Naughton, Mike Sheridan, and
Jame Gosling, known as the Green team, started the development of Java in the year
1991. These people were the engineers at Sun Microsystems. In 1996, the first public
implementation was released as Java 1.0. The compiler of Java 1.0 was rewritten by
Arthur Van Hoff to comply strictly with its specification. With the introduction of Java
2, the new versions have multiple different configurations that have been built for the
various platforms. It is worth noting that James Gosling is also known as the father of
Java.

The ISO standard body was approached by Sun Microsystems in the year 1997 to
formalize Java, but the process was withdrawn soon. At one point in time, Sun
Microsystems provided most of its implementation of Java available without any cost,
despite having the status of proprietary software.
Application Programs
The Implementation of an application program in Java application includes the
following steps.

1. The program creation (writing the code)


2. The program compilation.
3. Executing the compiled code.

It is worth noting here that JDK (Java Development Kit) should be installed properly on
the system, and the path should also be set.

The program Creation


The Java program can be written using a Text Editor (Notepad++ or NotePad or other
editors will also do the job.) or IDE (Eclipse, NetBeans, etc.).

FileName: TestClass.java

public class TestClass


{
// main method
public static void main(String []args)
{
// print statement
System.out.println("Hello World is my first Java Program.");
}
}

Write the above code and save the file with the name TestClass. The file should have
the .java extension.

The program Compilation

Open the command prompt, and type javac TestClass.java. javac is the command that
makes the Java compiler come to action to compile the Java program. After the
command, we must put the name of the file that needs to be compiled. In our case, it
is TestClass.java. After typing, press the enter button. If everything goes well, a
TestClass.class file will be generated that contains the byte code. If there is some error
in the program, the compiler will point it out, and TestClass.class will not be created.
The Terminologies in Java
JVM (Java Virtual Machine): JVM is the specification that facilitates the runtime
environment in which the execution of the Java bytecode takes place. Whenever one
uses the command java, an instance of the JVM is created. JVM facilitates the
definition of the memory area, register set, class file format, and fatal error reporting.
Note that the JVM is platform dependent.

Byte Code: It has already been discussed in the introductory part that the Java
compiler compiles the Java code to generate the .class file or the byte code. One has
to use the javac command to invoke the Java compiler.

Java Development Kit (JDK): It is the complete Java Development Kit that
encompasses everything, including JRE(Java Runtime Environment), compiler, java
docs, debuggers, etc. JDK must be installed on the computer for the creation,
compilation, and execution of a Java program.

Java Runtime Environment (JRE): JRE is part of the JDK. If a system has only JRE
installed, then the user can only run the program. In other words, only
the java command works. The compilation of a Java program will not be possible
(the javac command will not work).

Garbage Collector: Programmers are not able to delete objects in Java. In order to do
so, JVM has a program known as Garbage Collector. Garbage Collectors recollect or
delete unreferenced objects. Garbage Collector makes the life of a developer/
programmer easy as they do not have to worry about memory management.

Salient Features of Java


Platform Independent: Instead of directly generating the .exe file, Java compiler
converts the Java code to byte code, and this byte code can be executed on different
platforms without any issue, which makes Java a platform-independent language.
Note that in order to execute the byte code, JVM has to be installed on the system,
which is platform dependent.

Object-Oriented Programming Language: The concept of object-oriented


programing is based on the concept of objects and classes. Also, there are several
qualities that are present in object-oriented programming. A few of them are
mentioned below.

o Abstraction
o Inheritance
o Polymorphism
o Encapsulation

The Java language also extensively uses the concepts of classes and objects. Also, all
these features mentioned above are there in Java, which makes Java an object-oriented
programming language. Note that Java is an object-oriented programming language
but not 100% object-oriented.

Simple: Java is considered a simple language because it does not have the concept of
pointers, multiple inheritances, explicit memory allocation, or operator overloading.

Robust:
Java language is very much robust. The meaning of robust is reliable. The Java
language is developed in such a fashion that a lot of error checking is done as early as
possible. It is because of this reason that this language can identify those errors that
are difficult to identify in other programming languages. Exception Handling, garbage
collections, and memory allocation are the features that make Java robust.

Secure: There are several errors like buffer overflow or stack corruption that are not
possible to exploit in the Java language. We know that the Java language does not
have pointers. Therefore, it is not possible to have access to out-of-bound arrays. If
someone tries to do so, ArrayIndexOutofBound Exception is raised. Also, the execution
of the Java programs happens in an environment that is completely independent of
the Operating System, which makes this language even more secure.

Distributed: Distributed applications can be created with the help of the Java
language. Enterprise Java beans and Remote Method Invocation are used for creating
distributed applications. The distribution of Java programs can happen easily between
one or more systems that are connected to each other using the internet.

Multithreading: The Java language supports multithreading. The multithreading


feature supports the execution of two or more parts of the program concurrently. Thus,
the utilization of the CPU is maximized.

Portability: We know that Java is a platform-independent language. Thus, the byte


code generated on one system can be taken on any other platform for execution,
which makes Java portable.

High-Level Performance: The architecture of Java is created in such a fashion that it


decreases runtime overhead. In some places, Java uses JIT (Just In Time) compiler when
the code is compiled on a demand basis, where the compiler is only compiling those
methods that are invoked and thus making the faster execution of applications.
Dynamic Flexibility: The Java language follows the Object-Oriented programming
paradigm, which gives us the liberty to add new methods and classes to the existing
classes. The Java language also supports functions mentioned in C/C++ languages and
which are generally referred to as the native methods.

SandBox Execution: It is a known fact that Java programs are executed in different
environment, which gives liberty to users to execute their own applications without
impacting the underlying system using the bytecode verifier. The Bytecode verifier also
gives extra security as it checks the code for the violation of access.

Write Once Run Anywhere: The Java code is compiled by the compiler to get
the .class file or the byte code, which is completely independent of any machine
architecture.

Programs on Java
A few basic Java programs are mentioned below.
Program - 1
FileName: DemoClass.java
// Importing different classes
import java.io.*;

// Main class
public class DemoClass
{

// main method
public static void main(String argvs[])
{

System.out.println("Welcome to javaTpoint.");
}
}

Programming Structures in Java:


Defining Classes in Java, Constructors, Methods, Access
Specifies, Static Members, Final Members, Comments, Data types, Variables, Operators,
Control Flow, Arrays & String.

Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student named
Ravi is an object.

Properties of Java Classes


Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.

Class does not occupy memory.

Class is a group of variables of different data types and a group of methods.

A Class in Java can contain:

Data member

Method

Constructor

Nested Class

Interface

Class Declaration in Java


access modifier class <class name>
{
data member;
method;
constructor;
nested class;
interface;}
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-
life entities. Objects are the instances of a class that are created to use the attributes
and methods of a class. A typical Java program creates many objects, which as you
know, interact by invoking methods.

Abstraction
Abstraction is one of the key concepts of object-oriented programming (OOP)
languages. Its main goal is to handle complexity by hiding unnecessary details from the
user. This enables the user to implement more complex logic on top of the provided
abstraction without understanding about all the hidden complexity. For example,
people do not think of a car as a set of tens of thousands of individual parts. They think
of it as a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the desired location without worrying about the
complexity of the parts that form the car. They can ignore the details of how the engine,
transmission, and braking systems work. Instead, they are free to utilize the object as a
whole.

Abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared
abstract, it cannot be instantiated. So we cannot create an object of an abstract class.
Also, an abstract class can contain abstract as well as concrete methods.

To use an abstract class, we have to inherit it from another class where we have to
provide implementations for the abstract methods there itself, else it will also become
an abstract class.

Interface:
Interface in Java 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.

So an interface is a group of related methods with empty bodies.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. It
means to hide our data in order to make it safe from any modification.

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.

A java class is the example of encapsulation.

Encapsulation can be achieved in Java by:

Declaring the variables of a class as private.

Providing public setter and getter methods to modify and view the variables values.

Inheritance
This is a special feature of Object-Oriented Programming in Java. It lets programmers create
new classes that share some of the attributes of existing classes.
For e.g., 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
properties
whose are inherited is known as ‘Parent
class’.
Inheritance is classified into 4
types:

Single inheritance
It enables a derived class to inherit the properties and behavior from a single parent class.

Here, Class A is a parent class and Class B is a child class which inherits the properties and
behavior of the parent class.

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. as hierarchical inheritance.

Here, class B inherits the properties and behavior of class A and class C inherits the prop -
erties of class B. Class A is the parent class for B and class B is the parent class for C. So, class
C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical i
When a class has more than one child class (sub class), then such kind of inheritance is known

Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance. Since


multiple inheritance is not supported in Java as it leads to ambiguity, this type of inheritance
can only be achieved through the use of the interfaces.

Here, class A is a parent class for classes B and C, whereas classes B and C are the parent
classes of D which is the only child class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. It is the abilIn Java, compile time polymorphism refers to a process in which a call to an
overloaded method is resolved at compile time rather than at run time. Method overloading is

For eg, Bank is a base class that provides a method rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that
provide different rates of interest.
Polymorphism in Java is of two types:
Run time polymorphism.
Compile time polymorphism.

Run time polymorphism:


In Java, runtime polymorphism refers to a process in which a call to an overridden method
is resolved at runtime rather than at compile-time. Method overriding is an example of run
time polymorphism.

Compile time polymorphism:


an example of compile time polymorphism of a variable, function, or object to take on multiple
forms. In other words, polymorphism allows us to define one interface or method and have
multiple implementations. In Java, compile time polymorphism refers to a process in which a
call to an overloaded method is resolved at compile time rather than at run time. Method
overloading is an example of compile time polymorphism.

Variables
A variable is the holder that can hold the value while the java program is executed. A variable is
assigned with a datatype. It is the name of reserved area allocated in memory. In other words, it
is a name of memory location. There are three types of variables in java: local, instance and
static.

A variable provides us with named storage that our programs can manipulate. Each variable in
Java has a specific type, which determines the size and layout of the variable’s memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.

Before using any variable, it must be declared. The following statement expresses the basic
form of a variable declaration – datatype variable [ = value] [, variable [ = value] ...] ;

Here the data type is one of Java’s data types and variable is the name of the variable. To
declare more than one variable of the specified type, use a comma-separated list.

Example

int a, b, c; // Declaration of variables a, b, and c.

int a = 20, b = 30; // initialization byte B = 22; // Declaratrion


initializes a byte type variable B.

Types of Variables

There are three types of variables in java:


• local variable
• instance variable
• static variable

Fig. Types of variables

Local variable

Local variables are declared inside the methods, constructors, or blocks.

Local variables are created when the method, constructor or block is entered

Local variable will be destroyed once it exits the method, constructor, or block.

Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.

There is no default value for local variables, so local variables should be declared and an initial
value should be assigned before the first use.

Access specifiers cannot be used for local variables.

instance variable

A variable declared inside the class but outside the method, is called instance variable.
Instance variables are declared in a class, but outside a method, constructor or any block.

A slot for each instance variable value is created when a space is allocated for an object in the
heap.

Instance variables are created when an object is created with the use of the keyword ‘new’ and
destroyed when the object is destroyed.

Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object’s state that must be present throughout the class.

Instance variables can be declared in class level before or after use.

Access modifiers can be given for instance variables.

The instance variables are visible for all methods, constructors and block in the class. It is
recommended to make these variables as private. However, visibility for subclasses can be
given for these variables with the use of access modifiers.

Instance variables have default values.

○ numbers, the default value is 0,

○ Booleans it is false,

○ Object references it is null.

Values can be assigned during the declaration or within the constructor.

Instance variables cannot be declared as static.

Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they should
be called using the fully qualified name. ObjectReference.VariableName.

static variable
Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor, or a block.
Only one copy of each class variable per class is created, regardless of how many objects are
created from it.

Static variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final, and static. Constant variables never change from their
initial value.

Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.

Static variables are created when the program starts and destroyed when the program stops.

Visibility is the same as instance variables. However, most static variables are declared public
since they must be available for users of the class.

Default values are the same as instance variables.

○ numbers, the default value is 0;

○ Booleans, it is false.

○ Object references, it is null.

Values can be assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.

Static variables cannot be local.

Static variables can be accessed by calling with the class name Class Name. Variable Name.

When declaring class variables as public static final, then variable names (constants) are all in
upper case. If the static variables are not public and final, the naming syntax is the same as
instance and local variables.
Operators
Operator in java is a symbol that is used to perform operations. Java provides a rich set of
operators to manipulate variables. For example: +, -, *, / etc. All the Java operators can be
divided into the following groups −
Arithmetic Operators : Multiplicative : * / %
Additive :+-
Relational Operators
Comparison : < > <= >= instance of
Equality : == !=
Bitwise Operators
bitwise AND : & bitwise exclusive OR : ^ bitwise inclusive OR : |
Prefix : ++expr --expr +expr -expr

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations in the same way as they
are used in algebra. The following table lists the arithmetic operators −

Operator description example Output


+ (Addition ) Adds values A & B. A+B 30
- (Subtraction) Subtracts B from A A-B -10
* (Multiplication) Multiplies values A & B A*B 200
/ (Division) Divides B by A B/A 2
Divides left-hand operand by right-
% (Modulus) B%A 0
hand operand and returns remainder.

Shift operator: << >> >>>


Logical Operators logical AND : && logical OR : || logical NOT : ~ ! • Assignment
Operators: =
Ternary operator: ? :
Unary operator
Postfix : expr++ expr—
Example: int A=10,B=20;
// Java program to illustrate arithmetic operators public class Aoperators
{

public static void main(String[] args)

int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30; String x =


“Thank”, y = “You”;
System.out.println(“a + b = “+(a + b));

System.out.println(“a - b = “+(a - b)); System.out.println(“x + y = “+x + y);


System.out.println(“a * b = “+(a * b));

System.out.println(“a / b = “+(a / b));

System.out.println(“a % b = “+(a % b));

Relational
Operators
The following relational operators are supported by Java language.

Example:
int A=10,B=20;
Operator description example Output

Checks if the values of two operands are


== (equal to) equal or not, if yes then condition (A == B) true
becomes true.

Checks if the values of two operands


are equal or not, if values are not equal
!= (not equal to) (A != B) true
then condition becomes true.

Checks if the value of left operand is


> (greater than) greater than the value of right operand, if (A > B) true
yes then condition becomes true.

Checks if the value of left operand is less


< (less than) than the value of right operand, if yes then (A < B) true
condition becomes true.
Checks if the value of left operand is
>= (greater than greater than or equal to the value of right (A >= B) true
or equal to) operand, if yes then condition becomes true.

Checks if the value of left operand is less


<= (less than or than or equal to the value of right operand, (A <= B) true
equal to) if yes then condition becomes true.

boolean re-
checks whether the object is of a particular
type (class type or interface type) sult = name
instance of
(Object reference variable ) instanceof True
Operator instanceof
(class/interface type)
String;

// Java program to illustrate relational operators public class


operators
{

public static void main(String[] args)

{ int a = 20, b = 10;


boolean condition = true;
//various conditional operators

System.out.println(“a == b :” + (a == b));

System.out.println(“a < b :” + (a < b));

System.out.println(“a <= b :” + (a <= b));

System.out.println(“a > b :” + (a > b));

System.out.println(“a >= b :” + (a >= b));

System.out.println(“condition==true :” + (condition == true));

Java supports several bitwise operators, that can be applied to the integer types, long, int,
short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.
System.out.println(“a != b :” + (a != b));

}
}

Bitwise
Operators

Example:
int a = 60,b = 13; binary format of a & b will be
as follows − a = 0011 1100 b = 0000 1101
Bitwise operators follow the truth table:

a b a&b a|b a^b ~a

0 0 0 0 1 1

0 1 0 1 0 1

1 0 0 1 0 0

1 1 1 1 1 0

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators − int
A=60,B=13;
Operator description example Output

& (bitwise Binary AND Operator copies a (A & B) will give 12


and) bit to the result if it exists in both 12 which is (in binary f
operands. orm:00
00

1100)

| (bitwise or) Binary OR Operator copies a bit if it exists in (A | B) 61


either operand. (in binary
form: 0011
1101)
^ (bitwise (A ^ B) will give 49
Binary XOR Operator copies the bit if it is 49 which is 0011 (in binary
XOR)
set in one operand but not both. 0001 form: 0011
0001)

~ (bitwise Binary Ones Complement Operator is (~A) will give - -61


compliment) unary and has the effect of ‘flipping’ bits. 61 which is (in binary
1100 0011 in form: 1100
2’s 0011)
complement
form due to a
signed binary
number.

<< (left shift) A << 2 will give 240


The left operands value is moved left by 240 which is
the number of bits specified by the right (in binary
1111 0000 form: 1111
operand.
0000)

>> (right A >> 2 will give 15


shift) The left operands value is moved right by 15 which is 1111 (in binary
the number of bits specified by the right
operand. form:
1111)

>>> (zero fill The left operands value is moved right by A >>>2 will give 15
right the number of bits specified by the right 15 which is 0000 (in binary
operand and shifted values are filled up 1111 form: 0000
shift)
with zeros. 1111)

// Java program to illustrate bitwise operators public class


operators
{

public static void


main(String[] args)

System.out.println(“a&b = “ + (a & b));


System.out.println(“a|b = “ + (a | b));
System.out.println(“a^b = “ + (a ^ b));
System.out.println(“~a = “ + ~a);
}
{ int a = 10;
int b = 20;

Logical Operators
The following are the logical operators supported by java.

Example:
A=true;

B=false;

Operator description example Ouptput

&& (logical If both the operands are non-zero,


then the condition becomes true. (A && B) false
and)

|| (logical or) If any of the two operands are


nonzero, then the condition (A || B) true
becomes true.

! (logical not) Use to reverses the logical state of


its operand. If a condition is true
!(A && B) true
then Logical NOT operator will
make false.

assignment Operators
The following are the assignment operators supported by Java.
Operator description example

= Assigns values from right side oper- C=A+B


(Simple ands to left side operand. will assign
assignment value of A
operator) + B into C
+=
C += A is
(Add AND It adds right operand to the left operand and
equivalent
assignment assigns the result to left operand.
to C = C + A
operator)

-=
(Subtract
C -= A is
It subtracts right operand from the left operand
AND equivalent
and assigns the result to left operand.
to C = C – A
assignment
operator)

*=
(Multiply
C *= A is
It multiplies right operand with the left operand
AND equivalent
and assigns the result to left operand.
to C = C * A
assignment
operator)

/=
(Divide
C /= A is
It divides left operand with the right operand and
AND equivalent
assigns the result to left operand.
to C = C / A
assignment
operator)

%=
(Modulus C %= A is
It takes modulus using two operands and
AND equivalent
assigns the result to left operand.
assignment to C = C % A
operator)

C <<= 2 is
<<= Left shift AND assignment operator. same as

C = C << 2

C >>= 2 is
>>= Right shift AND assignment operator. same as

C = C >> 2

C &= 2 is
&= Bitwise AND assignment operator. same as

C=C&2
bitwise exclusive OR and assignment C ^= 2 is
^= operator. same as

C=C^2

C |= 2 is
|= bitwise inclusive OR and assignment operator. same as C

=C|2

// Java program to illustrate assignment operators


public class operators
{

public static void main(String[] args)

int a = 20, b = 10, c, d, e = 10, f = 4, g = 9; c=


b;
System.out.println(“Value of c = “ + c); a
+= 1;

b -= 1; e
*= 2; f /= 2;
System.out.println(“a, b, e, f = “ +
a + “,” + b + “,” + e + “,” + f);
}

Ternary
Operator
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean expressions. The goal
of the operator is to decide, which value should be assigned to the variable. The operator is
written as –
variable x = (expression) ? value if true : value if false

Following is an example − Example:


public class example

{
public static void main(String args[])

int a, b; a =
10;
b = (a == 0) ? 20: 30;

System.out.println( “b : “ + b );

Unary
Operators
Unary operators use only one operand. They are used to increment, decrement or negate a
value.

Operator description

- Unary minus negating the values

+ Unary plus converting a negative value to positive

++ :Increment operator incrementing the value by 1

— : Decrement operator decrementing the value by 1

! : Logical not operator inverting a boolean value

// Java program to illustrate unary operators public class


operators
{

public static void main(String[] args)


{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
boolean condition = true;
c = ++a;
System.out.println(“Value of c (++a) = “ + c);

c = b++;
System.out.println(“Value of c (b++) = “ + c);

c = --d;
System.out.println(“Value of c (--d) = “ + c);

c = --e;

System.out.println(“Value of c (--e) = “ + c);

System.out.println(“Value of !condition =” + !condition);

}
}

Precedence of java Operators


Operator precedence determines the grouping of operands in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −

For example, the following expression, x = 10 +


5 * 2;
is evaluated. So, the output is 20, not 30. Because operator * has higher precedence
than +.
The following table shows the operators with the highest precedence at the top of the table
and those with the lowest at the bottom. Within an expression, higher precedence operators
will be evaluated first.
category Operator associativity

Postfix >() [] . (dot operator) Left to right

Unary >++ - - ! ~ Right to left

Multiplicative >* / Left to right

Additive >+ - Left to right

Shift >>> >>> << Left to right


Relational >> >= < <= Left to right

Equality >== != Left to right

Bitwise AND >& Left to right

Bitwise XOR >^ Left to right

Bitwise OR Left to right

>|

Logical AND >&& Left to right

Logical OR >|| Left to right

Conditional ?: Right to left

Assignment >= += -= *= /= %= >>= Right to left

<<= &= ^= |=

Control Flow
Java Control statements control the flow of execution in a java program, based on data
values and conditional logic used. There are three main categories of control flow statements;
Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and assert.


Selection statements
The selection statements checks the condition only once for the program execution.

if statement:
The if statement executes a block of code only if the specified expression is true. If the value
is false, then the if block is skipped and execution continues with the rest of the program.

The simple if statement has the following syntax:


if (<conditional expression>)
<statement action>

The following program explains the if statement.


public class programIF{ public static void main(String[] args{

int a = 10, b = 20; if (a >


b)
System.out.println(“a > b”); if (a <
b)
System.out.println(“b < a”);

if-else statement

syntax:

if (<conditional expression>)

<statement action>

else

<statement action>

The following program explains the if-else statement.


public class ProgramIfElse

public static void main(String[] args)

{
int a = 10, b = 20; if (a >
b)
{

System.out.println(“a > b”);

} else
{

System.out.println(“b < a”);

}
}

switch case statement.

the flow of the program falls through to the next case. So, after every case, you must insert a
break statement.

The syntax of switch case is given as follows: switch


(<non-long integral expression>) { case
label1: <statement1> case label2: <statement2>


case labeln: <statementn>

default: <statement>

} // end switch

Iteration
Iteration statements execute a block of code for several numbers of times until the condi

While statement
while (<loop

condition>{<statements>}

Do-while Loop statement


The do-while loop is similar to the while loop, except that the test condition is performed at
the end of the loop instead of at the beginning. The do—while loop executes atleast once
without checking the condition.

The syntax of the do-while loop is do


<loop body> while (<loop
condition>);

Constructors
Every class has a constructor. If the constructor is not defined in the class, the Java
compiler builds a default constructor for that class. While a new object is created, at least one
constructor will be invoked. The main rule of constructors is that they should have the same
name as the class. A class can have more than one constructor.

Rules for writing Constructor

• Constructor(s) of a class must have same name as the class name in which it resides.
• A constructor in Java cannot be abstract, final, static and synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.

Following is an example of a constructor −


Example
public class myclass { public
myclass() { // Constructor
}
public myclass(String name) {

// This constructor has one parameter, name.

} types of

constructors
There are two type of constructor in Java:

1. no-argument constructor:
A constructor that has no parameter is known as default constructor.

If the constructor is not defined in a class, then compiler creates default constructor (with
no arguments) for the class. If we write a constructor with arguments or no-argument then
compiler does not create default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the
type.

// Java Program to illustrate calling a no-argument constructor import java.io.*; class


myclass
{
int num;
String name;
//this would be invoked while object of that class created.
System.out.println(“Constructor called”);
}
}
class myclassmain
{
public static void main (String[] args)
{
// this would invoke default constructor.
myclass m1 = new myclass();
// Default constructor provides the default values to the object like 0, null
System.out.println(m1.num);
System.out.println(m1.name);
}
}

2. Parameterized constructor
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with your own values, then use parameterized constructor.
// Java Program to illustrate calling of parameterized constructor.
import java.io.*; class myclass
{
// data members of the class. String name; int num;
// contructor with arguments. myclass(String name, int n)
// this would invoke parameterized constructor.
myclass m1 = new myclass(“Java”, 2017);
System.out.println(“Name :” + m1.name + “ num :” + m1.num);
this.name = name; this.num = n;
}
}
class myclassmain{
public static void main (String[] args)
{
}
}
There are no “return value” statements in constructor, but constructor returns current class
instance. We can write ‘return’ inside a constructor.

Methods in java
A method is a collection of statement that performs specific task. In Java, each method is a
part of a class and they define the behavior of that class. In Java, method is a jargon used for
method.

advantages of methods
• Program development and debugging are easier
• Increases code sharing and code reusability
• Increases program readability
• It makes program modular and easy to understanding
• It shortens the program length by reducing code redundancy types of methods
There are two types of methods in Java programming:

• Standard library methods (built-in methods or predefined methods)

User defined methods standard

library methods
The standard library methods are built-in methods in Java programming to handle tasks such
as mathematical computations, I/O processing, graphics, string handling etc. These methods
are already defined and come along with Java class libraries, organized in packages.
Packages Library methods descriptions
java.lang.Math acos() Computes arc cosine of the argument
All maths related exp() Computes the e raised to given power
methods are defined in abs() Computes absolute value of argument
this class
log() Computes natural logarithm
sqrt() Computes square root of the argument
pow() Computes the number raised to given
power
java.lang.String Returns
charAt() the char value at the specified
concat()
All string related methods compareTo()
are defined in this class Concatenates two string
indexOf()
Compares two string
Returns the index of the first occurrence
toUpperCase()
of the given character
converts all of the characters in the String

Example:
Program to compute square root of a given number using built-in method. public class
MathEx {
public static void main(String[] args) {
System.out.print(“Square root of 14 is: “ + Math.sqrt(14));
}
}
Sample Output:
Square root of 14 is: 3.7416573867739413

user-defined methods
The methods created by user are called user defined methods.

Every method has the following.

• Method declaration (also called as method signature or method prototype)


• Method definition (body of the method)
• Method call (invoke/activate the method) method declaration
The syntax of method declaration is:

Syntax:
return_type method_name(parameter_list);

Here, the return_type specifies the data type of the value returned by method. It will be void
if the method returns nothing. method_name indicates the unique name assigned to the
method. parameter_list specifies the list of values accepted by the method.
method Definition
Method definition provides the actual body of the method. The instructions to complete a
specific task are written in method definition. The syntax of method is as follows:

Syntax:
modifier return_type method_name(parameter_list){

// body of the method

}
Here,

Modifier – Defines the access type of the method i.e accessibility re-
gion of method in the application

return_type – Data type of the value returned by the method or void if


method returns nothing
method_name – Unique name to identify the method. The name must
follow the rules of identifier
parameter_list – List of input parameters separated by comma. It must be
like
datatype parameter1,datatype parameter2,……
List will be empty () in case of no input parameters.
method body – block of code enclosed within { and } braces to perform
specific task

Method Overloading
Method overloading is the process of having multiple methods with same name that differs
in parameter list. The number and the data type of parameters must differ in overloaded
methods. It is one of the ways to implement polymorphism in Java. When a method is called,
the overloaded method whose parameters match with the arguments in the call gets invoked.

Note: Overloaded methods are differentiable only based on parameter list and not on their
return type.

Example: Program for addition using Method Overloading class MethodOverload{ void
add(){
System.out.println(“No parameters”);
}
void add(int a,int b){ // overloaded add() for two integer parameter
System.out.println(“Sum:”+(a+b));
}
void add(int a,int b,int c){ // overloaded add() for three integer parameter
System.out.println(“Sum:”+(a+b+c));
}
void add(double a,double b){ // overloaded add() for two double parameter
System.out.println(“Sum:”+(a+b));
}
}
public class Main {
public static void main(String[] args) { MethodOverload obj=new MethodOverload();
obj.add(); // call all versions of add() obj.add(1,2); obj.add(1,2,3);
obj.add(12.3,23.4);
}
}
Sample Output:
No parameters
Sum:3
Sum:6
Sum:35.7
Here, add() is overloaded four times. The first version takes no parameters, second takes
two integers, third takes three integers and fourth accepts two double parameter.

Access specifiers
Access specifiers or access modifiers in java specifies accessibility (scope) of a data
member, method, constructor or class. It determines whether a data or method in a class can
be used or invoked by other class or subclass.

Types of access Specifiers


There are 4 types of java access specifiers:

1. Private
2. Default (no speciifer)
3. Protected
4. Public
The details about accessibility level for access specifiers are shown in following table.
access modifiers default Private Protected Public
Accessible inside the class Yes Yes Yes Yes
Accessible within the subclass
Yes No Yes Yes
inside the same package
Accessible outside the package No No No Yes
Accessible within the subclass
No No Yes Yes
outside the package

Private access modifier


Private data fields and methods are accessible only inside the class where it is declared i.e
accessible only by same class members. It provides low level of accessibility. Encapsulation
and data hiding can be achieved using private specifier.

Example:
Role of private specifier class
PrivateEx{ private int x; public
int y; private
// private data
PrivateEx(){} public
// public data
PrivateEx(int a,int b){ // private constructor
x=a; y=b; // public constructor
}
}
public class Main {

public static void main(String[] args) {

PrivateEx obj1=new PrivateEx(); // Error: private constructor cannot be applied

PrivateEx obj2=new PrivateEx(10,20); // public constructor can be applied to obj2


System.out.println(obj2.y); // public data y is accessible by a non-member
System.out.println(obj2.x); //Error: x has private access in PrivateEx

}
}
In this example, we have created two classes PrivateEx and Main. A class contains private
data member, private constructor and public method. We are accessing these private
members from outside the class, so there is compile time error.

Default access modifier


If the specifier is mentioned, then it is treated as default. There is no default specifier
keyword. Using default specifier we can access class, method, or field which belongs to same
package, but not from outside this package.

Example:

public static void main(String[] args) {


Role of default specifier class DefaultEx{ int y=10; // default data
} public class Main {
DefaultEx obj=new DefaultEx();
System.out.println(obj.y);
}
}

public static void main(String[] args) {

// default datay is accessible outside the class


In this example, show() of class Base is declared as protected, so it can be accessed from
outside the class only through inheritance. Chapter 2 explains the concept of inheritance in

Protected access modifier


Protected methods and fields are accessible within same class, subclass inside same
package and subclass in other package (through inheritance). It cannot be applicable to class
and interfaces.

Example:
Role of protected specifier

class Base
{ protected void show(){
System.out.println(“In Base”);
}
} public class Main extends Base
{ public static void main(String[] args)
{ Main obj=new Main();

}
Public access modifier
The public access specifier has highest level of accessibility. Methods, class, and fields
declared as public are accessible by any class in the same package or in other package.

Example:
Role of public specifier
class PublicEx{ public int
no=10;
}
public class Main{ public static void

main(String[] args) {
PublicEx obj=new PublicEx();

System.out.println(obj.no);

}
}

• Static Keyword

• import (static import) static variable

manly shared by all objects of the class.


• Memory allocation for such variables only happens once when the class is loaded in the
memory.
• scope of the static variable is class scope ( accessible only inside the class)
• lifetime is global ( memory is assigned till the class is removed by JVM).
• Automatically initialized to 0.
• It is accessible using ClassName.variablename
• Static variables can be accessed directly in static and non-static methods.
Example :

Without static With static

class staticex{

static int no=10;


class staticex{
Staticex(){
int no=10;
System.out.println(no);
Staticex(){
no++;
System.out.println(no);
}
no++;
}
}
public class m ain{
} public class main{ public static void
public static void main(String[] args)
main(String[] args)
{
{

Staticex obj1=new Staticex(); Static e x obj1=new Static e x();

Staticex obj2=new Staticex(); Static e x obj2=new Static e x();

Staticex obj3=new Staticex(); Static e x obj3=new Static e x();

} }

} }

Sample Output: Sample Output:

10 10

10 11

10 12
Example:
class StaticEx{
static int x; int y=10; static void display(){
System.out.println(“Static Method “+x); // static method accessing static variable
}
public void show(){
System.out.println(“Non static method “+y);
System.out.println(“Non static method “+x); // non-static method can access static
variable
}
}
public class Main
{
public static void main(String[] args) {
StaticEx obj=new StaticEx();
StaticEx.display(); // static method invoked without using object
obj.show();

A static block is a block of code enclosed in braces, preceded by the keyword static.

• The statements within the static block are first executed automatically before main when
the class is loaded into JVM.
• A class can have any number of static blocks.
• JVM combines all the static blocks in a class as single block and executes them.
• Static methods can be invoked from the static block and they will be executed as and
when the static block gets executed.
Syntax:
static{
…………….
}
Example:
class StaticBlockEx{

StaticBlockEx (){
System.out.println(“Constructor”);
static void show(){
} static {
System.out.println(“Inside method”);

System.out.println(“Second static block”);

public static void main(String[] args) {


StaticBlockEx obj=new StaticBlockEx ();
System.out.println(“First static block”);

} static{

show();

static{

System.out.println(“Static in main”);

}
}

Nested class (static class)


Nested class is a class declared inside another class. The inner class must be a static class
declared using keyword static. The static nested class can refer directly to static members of
the enclosing classes, even if those members are private.

Syntax:
class OuterClass{

……..
static class InnerClass{

class Outer{ static int x=10;


static class Inner{ int
y=20; public void show(){
System.out.println(x+y); // nested class accessing its own data & outer class static
data
}
}
} class Main{
public static void main(String args[]){
Outer.Inner obj=new Outer.Inner(); // Creating object for static nested class
obj.show();
}
}
Sample Output:30

static
import
The static import allows the programmer to access any static members of imported class
directly. There is no need to qualify it by its name.

Syntax:
Import static package_name;

Advantage:
• Less coding is required if you have access any static member of a class oftenly.
Disadvantage:
Overuse of static import makes program unreadable and unmaintable.

Arrays
Array is a collection of elements of similar data type stored in contiguous memory location.
The array size is fixed i.e we can’t increase/decrease its size at runtime. It is index based and
the first element is stored at 0th index.

Advantages of Array
• Code Optimization: Multiple values can be stored under common name. Date retrieval or
sorting is an easy process.
• Random access: Data at any location can be retrieved randomly using the index.
Disadvantages of Array
• Inefficient memory usage: Array is static. It is not resizable at runtime based on number
of user’s input. To overcome this limitation, Java introduce collection concept.

types of array
There are two types of array.
• One Dimensional Array
• The syntax for declaring an array variable is

dataType[] arrayName;

dataType arrayName [];

Declaring Array Variables

Syntax:

an identifier.

Example:
int[] a;

instantiation of an array
Array can be created using the new keyword. To allocate memory for array elements we
must mention the array size. The size of an array must be specified by an int value and not long
or short. The default initial value of elements of an array is 0 for numeric types and false for
boolean.

Syntax:
arrayName=new datatype[size];

Or
dataType[] arrayName=new datatype[size]; //declaration and instantiation

Example:
int[] a=new int[5]; //defining an integer array for 5 elements

Alternatively, we can create and initialize array using following syntax.

Syntax:
dataType[] arrayName=new datatype[]{list of values separated by comma};

Or
dataType[] arrayName={ list of values separated by comma};

Example:
int[] a={12,13,14}; int[]
a=new int[]{12,13,14};
The built-in length property is used to determine length of the array i.e. number of ele -

The array elements can be accessed by using indices. The index starts from 0 and ends at
( array size-1). Each element in an array can be accessed usingfor loop.

public static void main(String args[]){


int a[]=new int[]{10,20,30,40};//declaration and initialization
ments present in an array. accessing
array elements

Example:
Program to access array elements. class
Main{

//printing array

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}
}
Sample Output:
10
20
30
40
the for-each loop
The for-each loop is used to traverse the complete array sequentially without using an index
variable. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList).
Syntax:
for(type var:arrayName){ Statements
using var;
}
Example:
Program to calculate sum of array elements. class
Main{

int sum=0; for(int


i:a) sum+=i;
System.out.println(“Sum:”+sum);

}
}
Sample Output:

Sum:100

multidimensional arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays.

Syntax:
dataType[][] arrayName=new datatype[rowsize][columnnsize]; // 2 dimensional array
dataType[][][] arrayName=new datatype[][][];

Program to access 2D array elements


class TwoDimEx {
public static void main(String args[])

// declaring and initializing 2D array


int arr[][] = { {1,1,12},{2,16,1},{12,42,2} };
// printing 2D array
for (int i=0; i< arr.length; i++)
{

for (int j=0; j < arr[i].length ; j++)

System.out.print(arr[i][j] + “ “);
System.out.println();

}
}
}

jagged array
Jagged array is an array of arrays with different row size i.e. with different dimensions.

Example:
class Main {

public static void main(String[] args) {

int[][] a = {

{11, 3, 43},

{3, 5, 8, 1},

{9},

};

System.out.println(“Length of row 1: “ + a[0].length);


System.out.println(“Length of row 2: “ + a[1].length);
System.out.println(“Length of row 3: “ + a[2].length);
}

Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

Char Sequence Interface


The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create
strings in Java by using these three classes.

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

You might also like