0% found this document useful (0 votes)
17 views

Java

Uploaded by

Rashmi Deshpande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java

Uploaded by

Rashmi Deshpande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 95

Siddhant College Of Engineering

What is Java?

Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995.

James Gosling is known as the father of Java. Before Java, its name was Oak.

Since Oak was already a registered company, so James Gosling and his team changed the
name from Oak to Java.

The team initiated this project to develop a language for digital devices such as set-top
boxes, television, etc.

Originally C++ was considered to be used in the project but the idea was rejected for
several reasons(For instance C++ required more memory).

Gosling endeavoured to alter and expand C++ however before long surrendered that
for making another stage called Green.

James Gosling and his team called their project “Greentalk” and its file extension
was .gt and later became to known as “OAK”. Why “Oak”? The name Oak was used
by Gosling after an oak tree that remained outside his office.

Features of Java
Siddhant College Of Engineering

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:

Java syntax is based on 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.

concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
Siddhant College Of Engineering

6. Encapsulation

C++ vs Java

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for Java is mainly used for application
system programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile applications.

Design Goal C++ was designed for Java was designed and created as
systems and applications an interpreter for printing systems
programming. It was an but later extended as a support
extension of the C network computing. It was
programming language designed to be easy to use and
accessible to a broader audience.
.

Goto C++ supports the goto Java doesn't support the goto
statement.
statement.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by using interfaces in java
.

Operator C++ supports operator Java doesn't support operator


Overloading overloading overloading.
.

Pointers C++ supports pointers Java supports pointer internally.


However, you can't write the
. You can write a pointer
pointer program in java. It means
program in C++.
java has restricted pointer support
Siddhant College Of Engineering

in java.

Compiler and C++ uses compiler only. C+ Java uses both compiler and
Interpreter + is compiled and run using interpreter. Java source code is
the compiler which converts converted into bytecode at
source code into machine compilation time. The interpreter
code so, C++ is platform executes this bytecode at runtime
dependent. and produces output. Java is
interpreted that is why it is
platform-independent.

Call by Value C++ supports both call by Java supports call by value only.
and Call by value and call by reference. There is no call by reference in
reference java.

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in Java has built-in thread
support for threads. It relies
support.
on third-party libraries for
thread support.

Documentation C++ doesn't support Java supports documentation


comment documentation comments. comment (/** ... */) to create
documentation for java source
code.

Virtual Keyword C++ supports virtual Java has no virtual keyword. We


keyword so that we can can override all non-static methods
decide whether or not to by default. In other words, non-
override a function. static methods are virtual by
default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the
top for the negative numbers. For
positive numbers, it works same
like >> operator.

Inheritance Tree C++ always creates a new Java always uses a single
inheritance tree. inheritance tree because all classes
Siddhant College Of Engineering

are the child of the Object class in


Java. The Object class is the root of
the inheritance
tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with


hardware.

Object-oriented C++ is an object-oriented Java is also an object-oriented


language. However, in the C
language. However, everything
language, a single root
(except fundamental types) is an
hierarchy is not possible.
object in Java. It is a single root
hierarchy as everything gets
derived from java.lang.Object.

Class

1. Class is a set of object which shares common characteristics/ behavior and common
properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint or prototype from
which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of methods.

Syntax to declare a class:


access_modifier class<class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
Siddhant College Of Engineering

classStudent
{
intid;//data member (also instance variable)
String name; //data member (also instance variable)

publicstaticvoidmain(String args[])
{
Student s1=newStudent();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Defining a Class in Java

Java provides a reserved keyword class to define a class. The keyword must be followed by
the class name. Inside the class, we declare methods and variables.

In general, class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by convention).
4. 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.
5. 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.
6. Body: The class body surrounded by braces, { }.

Syntax:
1. <access specifier> class class_name
2. {
3. // member variables
4. // class methods
5. }
Siddhant College Of Engineering

Accessing Class Members in Java

Instance variables and methods are accessed via objects with the help of a dot (.) operator.
The dot operator creates a link between the name of the instance variable and the name of the
class with which it is used.

class Employee
{
String name;
int age;
float bsal, gsal;

public void acceptDetails(String n, int a, int s)


{
name = n;
age = a;
bsal = s;
}
public void showData()
{
System.out.println("Employee Name = " + name);
System.out.println("Employee Age = " + age);
System.out.println("Employee Basic Salary = " + bsal);
System.out.println("Employee Gross Salary = " + gsal);
}
void cal() // public by default
{
gsal = bsal - (bsal*5/100);
}

public static void main(String args [])


{
Employee e1 = new Employee(); // object e1 created
e1.acceptDetails("Nancy", 28, 12000);
e1.cal();
e1.showData();
}}

field declaration in Java


Java is an object-oriented programming language which uses “object” concept to group data
and methods in a class.
A variable defined in a class is called a field.
A field is declared by specifying its type and name.
 Declare a field for the primitive data type, object, and collection
Siddhant College Of Engineering

 Add static , final , transient , and access modifiers to fields


 Access fields via Java reflection
 Inherits fields from the parent class

Object

It is a basic unit of Object-Oriented Programming and represents 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.
Example of an object: dog

How to Create Object in Java

The object is a basic building block of an OOPs language.

In Java, we cannot execute any program without creating an object.

There is various way to create an object in Java that we will discuss in this section, and also
learn how to create an object in Java.

Java provides five ways to create an object.

o Using new Keyword


o Using clone() method
o Using newInstance() method of the Class class
o Using newInstance() method of the Constructor class
o Using Deserialization
Siddhant College Of Engineering

Using new Keyword

Using the new keyword is the most popular way to create an object or instance of the class.
When we create an instance of the class by using the new keyword, it allocates memory
(heap) for the newly created object and also returns the reference of that object to that
memory. The new keyword is also used to create an array.

The syntax for creating an object is:

ClassName object = new ClassName();

1. public class CreateObjectExample1


2. {
3. void show()
4. {
5. System.out.println("Welcome to javaTpoint");
6. }
7. public static void main(String[] args)
8. {
9. //creating an object using new keyword
10. CreateObjectExample1 obj = new CreateObjectExample1();
11. //invoking method using the object
12. obj.show();
13. }
14. }

Method in Java

a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task.

It provides the reusability of code. We can also easily modify code using methods.

The most important method in Java is the main() method.

Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method
Siddhant College Of Engineering

Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }

User-defined Method

The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.

How to Create a User-defined Method


1. //user defined method
2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }
Siddhant College Of Engineering

Method Declaration

The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
Siddhant College Of Engineering

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

What is token in Java?

The Java compiler breaks the line of code into text (words) is called Java tokens.

These are the smallest element of the Java program.

The Java compiler identified these words as tokens.

These tokens are separated by the delimiters.

It is useful for compilers to detect errors. Remember that the delimiters are not part of the
Java tokens.

token <= identifier | keyword | separator | operator | literal | comment


Siddhant College Of Engineering

For example, consider the following code.

1. public class Demo


2. {
3. public static void main(String args[])
4. {
5. System.out.println("javatpoint");
6. }
7. }

In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [, ], ),
System, ., out, println, javatpoint, etc. are the Java tokens.

java token includes the following:

o Keywords

These are the pre-defined reserved words of any programming language.


Each keyword has a special meaning. It is always written in lower case.

o Identifiers

Identifiers are used to name a variable, constant, function, class, and array.

It usually defined by the user.

It uses letters, underscores, or a dollar sign as the first character.

The label is also known as a special kind of identifier that is used in the goto statement.

Remember that the identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.

o Literals

In programming literal is a notation that represents a fixed value (constant) in


the source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It
Siddhant College Of Engineering

is defined by the programmer. Once it has been defined cannot be changed. Java provides
five types of literals are as follows:

o Integer
o Floating Point
o Character
o String
o Boolean

o Operators

In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:

o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

o Separators

The separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:

separator <= ; | , | . | ( | ) | { | } | [ | ]

o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
Siddhant College Of Engineering

o Comma (,): It is used to separate two values, statements, and parameters.


o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.

o Comments

Comments allow us to specify information about the program inside our Java code.

Java compiler recognizes these comments as tokens but excludes it form further processing.

The Java compiler treats comments as whitespaces. Java provides the following two types of
comments:

o Line Oriented: It begins with a pair of forwarding slashes (//).


o Block-Oriented: It begins with /* and continues until it founds */.

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.

It is a combination of "vary + able" which means its value can be changed.

What do you mean by a dynamic initialization of variables?

Dynamic initialization of object refers to initializing the objects at run time i.e. the initial
value of an object is to be provided during run time.
Siddhant College Of Engineering

Dynamic initialization can be achieved using constructors and passing parameters values to
the constructors.

This type of initialization is required to initialize the class variables during run time.

If any variable is not assigned with value at compile-time and assigned at run time is
called dynamic initialization of a variable.

publicclass Main {
publicstaticvoidmain(String args[]) {

// c is dynamically initialized
double c = Math.sqrt(2 * 2);

System.out.println("c is " + c);


}
}
What is the Scope of a Variable?

In programming, a variable can be declared and defined inside a class, method, or block. It
defines the scope of the variable i.e. the visibility or accessibility of a variable. Variable
declared inside a block or method are not visible to outside. If we try to do so, we will get a
compilation error. Note that the scope of a variable can be nested.

o We can declare variables anywhere in the program but it has limited scope.
o A variable can be a parameter of a method or constructor.
o A variable can be defined and declared inside the body of a method and constructor.
o It can also be defined inside blocks and loops.
o Variable declared inside main() function cannot be accessed outside the main()
function

There are types of variables based on their scope:

o Member Variables (Class Level Scope)


o Local Variables (Method Level Scope)
Siddhant College Of Engineering

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:

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.

What is Constant in Java?


A constant is something that in immutable. In Java programming constant is an variable
whose value cannot be changes once it has been assgined.

Constants can be declared using Java's static and final keywords. The static keyword is used
for memory management and final keyword signifies the property that the value of the
variable cannot be changed. It makes the primitive data types immutable.

Types of Constants

There are the following types if constants in Java:

1. Numeric Constants
o Integer Constants
o Real Constants
2. Non-numeric Constants
o Character Constants
o String Constants

Syntax for Java Constants

staticfinal datatype identifier_name = constant;

Example:

staticfinalfloat PI = 3.14f;
Siddhant College Of Engineering

public class Declaration {

static final double PI = 3.14;

public static void main(String[] args) {

System.out.println("Value of PI: " + PI);

Symbolic Constants in Java?


Constants may appear repeatedly in number of places in the program. Constant values are
assigned to some names at the beginning of the program, then the subsequent use of
these names in the program has the effect of caving their defined values to be
automatically substituted in appropriate points. The constant is declared as follows:

Syntax : final type symbolicname= value;


Eg final float PI =3.14159;
final int STRENGTH =100;

symbolic names take the some form as variable names. But they one written in capitals
to distance from variable names. This is only convention not a rule.

After declaration of symbolic constants they shouldn’t be assigned any other value with
in the program by using an assignment statement.

For eg:- STRENTH = 200 is illegal


Siddhant College Of Engineering

Type conversion in Java


Java provides various data types just likely any other dynamic languages such as boolean,
char, int, unsigned int, signed int, float, double, long, etc in total providing 7 types where
every datatype acquires different space while storing in memory.

When you assign a value of one data type to another, the two types might not be compatible
with each other.
If the data types are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion, and if not then they need to be cast or converted
explicitly.

Datatyp
e Bits Acquired In Memory

boolean 1

byte 8 (1 byte)

char 16 (2 bytes)

short 16(2 bytes)

int 32 (4 bytes)

long 64 (8 bytes)

float 32 (4 bytes)

double 64 (8 bytes)

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted. This
happens when:
 The two data types are compatible.
 When we assign a value of a smaller data type to a bigger data type.
Siddhant College Of Engineering

// Java Program to Illustrate Automatic Type Conversion

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
int i = 100;

// Automatic type conversion


// Integer to long type
long l = i;

// Automatic type conversion


// long to float type
float f = l;

// Print and display commands


System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}
Siddhant College Of Engineering

Narrowing or Explicit Conversion


If we want to assign a value of a larger data type to a smaller data type we perform explicit
type casting or narrowing.

// Java program to illustrate Incompatible data Type


// for Explicit Type Conversion

// Main class
public class GFG {

// Main driver method


public static void main(String[] argv)
{

// Declaring character variable


char ch = 'c';
// Declaringinteger variable
int num = 88;
// Trying to insert integer to character
ch = num;
}
}
Siddhant College Of Engineering

Type Promotion in Expressions


While evaluating expressions, the intermediate value may exceed the range of operands and
hence the expression value will be promoted. Some conditions for type promotion are:
1. Java automatically promotes each byte, short, or char operand to int when evaluating an
expression.
2. If one operand is long, float or double the whole expression is promoted to long, float,
or double respectively.

// Java program to Illustrate Type promotion in Expressions

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Declaring and initializing primitive types


byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

// The Expression
double result = (f * b) + (i / c) - (d * s);

// Printing the result obtained after


// all the promotions are done
System.out.println("result = " + result);
}
Siddhant College Of Engineering

Operators in Java

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
Arithmetic Operators

These operators involve the mathematical operators that can be used to perform various
simple or advanced arithmetic operations on the primitive data types referred to as the
operands.

class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
Siddhant College Of Engineering

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


// modulo operator
System.out.println("a % b = " + (a % b));
}
}

Java Relational Operators

Relational operators are used to check the relationship between two operands.

The return value of a comparison is either true or false. These values are known as Boolean
values.

For example,

// check if a is less than b


a < b;

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

class Main {
public static void main(String[] args) {
Siddhant College Of Engineering

// create variables
int a = 7, b = 11;

// value of a and b
System.out.println("a is " + a + " and b is " + b);

// == operator
System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator
System.out.println(a > b); // false

// < operator
System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}
Siddhant College Of Engineering

Java Assignment Operator


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

Java Assignment Operator Example


public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}

Java Logical Operators


Logical operators are used to performing logical “AND”, “OR” and “NOT” operations, i.e.
the function similar to AND gate and OR gate in digital electronics.
Logical operators are used to check whether an expression is true or false. They are used in
decision making.

Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and


AND) expression2 expression2 are true

|| (Logical expression1 || true if either expression1 or


OR) expression2 expression2 is true

! (Logical true if expression is false and


!expression
NOT) vice versa

// Java code to illustrate


Siddhant College Of Engineering

// logical AND operator

import java.io.*;

class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;

// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);

// using logical AND to verify


// two constraints
if ((a < b) && (b == c)) {
d = a + b + c;
System.out.println("The sum is: " + d);
}
else
System.out.println("False conditions");
}
}
Siddhant College Of Engineering

Example 2
class Logicaloperator {
public static void main(String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Siddhant College Of Engineering

Java Unary Operators


Unary operators are used with only one operand. For example, ++ is a unary operator that
increases the value of a variable by 1. That is, ++5 will return 6.

Different types of unary operators are:

Operator Meaning

Unary plus: not necessary to use since numbers are positive without
+
using it

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a boolean

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

// declare variables
int a = 12, b = 12;
int result1, result2;

// original value
System.out.println("Value of a: " + a);

// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
Siddhant College Of Engineering

System.out.println("Value of b: " + b);

// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
Example 2
// Java Program to Illustrate Unary NOT Operator
// Importing required classes
import java.io.*;
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
booleancond = true;
int a = 10, b = 1;

// Displaying values stored in above variables


System.out.println("Cond is: " + cond);
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);

// Displaying values stored in above variables


// after applying unary NOT operator
System.out.println("Now cond is: " + !cond);
Siddhant College Of Engineering

System.out.println("!(a < b) = " + !(a < b));


System.out.println("!(a > b) = " + !(a > b));
}
}

Java Bitwise Operators


Bitwise operators in Java are used to perform operations on individual bits.

For example,

Bitwise complement Operation of 35

35 = 00100011 (In Binary)

~ 00100011
________
11011100 =220 (In decimal)

Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0).

The various bitwise operators present in Java are:

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR
publicclassbitwiseop {
publicstaticvoidmain(String[] args) {
//Variables Definition and Initialization
Siddhant College Of Engineering

int num1 =30, num2 =6, num3 =0;

//Bitwise AND
System.out.println("num1 & num2 = "+ (num1 & num2));

//Bitwise OR
System.out.println("num1 | num2 = "+ (num1 | num2) );

//Bitwise XOR
System.out.println("num1 ^ num2 = "+ (num1 ^ num2) );

//Binary Complement Operator


System.out.println("~num1 = "+~num1 );

//Binary Left Shift Operator


num3 = num1 <<2;
System.out.println("num1 << 1 = "+ num3 );

//Binary Right Shift Operator


num3 = num1 >>2;
System.out.println("num1 >>1 = "+ num3 );

//Shift right zero fill operator


num3 = num1 >>>2;
System.out.println("num1 >>> 1 = "+ num3 );

}
}

Java instanceof Operator


The instanceof operator checks whether an object is an instanceof a particular class.
This operator gives the boolean values such as true or false. If it relates to a specific class,
then it returns true as output. Otherwise, it returns false as output.
Syntax:
object-reference instanceof type;

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

String str = "Programiz";


boolean result;

// checks if str is an instance of


// the String class
Siddhant College Of Engineering

result = str instanceof String;


System.out.println("Is str an object of String? " + result);
}
}

Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,

variable = Expression ? expression1 : expression2

class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Java Mathematical Functions

Java Mathematical functions are predefined functions which accept values and return the
result. To use mathematical functions, we have to use Math class in our program.

With the help of mathematical functions we can easily solve a complex equation in our
program, for example, if we want to find the square root of a number, then we can
use sqrt() mathematical function to find the square root of a given number.

pow() Function

The pow() function is used to computes the power of a number.


Syntax of pow() function
doublepow(double x,double y);
Siddhant College Of Engineering

sqrt() Function

The sqrt() function returns the square root of a positive number. Remember that square root
of a negative can not be calculated.
Syntax of sqrt() function
doublesqrt(doublenum);

max() Function

The max() function returns the greater among two numbers. The number can be
an integer, long, float or double value.

Syntax of max() function


intmax(int a,int b);

min() Function

The min() function returns the smallest among two numbers. The number can be
an integer, long, float or double value.
Syntax of min() function
intmin(int a,int b);

abs() Function

The abs() function returns the absolute value of a number. The number can be
an integer, long, float or double value. Here Absolute value means number without negative
sign. The absolute value of a number is always positive.
Syntax of abs() function
intabs(intnum);
Siddhant College Of Engineering

Java Math exp()

The Java Math exp() method returns the Euler's number e raised to the power of the specified
value.

The syntax of the exp() method is:


Math.exp(double a)

Java Math round()

The round() method rounds the specified value to the closest int or long value and returns it.

The syntax of the round() method is:

Math.round(value)

The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax

if(condition){

// block of code to be executed if the condition is true

1. //Java Program to demonstate the use of if statement.


2. public class IfExample {
3. public static void main(String[] args) {
4. //defining an 'age' variable
5. int age=20;
6. //checking the age
7. if(age>18){
8. System.out.print("Age is greater than 18");
9. }
10. }
11. }
Siddhant College Of Engineering

12. Java if-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.

Syntax:

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

1. //A Java Program to demonstrate the use of if-else statement.


2. //It is a program of odd and even number.
3. public class IfElseExample {
4. public static void main(String[] args) {
5. //defining a variable
6. int number=13;
7. //Check if the number is divisible by 2 or not
8. if(number%2==0){
9. System.out.println("even number");
10. }else{
11. System.out.println("odd number");
12. }
13. }
14. }

Leap Year Example:

A year is leap, if it is divisible by 4 and 400. But, not by 100.

1. public class LeapYearExample {


2. public static void main(String[] args) {
3. int year=2020;
4. if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
5. System.out.println("LEAP YEAR");
Siddhant College Of Engineering

6. }
7. else{
8. System.out.println("COMMON YEAR");
9. }
10. }
11. }

Practice Example :
public class time{
public static void main(String args[]){
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}

nested-if
Nested if statements mean an if statement inside an if statement. Yes, java allows us to nest
if statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
Siddhant College Of Engineering

}
// Java program to illustrate nested-if statement
import java.util.*;
class NestedIfDemo {
public static void main(String args[])
{
int i = 10;

if (i == 10 || i<15) {
// First if statement
if (i< 15)
System.out.println("i is smaller than 15");
Siddhant College Of Engineering

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i< 12)
System.out.println(
"i is smaller than 12 too");
} else{
System.out.println("i is greater than 15");
}
}
}

1. public class JavaNestedIfExample2 {


2. public static void main(String[] args) {
3. //Creating two variables for age and weight
4. int age=25;
5. int weight=48;
6. //applying condition on age and weight
7. if(age>=18){
8. if(weight>50){
9. System.out.println("You are eligible to donate blood");
10. } else{
11. System.out.println("You are not eligible to donate blood");
12. }
13. } else{
14. System.out.println("Age must be greater than 18");
15. }
16. } }
Siddhant College Of Engineering

Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

1. //Java Program to demonstrate the use of If else-if ladder.


2. //It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
3. public class IfElseIfExample {
Siddhant College Of Engineering

4. public static void main(String[] args) {


5. int marks=65;
6.
7. if(marks<50){
8. System.out.println("fail");
9. }
10. else if(marks>=50 && marks<60){
11. System.out.println("D grade");
12. }
13. else if(marks>=60 && marks<70){
14. System.out.println("C grade");
15. }
16. else if(marks>=70 && marks<80){
17. System.out.println("B grade");
18. }
19. else if(marks>=80 && marks<90){
20. System.out.println("A grade");
21. }else if(marks>=90 && marks<100){
22. System.out.println("A+ grade");
23. }else{
24. System.out.println("Invalid!");
25. }
26. }
27. }

1. public class PositiveNegativeExample {


2. public static void main(String[] args) {
3. int number=-13;
4. if(number>0){
5. System.out.println("POSITIVE");
6. }else if(number<0){
7. System.out.println("NEGATIVE");
8. }else{
9. System.out.println("ZERO");
10. }
11. }
12. }
Siddhant College Of Engineering

Java Switch Statements

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later in this
chapter

Syntax

switch(expression){

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

public class switchexample {


public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
Siddhant College Of Engineering

break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}
Siddhant College Of Engineering

Nested-Switch Statement:
Nested-Switch statements refers to Switch statements inside of another Switch Statements.

// Java Program to demonstrate the use of Java Nested Switch


public class NestedSwitchExample {
public static void main(String args[]) {
int year = 3, semester = 2;
switch (year) {
case 1:
switch (semester) {
case 1:
System.out.println("Total semesters passed: 1");
break;
Siddhant College Of Engineering

case 2:
System.out.println("Total semesters passed: 2");
break;
}
break;
case 2:
switch (semester) {
case 1:
System.out.println("Total semesters passed: 3");
break;
case 2:
System.out.println("Total semesters passed: 4");
break;
}
break;
case 3:
switch (semester) {
case 1:
System.out.println("Total semesters passed: 5");
break;
case 2:
System.out.println("Total semesters passed: 6");
break;
}
break;
case 4:
switch (semester) {
case 1:
System.out.println("Total semesters passed: 7");
break;
Siddhant College Of Engineering

case 2:
System.out.println("Total semesters passed: 8");
break;
}
break;
}
}
}

Java While Loop

The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.

The while loop is considered as a repeating if statement. If the number of iteration is not
fixed, it is recommended to use the while loop.

Syntax:

1. while (condition){
2. //code to be executed
3. Increment / decrement statement
4. }

Flowchart For while loop (Control Flow):


Siddhant College Of Engineering

1. public class WhileExample {


2. public static void main(String[] args) {
3. int i=1;
4. while(i<=10){
5. System.out.println(i);
6. i++;
7. }
8. }
9. }

Java For loop


Java for loop is used to run a block of code for a certain number of times. The syntax
of for loop is:

for (initialExpression; testExpression; updateExpression) {


// body of the loop
}

1. The initialExpression initializes and/or declares variables and executes only once.
2. The condition is evaluated. If the condition is true, the body of the for loop is executed.
3. The updateExpression updates the value of initialExpression.
4. The condition is evaluated again. The process continues until the condition is false.
Siddhant College Of Engineering

Classforloop {
publicstaticvoidmain(String[] args)
{
for(inti = 1; i<= 10; i++) {
System.out.println(i);
}
}
}

For-each loop in Java

For-each is another array traversing technique like for loop.


 It starts with the keyword for like a normal for-loop.
 Instead of declaring and initializing a loop counter variable, you declare a variable that
is the same type as the base type of the array, followed by a colon, which is then
followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an indexed
array element.

 It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

Syntax:
for (type var : array)
{
statements using var;
}

/*package whatever //do not write package name here */


import java.io.*;
class Easy

{
public static void main(String[] args)

{
// array declaration
int ar[] = { 10, 50, 60, 80, 90 };
for (int element :ar)
Siddhant College Of Engineering

System.out.print(element + " ");


}
}

Java Break Statement

The Java break statement is used to break loop or switch statement. It breaks the current flow
of the program at specified condition. In case of inner loop, it breaks only inner loop.

We can use Java break statement in all types of loops such as for loop, while loop and do-
while loop.

Syntax:

1. jump-statement;
2. break;

1. //inside the for loop.


2. public class BreakExample {
3. public static void main(String[] args) {
4. //using for loop
5. for(int i=1;i<=10;i++){
6. if(i==5){
7. //breaking the loop
8. break;
9. } System.out.println(i);
}
Siddhant College Of Engineering

}
}

Continue:
The continue statement in Java is used to skip the current iteration of a loop. We can use
continue statement inside any types of loops such as for, while, and do-while loop.
Basically continue statements are used in the situations when we want to continue the loop
but do not want the remaining statement after the continue statement.
Syntax:

continue;

// Java program to demonstrates the continue


// statement to continue a loop
class GFG {
public static void main(String args[])
{
for (int i = 0; i< 10; i++) {
// If the number is 2
// skip and continue
if (i == 2)
continue;

System.out.print(i + " ");


}
Siddhant College Of Engineering

}
}

Difference between break and continue:


Break Continue

The break statement is used to terminate the The continue statement is used to skip the
loop immediately. current iteration of the loop.

break keyword is used to indicate break continue keyword is used to indicate continue
statements in java programming. statement in java programming.

We can use a break with the switch We can not use a continue with the switch
statement. statement.

The break statement terminates the whole The continue statement brings the next
loop early. iteration early.

It stops the execution of the loop. It does not stop the execution of the loop.

Java return keyword


In Java, the return keyword returns a value from a method.
The method will return the value immediately when the keyword is encountered.
This means that the method will not execute any more statements beyond
the return keyword, and any local variables created in the method will be discarded.
Developers can use the return keyword with or without a value. If a value is specified, it will
be returned to the caller. Otherwise, a null value will be returned.

labeled loop

A label is a valid variable name that denotes the name of the loop to where the control of
execution should jump. To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop.

In layman terms, we can say that label is nothing but to provide a name to a loop. It is a good
habit to label a loop when using a nested loop. We can also use labels
with continue and break statements.
Siddhant College Of Engineering

Java Labeled for Loop

Labeling a for loop is useful when we want to break or continue a specific for loop according
to requirement. If we put a break statement inside an inner for loop, the compiler will jump
out from the inner loop and continue with the outer loop again.

What if we need to jump out from the outer loop using the break statement given inside the
inner loop? The answer is, we should define the label along with the colon(:) sign before the
loop.

Syntax:

1. labelname:
2. for(initialization; condition; incr/decr)
3. {
4. //functionality of the loop
5. }

1. public class LabeledForLoop


2. {
3. public static void main(String args[])
4. {
5. int i, j;
6. //outer loop
7. outer: //label
8. for(i=1;i<=5;i++)
9. {
10. System.out.println();
11. //inner loop
12. inner: //label
13. for(j=1;j<=10;j++)
14. {
15. System.out.print(j + " ");
16. if(j==9)
17. break inner;
Siddhant College Of Engineering

18. }
19. }
20. }
21. }

Java Labeled while Loop

Syntax:

1. labelName:
2. while ( ... )
3. {
4. //statements to execute
5. }

Java Nested Loops

Nested loop means a loop statement inside another loop statement. That is why nested
loops are also called as “loop inside loop“.

Syntax for Nested For loop:

for ( initialization; condition; increment ) {

for ( initialization; condition; increment ) {


// statement of inside loop
}
// statement of outer loop
}
}}
Siddhant College Of Engineering

Syntax for Nested While loop:

while(condition) {

while(condition) {

// statement of inside loop


}

// statement of outer loop


}

2.1 Java Constructors

What is a Constructor?

A constructor in Java is similar to a method that is invoked when an object of the class is
created.

Unlike Java methods, a constructor has the same name as that of the class and does not have
any return type. For example,

class Test {

Test() {

// constructor body

classconstructor {
private String name;

// constructor
constructor() {
Siddhant College Of Engineering

System.out.println("Constructor Called:");
name = "Hello";
}

publicstaticvoidmain(String[] args) {

constructorobj = newconstructor();
System.out.println("The name is " + obj.name);
}
}

Types of Constructor

In Java, constructors can be divided into 3 types:

1. Parameterized Constructor

2. Default Constructor

1. Java Parameterized Constructor

A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructor with parameters).

classMain {

String languages;

// constructor accepting single value


Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

publicstaticvoidmain(String[] args) {

// call constructor by passing a single value


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Siddhant College Of Engineering

Main obj3 = new Main("C");


}
}

publicclassMain{

int x;

publicMain(int y){

x = y;

publicstaticvoidmain(String[]args){

MainmyObj=newMain(5);

System.out.println(myObj.x);

publicclassMain{

intmodelYear;

StringmodelName;

publicMain(int year,String name){

modelYear= year;

modelName= name;

}
Siddhant College Of Engineering

publicstaticvoidmain(String[]args){

MainmyCar=newMain(1969,"Mustang");

System.out.println(myCar.modelYear+" "+myCar.modelName);

1. class Student4{
2. int id;
3. String name;
4. //creating a parameterized constructor
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. //method to display the values
10. void display(){System.out.println(id+" "+name);}
11.
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }

1. Java Default Constructor

If we do not create any constructor, the Java compiler automatically create a no-arg
constructor during the execution of the program. This constructor is called default
constructor.
Siddhant College Of Engineering

classMain {

int a;
boolean b;

publicstaticvoidmain(String[] args) {

// A default constructor is called


Main obj = newMain();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}

// Create a Main class

publicclassMain{

intx;// Create a class attribute

// Create a class constructor for the Main class

publicMain(){

x =5;// Set the initial value for the class attribute x

publicstaticvoidmain(String[]args){

MainmyObj=newMain();// Create an object of class Main (This will call the constructor)

System.out.println(myObj.x);// Print the value of x

1. /Let us see another example of default constructor


2. //which displays the default values
3. class Student3{
Siddhant College Of Engineering

4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. s1.display();
15. s2.display();
16. }
17. }
Siddhant College Of Engineering

Nesting of Methods

When a method in java calls another method in the same class, it is called Nesting of
methods.
Syntax:
class Main
{
method1(){

// statements
}

method2()
{
// statements

// calling method1() from method2()


method1();
}
method3()
{
// statements

// calling of method2() from method3()


method2();
}
}
Siddhant College Of Engineering

Enter length, breadth and height as input. After that we first call the volume method. From
volume method we call area method and from area method we call perimeter method. Hence
we get perimeter, area and volume of cuboid as output.

1. importjava.util.Scanner;
2. publicclassNesting_Methods
3. {
4. intperimeter(int l, int b)
5. {
6. intpr=12*(l + b);
7. returnpr;
8. }
9. intarea(int l, int b)
10. {
11. intpr=perimeter(l, b);
12. System.out.println("Perimeter:"+pr);
13. intar=6* l * b;
14. returnar;
15. }
16. intvolume(int l, int b, int h)
17. {
18. intar=area(l, b);
19. System.out.println("Area:"+ar);
20. intvol ;
21. vol = l * b * h;
22. return vol;
23. }
24. publicstaticvoidmain(String[]args)
25. {
26. Scanner s =newScanner(System.in);
27. System.out.print("Enter length of cuboid:");
28. int l =s.nextInt();
29. System.out.print("Enter breadth of cuboid:");
30. int b =s.nextInt();
31. System.out.print("Enter height of cuboid:");
32. int h =s.nextInt();
33. Nesting_Methodsobj=newNesting_Methods();
34. int vol =obj.volume(l, b, h);
35. System.out.println("Volume:"+vol);
36. }
37. }
Siddhant College Of Engineering

this Keyword

In Java, this keyword is used to refer to the current object inside a method or a constructor.

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Siddhant College Of Engineering

Chek with this code

19. class Student{


20. int rollno;
21. String name;
22. float fee;
23. Student(int rollno,String name,float fee){
24. this.rollno=rollno;
25. this.name=name;
26. this.fee=fee;
27. }
28. void display()
29. {
30. System.out.println(rollno+" "+name+" "+fee);}
31. }
32.
33. class TestThis2{
34. public static void main(String args[]){
35. Student s1=new Student(111,"ankit",5000f);
36. Student s2=new Student(112,"sumit",6000f);
37. s1.display();
38. s2.display();
39. }}

Command Line Arguments in Java

Java command-line argument is an argument i.e. passed at the time of running the Java
program. In the command line, the arguments passed from the console can be received in
the java program and they can be used as input.
The users can pass the arguments during the execution bypassing the command-line
arguments inside the main() method.
We need to pass the arguments as space-separated values. We can pass both strings and
primitive data types(int, double, float, char, etc) as command-line arguments. These
arguments convert into a string array and are provided to the main() function as a string
array argument.
Siddhant College Of Engineering

1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }

classMain {
publicstaticvoidmain(String[] args) {
System.out.println("Command-Line arguments are");

// loop through all arguments


for(String str: args) {
System.out.println(str);
}
}
}

Garbage Collection in Java


Garbage collection in Java is the process by which Java programs perform automatic
memory management.

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.

we were using free() function in C language and delete() in C++.


But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

How can an object be unreferenced?

There are many ways:

1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
Siddhant College Of Engineering

2) By assigning a reference to another:


1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
1. new Employee();

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

Syntax:

public static void gc(){}

1. public class TestGarbage1{


2. public void finalize()
3. {
4. System.out.println("object is garbage collected");
5. }
6. public static void main(String args[]){
7. TestGarbage1 s1=new TestGarbage1();
8. TestGarbage1 s2=new TestGarbage1();
9. s1=null;
10. s2=null;
11. System.gc();
12. }
13. }

finalize() Method in Java

finalize() method in Java is a method of the Object class that is used to perform cleanup
activity before destroying any object. It is called by Garbage collector before destroying the
objects from memory.
Siddhant College Of Engineering

finalize() method is called by default for every object before its deletion. This method
helps Garbage Collector to close all the resources used by the object and helps JVM in-
memory optimization.

Java Access Modifiers/ Visiblity control

In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces,
variables, methods, constructors, data members, and the setter methods.

classAnimal {
publicvoidmethod1() {...}

privatevoidmethod2() {...}
}

In the above example, we have declared 2 methods: method1() and method2(). Here,

 method1 is public - This means it can be accessed by other classes.


 method2 is private - This means it can not be accessed by other classes.

Default/Friendly Access Specifiers


When no access modifier is specified, the member defaults to a limited version of public
accessibility that is known as “Friendly or Default Access Modifiers”.
A default access modifier in Java has no specific keyword. Whenever the access modifier is
not specified, then it is assumed to be the default. The entities like classes, methods, and
variables can have a default access.

class BaseClass
{
void display() //no access modifier indicates default modifier
{
System.out.println("BaseClass::Display with 'dafault' scope");
}
}
Siddhant College Of Engineering

class Main
{
public static void main(String args[])
{
//access class with default scope
BaseClassobj = new BaseClass();

obj.display(); //access class method with default scope


}
}

Public Access Modifier


A class or a method or a data field specified as ‘public’ is accessible from any class or
package in the Java program. The public entity is accessible within the package as well as
outside the package. In general, public access modifier is a modifier that does not restrict the
entity at all.

classA
{
publicvoiddisplay()
{
System.out.println("SoftwareTestingHelp!!");
}
}
classMain
{
publicstaticvoidmain(String args[])
{
Aobj = newA ();
obj.display();
}
}
Siddhant College Of Engineering

Protected Access Specifier


The protected access specifier allows access to entities through subclasses of the class in
which the entity is declared. It doesn’t matter whether the class is in the same package or
different package, but as long as the class that is trying to access a protected entity is a
subclass of this class, the entity is accessible.

class A
{
protected void display()
{
System.out.println("SoftwareTestingHelp");
}
}

class B extends A {}
class C extends B {}

class Main{
public static void main(String args[])
{
B obj = new B(); //create object of class B
obj.display(); //access class A protected method using obj
C cObj = new C(); //create object of class C
cObj.display (); //access class A protected method using cObj
}
}
Siddhant College Of Engineering

Private Access Modifier


The ‘private’ access modifier is the one that has the lowest accessibility level. The methods
and fields that are declared as private are not accessible outside the class. They are accessible
only within the class which has these private entities as its members.

class TestClass{
//private variable and method
private int num=100;
private void printMessage(){System.out.println("Hello java");}

public class Main{


public static void main(String args[]){
TestClassobj=new TestClass();
System.out.println(obj.num);//try to access private data member - Compile Time
Error
obj.printMessage();//Accessing private method - Compile Time Error
}
}

Object Class in Java

In Java, the Object class is considered the parent class for all the classes.

It simply means that all the classes in Java are derived/subclasses and their base class is
Object class.

All the classes directly or indirectly inherit from the Object class in Java.

Object class is present in java.lang package. Every class in Java is directly or indirectly
derived from the Object class.

The object class is the topmost class which is the base class for all the classes.
Siddhant College Of Engineering

Methods of Object class

1. toString() method

As the name suggests, it returns a string representation of an object. It is used to convert an


Object "to String".

As each class is a sub-class of the Object class in Java. So the toString() method gets
inherited by the other classes from the Object class.

If we try to print the object of any class, then the JVM internally invokes
the toString() method.

2.hashCode()

A hash code is an integer value that gets generated by the hashing algorithm. Hash code is
associated with each object in Java and is a distinct value. It converts an object's internal
address to an integer through an algorithm. It is not the memory address, it is the integer
representation of the memory address.
Siddhant College Of Engineering

3.equals (Object obj)

This method compares two objects and returns whether they are equal or not. It is used to
compare the value of the object on which the method is called and the object value which is
passed as the parameter.

4.getClass()

It is used to return the class object of this object. Also, it fetches the actual runtime class of
the object on which the method is called. This is also a native method. It can be used to get
the metadata of the this class. Metadata of a class includes the class name, fields name,
methods, constructor, etc.

5.clone()
The clone() method is used to create an exact copy of this object.
It creates a new object and copies all the data of the this object to the new object.

6.notify()
The notify() method is used to wake up only one single thread that is waiting on the object,
and that thread starts the execution.

7.notifyAll()

The notifyAll() method is used to wake up all threads that are waiting on this object. This
method gives the notification to all waiting threads of an object.

8.wait()

The wait() method tells the current thread to give up the lock and go to sleep.

9.finalize() method
This method is called just before an object is garbage collected. It is called the Garbage
Collector on an object when the garbage collector determines that there are no more
references to the object. We should override finalize() method to dispose of system
resources, perform clean-up activities and minimize memory leaks.
Siddhant College Of Engineering

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.

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.

How to Create and Initialize Array in Java?

In every program, to use an array, we need to create it before it is used. We require two things
to create an array in Java - data type and length.

As we know, an array is a homogenous container that can only store the same type of data.
Hence, it's required to specify the data type while creating it. Moreover, we also need to put
the number of elements the array will store.

Syntax:
datatype[] arrayName = new datatype[length]; OR
datatype arrayName[] = new datatype[length];

int[] myArray = newint[5];


int myArray1[] = newint[5];

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.
Siddhant College Of Engineering

Disadvantages

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.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java

1. Single Dimensional Array

An array that has only one subscript or one dimension is known as a single-dimensional
array. It is just a list of the same data type variables.

One dimensional array can be of either one row and multiple columns or multiple rows
and one column.

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Siddhant College Of Engineering

public class Demo {


public static void main (String[] args) {
// declaring and initializing an array
String strArray[] = {"Python", "Java", "C++", "C", "PHP"};

// using a for-each loop for printing the array


for(String i : strArray) {
System.out.print(i + " ");
}

// find the length of an array


System.out.println("\nLength of array: "+strArray.length);

}
}

2. Multi-Dimensional Array

In not all cases, we implement a single-dimensional array. Sometimes, we are required to


create an array within an array.

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. }}
Siddhant College Of Engineering

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);

Java String classprovides a lot of methods to perform operations on strings such as


compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

Creating a String
There are two ways to create string in Java:
 String literal
String s = “GeeksforGeeks”;
 Using new keyword
String s = new String (“GeeksforGeeks”);
Siddhant College Of Engineering

Java StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.

StringBuffer is a peer class of String that provides much of the functionality of strings.
The string represents fixed-length, immutable character sequences while StringBuffer
represents growable and writable character sequences. StringBuffer may have characters
and substrings inserted in the middle or appended to the end.

Methods of StringBuffer class

append() Used to add text at the end of the existing text.

length() The length of a StringBuffer can be found by the length( ) method

capacity() the total allocated capacity can be found by the capacity( ) method

This method returns the char value in this sequence at the specified
charAt() index.

delete() Deletes a sequence of characters from the invoking object

deleteCharAt() Deletes the character at the index specified by loc

ensureCapacity() Ensures capacity is at least equals to the given minimum.

insert() Inserts text at the specified index position

length() Returns length of the string

reverse() Reverse the characters within a StringBuffer object

Replace one set of characters with another set inside a StringBuffer


replace() object
Siddhant College Of Engineering
Siddhant College Of Engineering

Java Vector

Vector is like the dynamic array which can grow or shrink its size.

Unlike array, we can store n-number of elements in it as there is no size limit.

It is a part of Java Collection framework since Java 1.2. It is found in the java.util package
and implements the List interface,

so we can use all the methods of List interface here.

It is similar to the ArrayList, but with two differences-

o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.
o Vector implements a dynamic array which means it can grow or shrink as required.
Like an array, it contains components that can be accessed using an integer index.
o They are very similar to ArrayList, but Vector is synchronized and has some legacy
methods that the collection framework does not contain.

o Syntax:
o public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
o Here, E is the type of element.

import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
Siddhant College Of Engineering

//Adding elements using add() method of List


vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}
Siddhant College Of Engineering

Wrapper classes in Java

The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
Siddhant College Of Engineering

Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer,

//Java program to convert primitive into objects


//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}}

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing

//Java program to convert object into primitives


//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}}
Siddhant College Of Engineering

Example of wrapper class

//Java Program to convert all primitives into its corresponding


//wrapper objects and vice-versa
public class WrapperExample3{
public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
Siddhant College Of Engineering

System.out.println("Float object: "+floatobj);


System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);

//Unboxing: Converting Objects to Primitives


byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}
Siddhant College Of Engineering

Java Enums

The Enum in Java is a data type which contains a fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.

According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.

Enums are used to create our own data type like classes.

The enum data type (also known as Enumerated Data Type) is used to define an enum in
Java.
Siddhant College Of Engineering

Defining Java Enum

The enum can be defined within or outside the class because it is similar to a class.

enum Season { WINTER, SPRING, SUMMER, FALL }

Example :

class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}

Example 2:

class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());

}}
Siddhant College Of Engineering

What is the purpose of the values() method in the enum?

The Java compiler internally adds the values() method when it creates an enum. The values()
method returns an array containing all the values of the enum.

What is the purpose of the valueOf() method in the enum?

The Java compiler internally adds the valueOf() method when it creates an enum. The
valueOf() method returns the value of given constant enum.

What is the purpose of the ordinal() method in the enum?

The Java compiler internally adds the ordinal() method when it creates an enum. The
ordinal() method returns the index of the enum value.

Java HashMap

HashMap in Java is a part of the collections framework, which is found in java.util package.
It provides the basic implementation of Map interface of Java. It stores the data in a key-
value mapping in which every key is mapped to exactly one value of any data type.

Keys should be unique as the key is used to retrieve the corresponding value from the map.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for Key and V for Value.

HashMap is unsynchronised, therefore it's faster and uses less memory than HashTable.

Being unsynchronized means HashMap doesn’t guarantee any specific order of the elements.

Syntax:
Siddhant College Of Engineering

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,


Cloneable, Serializable

Parameters:

The HashMap in Java takes two parameters which are as follows:

1. K: It is the data type of keys maintained by the map. Keys should be unique.
2. V: It is the data type of values maintained. Values need not be unique. It can be
duplicate.

Basic Operations on Java HashMap

 Add elements

 Access elements

 Change elements

 Remove elements

Example

import java.util.HashMap;

class Main {

public static void main(String[] args) {

// create a hashmap
Siddhant College Of Engineering

HashMap<String, Integer> languages = new HashMap<>();

// add elements to hashmap

languages.put("Java", 8);

languages.put("JavaScript", 1);

languages.put("Python", 3);

System.out.println("HashMap: " + languages);

Example

// Import the HashMap class

importjava.util.HashMap;

publicclassMain{
Siddhant College Of Engineering

publicstaticvoidmain(String[]args){

// Create a HashMap object called capitalCities

HashMap<String,String>capitalCities=newHashMap<String,String>();

// Add keys and values (Country, City)

capitalCities.put("England","London");

capitalCities.put("Germany","Berlin");

capitalCities.put("Norway","Oslo");

capitalCities.put("USA","Washington DC");

System.out.println(capitalCities);

Example

Create a HashMap object called people that will store String keys and Integer values:

// Import the HashMap class

importjava.util.HashMap;
Siddhant College Of Engineering

publicclassMain{

publicstaticvoidmain(String[]args){

// Create a HashMap object called people

HashMap<String,Integer> people =newHashMap<String,Integer>();

// Add keys and values (Name, Age)

people.put("John",32);

people.put("Steve",30);

people.put("Angie",33);

for(Stringi:people.keySet()){

System.out.println("key: "+i+" value: "+people.get(i));

}
Siddhant College Of Engineering

Inheritance in Java

Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the


mechanism in Java by which one class is allowed to inherit the features(fields and methods)
of another class. In Java, Inheritance means creating new classes based on existing ones. A
class that inherits from another class can reuse the methods and fields of that class. In
addition, you can add new fields and methods to your current class as well.

Why Do We Need Java Inheritance?

 Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.

 Method Overriding: Method Overriding is achievable only through Inheritance. It is


one of the ways by which Java achieves Run Time Polymorphism.

 Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.

Important Terminologies Used in Java Inheritance

 Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template or
blueprint or prototype from which objects are created.

 Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
Siddhant College Of Engineering

 Sub Class/Child Class: The class that inherits the other class is known as a
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.

How to Use Inheritance in Java?

The extends keyword is used for inheritance in Java. Using the extends keyword indicates
you are derived from an existing class. In other words, “extends” refers to increased
functionality.

Syntax :

class derived-class extends base-class


{
//methods and fields
}

Inheritance in Java Example

Example: In the below example of inheritance, class Bicycle is a base class, class
MountainBike is a derived class that extends the Bicycle class and class Test is a driver class
to run the program.

// Java program to illustrate the

// concept of inheritance

// base class

class Bicycle {

// the Bicycle class has two fields

public int gear;

public int speed;

// the Bicycle class has one constructor

public Bicycle(int gear, int speed)

{
Siddhant College Of Engineering

this.gear = gear;

this.speed = speed;

// the Bicycle class has three methods

public void applyBrake(int decrement)

speed -= decrement;

public void speedUp(int increment)

speed += increment;

// toString() method to print info of Bicycle

public String toString()

return ("No of gears are " + gear + "\n"

+ "speed of bicycle is " + speed);

// derived class

class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field

public int seatHeight;

// the MountainBike subclass has one constructor

public MountainBike(int gear, int speed,


Siddhant College Of Engineering

int startHeight)

// invoking base-class(Bicycle) constructor

super(gear, speed);

seatHeight = startHeight;

// the MountainBike subclass adds one more method

public void setHeight(int newValue)

seatHeight = newValue;

// overriding toString() method

// of Bicycle to print more info

@Override public String toString()

return (super.toString() + "\nseat height is "

+ seatHeight);

// driver class

public class Test {

public static void main(String args[])

{
Siddhant College Of Engineering

MountainBike mb = new MountainBike(3, 100, 25);

System.out.println(mb.toString());

Output
No of gears are 3
speed of bicycle is 100
seat height is 25

You might also like