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

Unit 1-Java Final

Uploaded by

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

Unit 1-Java Final

Uploaded by

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

UNIT-1

INTRODUCTION TO JAVA PROGRAMMING


The History and Evolution of Java – Byte code – Java buzzwords – Data
types – Variables – Arrays – operators – Control statements – Type
conversion and casting. Concepts of classes and objects: Basic Concepts
of OOPs – constructors – static keyword – Final with data – Access
control – This key word – Garbage collection – Nested classes and inner
classes–String class

HISTORY OF JAVA
 Java started out as a research project.
 Research began in 1991 as the Green Project at Sun Microsystems, Inc.
 Research efforts birthed a new language, OAK. ( A tree outside of the
window of James Gosling’s office at Sun).
 It was developed as an embedded programming language, which would
enable embedded system application.
 It was not really created as web programming language.
 Java is available as jdk and it is an open source s/w.

Language was created with 5 main goals:


 It should be object oriented.
 A single representation of a program could be executed on multiple
operating systems. (i.e. write once, run anywhere)
 It should fully support network programming.

 It should execute code from remote sources securely.

 It should be easy to use.


 Oak was renamed Java in 1994.
 Now Sun Microsystems is a subsidiary (Controlled by) of Oracle
Corporation.

James Gosling Green Team

Java Logo

Java Platforms
There are three main platforms for Java:

 Java SE (Java Platform, Standard Edition) – runs on desktops and laptops.


 Java ME (Java Platform, Micro Edition) – runs on mobile devices such as
cell phones.
 Java EE (Java Platform, Enterprise Edition) – runs on servers.
Evolution(Versions) of Java
Version Codename Year Features Added
JDK 1.0 Oak Jan23,1996 This is the first stable version.
Rebirth of Inner classes JavaBeans, JDBC, RMI, Reflection,
JDK 1.1 Feb19,1997 AWT.
Java
JIT compiler, Collections, IDL & CORBA,
J2SE 1.2 Playground Dec8, 1998 strictfp, Java Plug-in.

HotSpot JVM, JavaSound, Java Naming and


J2SE 1.3 Kestrel May8, 2000 Directory Interface, Java Platform Debugger Archi

Preferences API, Logging API, assert, image


J2SE 1.4 Merlin Feb6, 2002
I/O API, security and cryptography extensions.
Generics, annotations, Autoboxing, Enumerations,
J2SE 5.0 Tiger Sep30, 2004 Varargs, Enhanced for each.

JDBC 4.0, JVM improvements, Improved JAXB,


JAVA SE Mustang Dec11, 2006 Improved web services, Support for older
6
Win9x versions dropped.
JAVA SE Major updates to Java
7 Dolphin July28, 2011

JAVA SE - March 2014 -


8

Java Terminology
Java Development Kit:
It contains one (or more) JRE's along with the various development tools like
the Java source compilers, bundling and deployment tools, debuggers,
development libraries, etc.
Java Virtual Machine:
An abstract machine architecture specified by the Java Virtual Machine
Specification.
It interprets the byte code into the machine code depending upon the
underlying OS and hardware combination.
JVM is platform dependent. (It uses the class libraries, and other supporting
files provided in JRE)
Java Runtime Environment:
A runtime environment which implements Java Virtual Machine, and provides all
class libraries and other facilities necessary to execute Java programs. This is the
software on your computer that actually runs Java programs.

JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc)
+runtime libraries.
Binary form of a .class file(partial)
public class Hello

public static void main(String[] args)

System.out.println("Hello, World!");

}
BYTE CODE
Byte Code can be defined as an intermediate code generated by the compiler
after the compilation of source code (JAVA Program). This intermediate
code makes Java a platform-independent language.

How is Byte Code generated?


 Compiler converts the source code or the Java program into the Byte
Code(or machine code), and secondly, the Interpreter executes the byte
code on the system.
 The Interpreter can also be called JVM(Java Virtual Machine). The byte
code is the common piece between the compiler(which creates it) and
the Interpreter (which runs it).
Let us look at this phenomenon, step by step
Suppose you are writing your first JAVA program.

import java.io.*;
public classGFG {
public staticvoid main(String args[])
{
System.out.println("GFG!");
}
}

Output
GFG!
 The above-written code is called JAVA source code.
 The compiler compiles the source code.
 Finally, Interpreter executes the compiled source code.

 Whenever we write any program, it is not written in machine code.


 We write it in a high-level language like JAVA, C++, Python, etc. But
the computer understands only the machine code.
 So when we execute our program, it is first converted into machine code
or Byte code by the compiler and then executed by the Interpreter.
This intermediate code or the byte can run on any platform making,
JAVA a platform-independent language.
JAVA BUZZWORDS
Java is the most popular object-oriented programming language. Java has many
advanced features, a list of key features is known as Java Buzz Words.
The java team has listed the following terms as java buzz words.

 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded
 Interpreted
 High performance
 Distributed
 Dynamic

Simple
Java programming language is very simple and easy to learn, understand, and
code. Most of the syntaxes in java followbasic programming language C and
object-oriented programming concepts are similar to C++. In a java programming
language, many complicated features like pointers, operator overloading,
structures, unions, etc. have been removed. One of the most useful features is the
garbage collector it makes java more simple.

Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a
web application. The applet in java does not allow access to other parts of the
computer, which keeps away from harmful programs like viruses and
unauthorized access.

Portable
Portability is one of the core features of java which enables the java programs to
run on any computer or operating system. For example, an applet developed
using java runs on a wide variety of CPUs, operating systems, and browsers
connected to the Internet.

Object-oriented
Java is said to be a pure object-oriented programming language. In java,
everything is an object. It supports all the features of the object-oriented
programming paradigm. The primitive data types java also implemented as
objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.

Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage
collector), java is a strictly typed language, it has a strong set of exception
handling mechanism, and many more.

Architecture-neutral (or) Platform Independent


Java has invented to archive "write once; run anywhere, any time, forever". The
java provides JVM (Java Virtual Machine) to archive architectural-neutral or
platform-independent. The JVM allows the java program created using one
operating system can be executed on any other operating system.

Multi-threaded
Java supports multi-threading programming, which allows us to write
programs that do multiple operations simultaneously.

Interpreted
Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. The byte code is interpreted to
any machine code so that it runs on the native machine.

High performance
Java provides high performance with the help of features like JVM,
interpretation, and its simplicity.

Distributed
Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote
Method Invocation (RMI), this feature enables a program to invoke methods
across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and
deallocation (objects and garbage collector).

DATA TYPES
Data types specify the different sizes and values that can be stored in the
variable.

Data types are divided into two groups:

 Primitive data types - includes byte, short, int, long, float, double, boolean
and char
 Non-primitive data types - such as String, Arrays and Classes

Primitive Data Types


A primitive data type specifies the size and type of variable values, and it has no
additional methods.
There are eight primitive data types in Java:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal


digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values


Java Numbers
Numbers
Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you should
use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or
more decimals. There are two types: float and double.

Even though there are many numeric types in Java, the most used for
numbers are int (for whole numbers) and double (for floating point numbers).

Integer Types
Byte

The byte data type can store whole numbers from -128 to 127. This can be used
instead of int or other integer types to save memory when you are certain that the
value will be within -128 and 127:

Example
public class Main {

public static void main(String[] args) {

byte myNum = 100;

System.out.println(myNum);

Short

The short data type can store whole numbers from -32768 to 32767:

Example
public class Main {

public static void main(String[] args) {

short myNum = 5000;

System.out.println(myNum);
}

Int
The int data type can store whole numbers from -2147483648 to 2147483647. In
general, the int data type is the preferred data type when we create variables with a
numeric value.

Example
public class Main {

public static void main(String[] args) {

int myNum = 100000;

System.out.println(myNum);

Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":

Example
public class Main {

public static void main(String[] args) {

long myNum = 15000000000L;

System.out.println(myNum);

}}
Floating Point Types
You should use a floating point type whenever you need a number with a decimal,
such as 9.99 or 3.14515.

The float and double data types can store fractional numbers. Note that you should
end the value with an "f" for floats and "d" for doubles:

Float Example
public class Main {

public static void main(String[] args) {

float myNum = 5.75f;

System.out.println(myNum);

}}

Double Example
public class Main {

public static void main(String[] args) {

double myNum = 19.99d;

System.out.println(myNum);

}}

Use float or double?


The precision of a floating point value indicates how many digits the value can
have after the decimal point. The precision of float is only six or seven decimal
digits, while double variables have a precision of about 15 digits. Therefore it
is safer to use double for most calculations.
Java Boolean Data Types
Boolean Types
A boolean data type is declared with the boolean keyword and can only take the
values true or false:

Example
public class Main {

public static void main(String[] args) {

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun);

System.out.println(isFishTasty);

Boolean values are mostly used for conditional testing

Java Characters
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

Example
public class Main {
public static void main(String[] args) {
char myGrade = 'B';
System.out.println(myGrade);}}
// Java Program to Demonstrate Char Primitive Data Type
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating and initializing custom character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i = 89;
// use byte and short
// if memory is a constraint
byte b = 4;
// this will give error as number is
// larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is
// larger than short range
// short s1 = 87878787878;
// by default fraction value
// is double in java
double d = 4.355453532;
// for float use 'f' as suffix as standard
float f = 4.7333434f;
//need to hold big range of numbers then we need this data type
long l = 12121L;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
}
}
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Java Non-Primitive Data Types
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.


The main difference between primitive and non-primitive data types are:

 Primitive types are predefined (already defined) in Java. Non-primitive


types are created by the programmer and is not defined by Java (except
for String).
 Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
 The size of a primitive type depends on the data type, while non-primitive
types have all the same size.

Java Strings
Strings are used for storing text.

A String variable contains a collection of characters surrounded by double


quotes:

Example
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}

Java Arrays
Arrays are used to storemultiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;
We have now declared a variable that holds an array of strings. To insert values to
it, we can use an array literal - place the values in a comma-separated list, inside
curly braces:
String[] cars = {"Volvo", "BMW","Ford", "Mazda"};

Example
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
Note: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.

Java Classes and Objects


Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.

Create a Class
To create a class, use the keyword class:

Main.java
Create a class named "Main" with a variable x:

public class Main{

int x =5;

}
Remember from the Java Syntax chapter that a class should always start with an
uppercase first letter, and that the name of the java file should match the class
name.

Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object name,
and use the keyword new:

Example
Create an object called "myObj" and print the value of x:

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}

Java Interface
Interfaces
Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related


methodswith empty bodies:

Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

Primitive Data Type

Non-Primitive Data Type or Reference Data Types

VARIABLES
Variable in Java is a data container that saves the data values during Java
program execution. Every variable is assigned a data type that designates the
type and quantity of value it can hold.
A variable is a name given to a memory location. It is the basic unit of storage in
a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations
done on the variable affect that memory location.
 In Java, all variables must be declared before use.

How to declare variables?

datatype name;
Eg:int count;
1. datatype: Type of data that can be stored in this variable.
2. data_name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be assigned
values in two ways:
 Variable Initialization
 Assigning value by taking input
How to initialize variables?
It can be perceived with the help of 3 components that are as follows:
 datatype: Type of data that can be stored in this variable.
 variable_name: Name given to the variable.

 value: It is the initial value stored in the variable.


Illustrations:
float simpleInterest;
// Declaring float variable
int time = 10, speed = 20;
// Declaring and Initializing integer variable
char var = 'h';
// Declaring and Initializing character variable
Types of Variables in Java
Now let us discuss different types of variables which are listed as follows:
1. Local Variables
2. Instance Variables
3. Static Variables

Let us discuss the traits of every variable been up here in detail.

1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
 These variables are created when the block is entered, or the function is
called and destroyed after exiting from the block or when the call returns
from the function.
 The scope of these variables exists only within the block in which the
variable is declared. i.e., we can access these variables only within that
block.
 Initialization of the local variable is mandatory before using it in the
defined scope.
/*package whatever //do not write package name here */
// Contributed by Shubham Jain
import java.io.*;
class GFG {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Output
Local Variable: 10

2. Instance Variables
Instance variables are non-static variables and are declared in a class outside
any method, constructor, or block.
 As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is
destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will
be used.
 Initialization of instance variable is not mandatory. Its default value is 0.
 Instance Variable can be accessed only by creating objects.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public String geek; // Declared Instance Variable
public GFG()
{ // Default Constructor
this.geek = "Shubham Jain"; // initializing Instance Variable
}
//Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
}
}
Output
Geek name is: Shubham Jain
3. Static Variables
Static variables are also known as Class variables.
 These variables are declared similarly as instance variables. The difference
is that static variables are declared using the static keyword within a class
outside any method constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per
class irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initialization of static variable is not mandatory. Its default value is 0.
 If we access the static variable like the instance variable (through an object),
the compiler will show the warning message, which won’t halt the
program. The compiler will replace the object name with the class name
automatically.
 If we access the static variable without the class name, the compiler will
automatically append the class name.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static String geek = "Shubham Jain"; //Declared static variable
public static void main (String[] args) {
//geek variable can be accessed withod object creation
//Displaying O/P
//GFG.geek --> using the static variable
System.out.println("Geek Name is : "+GFG.geek);
}
}
Output
Geek Name is : Shubham Jain
ARRAYS
An array is a collection of similar types of data.

For example, if we want to store the names of100 people then we can create an
array of the string type that can store100 names.

String[] array = new String[100];


Here, the above array cannot store more than 100 names. The number of values in
a Java array is always fixed.

How to declare an array in Java?


In Java, here is how we can declare an array.

dataType[] arrayName;
 dataType - it can be primitive data types like int, char, double, byte, etc.
 arrayName - it is an identifier
For example,
double[] data;
Here, data is an array that can hold values of type double.

But, how many elements can array this hold?


To define the number of elements that an array can hold, we have to allocate
memory for the array in Java. For example,

// declare an array
double[] data;

// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the size or length of
the array is 10.
In Java, we can declare and allocate the memory of an array in one single
statement. For example,

double[] data = new double[10];


How to Initialize Arrays in Java?
In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};
Here, we have created an array named age and initialized it with the values
inside the curly brackets.

Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements in
the array (i.e. 5).

In the Java array, each memory location is associated with a number. The number
is known as an array index. We can also initialize arrays in Java, using the index
number. For example,

// declare an array
int[] age = new int[5];

// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..

Java Arrays initialization


Note:
 Array index always start from 0. That is, the first element of an array is at index
0.

 If the size of an array is n, then the last element of the array will be at index
n-1.
How to Access Elements of an Array in Java?
We can access the element of an array using the index number. Here is the syntax
for accessing elements of an array,

// access array elements


array[index]

Let's see an example of accessing array elements using index numbers.

Example: Access Array Elements


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

// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}

Output
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5

In the above example, notice that we are using the index number to access each
element of the array.

We can use loops to access all the elements of the array at once.

Looping Through Array Elements


In Java, we can also loop through each element of the array. For example,

Example: Using For Loop


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

// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}

Output
Using for Loop:
12
4
5
In the above example, we are using the for Loop in Java to iterate through each
element of the array. Notice the expression inside the loop,
age.length
Here, we are using the length property of the array to get the size of the array.

Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays. However,
we can declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a


multidimensional array is an array itself. For example,

double[][] matrix = {{1.2, 4.3, 4.0},


{4.1, -1.1}
};

Here, we have created a multidimensional array named matrix. It is a 2-


dimensional array.

Java Multidimensional Arrays


we will learn about the Java multidimensional array using 2-dimensional arrays
and 3-dimensional arrays with the help of examples.

Before we learn about the multidimensional array, make sure you know about Java
array.
A multidimensional array is an array of arrays. Each element of a
multidimensional array is an array itself. For example,

int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-dimensional


array, that can hold a maximum of 12 elements,

2-dimensional Array
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java
starts with 0 and not 1.

Let's take another example of the multidimensional array. This time we will be
creating a 3-dimensional array. For example,

String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of


type String.

Example: 2-dimensional Array


class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
// calculate the length of each row
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);
}
}

Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1

Example: 3-dimensional Array


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

// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
// for..each loop to iterate through elements of 3d array
for (int[][] array2D: test) {
for (int[] array1D: array2D) {
for(int item: array1D) {
System.out.println(item);
}
}
}
}
}
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3

OPERATORS
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
System.out.println(x);
}
}
Output:
150
Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:
Example
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}
Output:
150
400
800

Java divides the operators into the following groups :


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Addition
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x + y);
}
}
Output:
8
Subtraction
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x - y);
}
}
Output:
2
Multiplication
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x * y);
}
}
Output:
15
Division
public class Main {
public static void main(String[] args) {
int x = 12;
int y = 3;
System.out.println(x / y);
}
}
Output:
4
Modulus
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x % y);
}
}
Output:
1
Increment
public class Main {
public static void main(String[] args) {
int x = 5;
++x;
System.out.println(x);
}
}
Output:
6
Decrement
public class Main {
public static void main(String[] args) {
int x = 5;
--x;
System.out.println(x);
}
}
Output:
4
Assignment Operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to
a variable called x:

Example
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println(x);
}
}
Output:
10
The addition assignment operator (+=) adds a value to a variable:
Example
public class Main {
public static void main(String[] args) {
int x = 10;
x += 5;
System.out.println(x);
}
}
Output:
15
A list of all assignment operators:
Comparison Operators
Comparison operators are used to compare two values:

Logical Operators
Logical operators are used to determine the logic between variables or values:

Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a =
60;
and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:

JAVA CONTROL STATEMENTS


Java compiler executes the code from top to bottom. The statements in the code
are executed according to the order in which they appear.
However, Java provides statements that can be used to control the flow of Java
code. Such statements are called control flow statements. It is one of the
fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.


1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o while loop
o do while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is


true
 Use else to specify a block of code to be executed, if the same condition is
false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

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
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.
In the example below, we test two values to find out if 20 is greater than 18. If the
condition is true, print some text:
public class Main {
public static void main(String[] args) {
if (20 > 18) {
System.out.println("20 is greater than 18"); // obviously
}
}
}
OUTPUT:
20 is greater than 18

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is false.

Syntax
if (condition) {

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

} else {

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

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

In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false}
Example
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
OUTPUT:
Good evening.
Example explained
In the example above, time (22) is greater than 10, so the first condition is false.
The next condition, in the else if statement, is also false, so we move on to
the else condition since condition1 and condition2 is both false - and print to the
screen "Good evening".

However, if the time was 14, our program would print "Good day."

Java Switch Statements


Use the switch statement to select one of many code blocks to be
executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 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

The example below uses the weekday number to calculate the weekday name:

Example
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
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;
}
}
}
OUTPUT:
Thursday

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need
for more testing.

A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:
Example
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
}
}
OUTPUT:
Looking forward to the Weekend

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handybecause they save time, reduce errors, and they make code more
readable.

Java While Loop


The while loop loops through a block of code as long as a specified condition
is true:

Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as
a variable (i) is less than 5:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
OUTPUT:
0
1
2
3
4
Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:

Example
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
OUTPUT:
0
1
2
3
4
Do not forget to increase the variable used in the condition, otherwise the loop will
never end!

Java For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
OUTPUT:
0
1
2
3
4

Example explained
Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:

Syntax
for (type variableName : arrayName) {
// code block to be executed
}

The following example outputs all elements in the cars array, using a "for-each"
loop:

Example
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}

OUTPUT:

Volvo
BMW
Ford
Mazda
Java Break and Continue in For Loop
Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example stops the loop when i is equal to 4:

Example
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
OUTPUT:
0
1
2
3
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
This example skips the value of 4:

Example
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
}
}
OUTPUT:
0
1
2
3
5
6
7
8
9

Break and Continue in While Loop


You can also use break and continue in while loops:

public class Main {


public static void main(String[] args) {
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
if (i == 4) {
break;
}
}
}
}
OUTPUT:
0
1
2
3
Continue Example
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}
}
}
OUTPUT:
0
1
2
3
5
6
7
8
9

TYPE CASTING AND TYPE CONVERSION


1. Type Casting:
In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing
casting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called
narrowing conversion.

Syntax/Declaration:-
destination_datatype = (target_datatype)variable;

(): is a casting operator.

target_datatype: is a data type in which we want to convert the source data


type.
Type Casting example –
float x;
byte y;
...
...
y=(byte)x; //Line 5
In Line 5: you can see that, we are converting float(source)
datatype into byte(target) data type.

2. Type conversion :
In type conversion, a data type is automatically converted into another data type
by a compiler at the compiler time. In type conversion, the destination data
type cannot be smaller than the source data type, that’s why it is also called
widening conversion. One more important thing is that it can only be applied to
compatible data types like float, double, integer, decimal.

Type Conversion example –


int x=30;
float y;
y=x; // y==30.000000.
Let’s see the difference between Type casting and Type conversion which are
given below:

S.NO TYPE CASTING TYPE CONVERSION

In type casting, a data type is


converted into another data Whereas in type conversion, a
type by a programmer using data type is converted into
1. casting operator. another data type by a compiler.

Type casting can be applied


to compatible data types as Whereas type conversion can
well as incompatible data only be applied to compatible
2. types. datatypes.
S.NO TYPE CASTING TYPE CONVERSION

In type casting, casting


operator is needed in order to Whereas in type conversion,
cast the a data type to another there is no need for a casting
3. data type. operator.

In typing casting, the


destination data type may be
4. smaller than the source data Whereas in type conversion, the
type, when converting the data destination data type can’t be
type to another data type. smaller than source data type.

Type casting takes place


during the program design by Whereas type conversion is
5. programmer. done at the compile time.

Whereas type conversion is also


Type casting is also called called widening conversion
narrowing conversion because because in this, the destination
in this, the destination data data type can not be smaller
type may be smaller than the than the source data type.
6. source data type.

Whereas type conversion is less


Type casting is often used in used in coding and competitive
coding and competitive programming as it might cause
7. programming works. incorrect answer.

Type casting is more efficient Whereas type conversion is less


8. and reliable. efficient and less reliable.
JAVA CLASSES AND OBJECTS
Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.

Create a Class
To create a class, use the keyword class:

Main.java
Create a class named "Main" with a variable x:

public class Main{

int x =5;

Remember from the Java Syntax chapter that a class should always start with an
uppercase first letter, and that the name of the java file should match the class
name.

Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object name,
and use the keyword new:

Example
Create an object called "myObj" and print the value of x:

public class Main {


int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
OUTPUT
5

Multiple Objects
You can create multiple objects of one class:

Example
Create two objects of Main:

public class Main {


int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main();
Main myObj2 = new Main();
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
OUTPUT
5
5
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often
used for better organization of classes (one class has all the attributes and methods,
while the other class holds the main() method (code to be executed)).

Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:

 Main.java
 Second.java

Main.java
public class Main {
int x = 5;
}
Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}

When both files have been compiled:

C:\Users\Your Name>javac Main.java


C:\Users\Your Name>javac Second.java

Run the Second.java file:

C:\Users\Your Name>java Second

And the output will be:

5
OBJECT ORIENTED PROGRAMMING CONCEPTS
 Objects
 Classes
 Data abstraction and Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding

A class is collection of objects of similar type or it is a template.


Ex: fruit mango;

class object

Objects are instances of the type class.

The wrapping up of data and functions into a single unit ( called class) is
known as encapsulation. Data encapsulation is the most striking features
of a class.
Abstraction refers to the act of representing essential features without including
the background details or explanations

Inheritance is the process by which objects of one class acquire the properties of
another class. The concept of inheritance provides the reusability.
Polymorphism: It allows the single method to perform different actions based
on the parameters.
Dynamic Binding: When a method is called within a program, it associated with
the program at run time rather than at compile time is called dynamic binding.

Object-Oriented Languages Types


1. Object-based programming language: It supports
 Data encapsulation
 Data hiding and access mechanisms
 Automatic initialization and clear-up of objects
 Operator overloading
Disadvantage : They do not support inheritance and dynamic binding

2. Object-oriented programming languages:


OOP = Object-based + inheritance + dynamic binding
Ex: C++, Java, Smalltalk, Object Pascal

Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the use
of existing classes.
 The principle of data hiding helps the programmer to build secure
programs.
 It is easy to partition the work in a project based on objects.
 Object oriented system easily upgraded from small to large systems.
 Software complexity can be easily managed.

Applications of OOP
 Real-time systems
 Object-oriented databases
 Neural networks and parallel programming
 Decision support and office automation systems
 CAD/CAM systems

Constructors
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
}
}
Here, Test() is a constructor. It has the same name as that of the class and
doesn't have a return type.
Example 1:Java Constructor
class Main {
private String name;

// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}
Output
Constructor Called:
The name is Programiz
In the above example, we have created a constructor named Main(). Inside the
constructor, we are initializing the value of the name variable.
Notice the statement of creating an object of the Main class.
Main obj = new Main();
Here, when the object is created, the Main() constructor is called. And, the
value of the name variable is initialized.
Hence, the program prints the value of the name variables as Programiz.
Types of Constructor
In Java, constructors can be divided into 3 types:
1) No-Arg Constructor
2) Parameterized Constructor
3) Default Constructor
1. No-Arg Constructors
Similar to methods, a Java constructor may or maynot have any parameters
(arguments).
If a constructor does not accept any parameters, it is known as a no-argument
constructor. For example,

private Constructor() {
// body of the constructor
}

Example 2: Java private no-arg constructor


class Main {
int i;
// constructor with no parameter
private Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Output
Constructor is called
Value of i: 5
In the above example, we have created a constructor Main(). Here, the
constructor does not accept any parameters. Hence, it is known as a no-arg
constructor.
Notice that we have declared the constructor as private.
Once a constructor is declared private, it cannot be accessed from outside the
class. So, creating objects from outside the class is prohibited using the
private constructor.
Here, we are creating the object inside the same class. Hence, the program is
able to access the constructor.
However, if we want to create objects outside the class, then we need to declare
the constructor as public.
Example 3: Java public no-arg constructors
class Company {
String name;
// public constructor
public Company() {
name = "Programiz";
}}
class Main {
public static void main(String[] args) {
// object is created in another class
Company obj = new Company();
System.out.println("Company name = " + obj.name);
}}
Output
Company name = Programiz
2. Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors
are known as parameterized constructors (constructor with parameters).
Example 4: Parameterized constructor
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output
Java Programming Language
Python Programming Language
C Programming Language

In the above example, we have created a constructor named Main(). Here, the
constructor takes a single parameter. Notice the expression,
Here, we are passing the single value to the constructor. Based on the argument
passed, the language variable is initialized inside the constructor.
3. 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.
Example 5: Default Constructor
class Main {
int a;
boolean b;
public static void main(String[] args) {
// A default constructor is called
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}}
Output
a=0
b = false
Here, we haven't created any constructors. Hence, the Java compiler
automatically creates the default constructor.
The default constructor initializes any uninitialized instance variables with
default values.

Type Default Value

boolean false

byte 0

short 0
int 0

long 0L

char \u0000

float 0.0f

double 0.0d

object Reference null

In the above program, the variables a and b are initialized with default
value 0 and false respectively.
Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the Java
compiler if it is not explicitly defined.

Example 6: Java Constructor Overloading


class Main {
String language;
// constructor with no parameter
Main() {
this.language = "Java";
}
// constructor with a single parameter
Main(String language) {
this.language = language;
}
public void getName() {
System.out.println("Programming Langauage: " + this.language);
}
public static void main(String[] args) {
// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}}
Output
Programming Language: Java
Programming Language: Python
In the above example, we have two constructors: Main() and Main(String
language). Here, both the constructor initialize the value of the variable
language with different values.
Based on the parameter passed during object creation, different constructors are
called and different values are assigned.
It is also possible to call one constructor from another constructor.

Copy Constructor
There is no copy constructor in Java. However, we can copy the values from
one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They
are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using
Java constructor.

//Java program to initialize the values from one object to another


object.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output
111 Karan
111 Karan
JAVA STATIC KEYWORD
In this, we will learn about the Java static keyword along with static methods,
static variables, and static blocks with the help of examples.

What is a static keyword in Java?


In Java, if we want to access class members, we must first create an instance of
the class. But there will be situations where we want to access class members
without creating any variables.
In those situations, we can use the static keyword in Java. If we want to access
class members without creating an instance of the class, we need to declare the
class members static.

Static Variables
In Java, when we create objects of a class, then every object will have its own copy
of all the variables of the class. For example,
class Test {
// regular variable
int age;
}
class Main {
// create instances of Test
Test test1 = new Test();
Test test2 = new Test();
}
Here, both the objects test1 and test2 will have separate copies of the variable age.
And, they are different from each other.
However, if we declare a variable static, all objects of the class share the same
static variable. It is because like static methods, static variables are also associated
with the class. And, we don't need to create objects of the class to access the static
variables.
For example,
class Test {
// static variable
static int age;
}
class Main {
// access the static variable
Test.age = 20;
}

Example 2: Java static and non-static Variables


class Test {
// static variable
static int max = 10;
// non-static variable
int min = 5;
}
public class Main {
public static void main(String[] args) {
Test obj = new Test();
// access the non-static variable
System.out.println("min + 1 = " + (obj.min + 1));
// access the static variable
System.out.println("max + 1 = " + (Test.max + 1));
}
}
Output
min + 1 = 6
max + 1 = 11
In the above program, we have declared a non-static variable named min and a
static variable named max inside the class Test.
Inside the Main class, we can see that we are calling the non-static variable using
the object of the class (obj.min + 1). However, we are calling the static variable by
using the class name (Test.max + 1).
Note: Static variables are rarely used in Java. Instead, the static constants are used.
These static constants are defined by static final keyword and represented in
uppercase. This is why some people prefer to use uppercase for static variables as
well.

Access static Variables and Methods within the Class


We are accessing the static variable from another class. Hence, we have used the
class name to access it. However, if we want to access the static member from
inside the class, it can be accessed directly. For example,
public class Main {
// static variable
static int age;
// static method
static void display() {
System.out.println("Static Method");
}
public static void main(String[] args) {
// access the static variable
age = 30;
System.out.println("Age is " + age);
// access the static method
display();
}}

Output
Static Method
Age is 30

Static Method
Here, we are able to access the static variable and method directly without using
the class name. It is because static variables and methods are by default public.
And, since we are accessing from the same class, we don't have to specify the class
name.

Static Blocks
In Java, static blocks are used to initialize the static variables. For example,
class Test {
// static variable
static int age;

// static block
static {
age = 23;
}}
Here we can see that we have used a static block with the syntax:
static {
// variable initialization
}
The static block is executed only once when the class is loaded in memory.
The class is loaded if either the object of the class is requested in code or the static
members are requested in code.
A class can have multiple static blocks and each static block is executed in the
same sequence in which they have been written in a program.

Example 3: Use of static block in java


class Main {
// static variables
static int a = 23;
static int b;
static int max;
// static blocks
static {
System.out.println("First Static block.");
b = a * 4;
}
static {
System.out.println("Second Static block.");
max = 30;
}
// static method
static void display() {
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("max = " + max);
}
public static void main(String args[]) {
// calling the static method
display();
}}
Output
First Static block.
Second Static block.
a = 23
b = 92
max = 30
In the above program. as soon as the Main class is loaded,
The value of a is set to 23.
The first static block is executed. Hence, the string First Static block is printed and
the value of b is set to a * 4.
The second static block is executed. Hence, the string Second Static block is
printed and the value of max is set to 30.
And finally, the print statements inside the method display() are executed.

Nested Static Class


In Java, we can declare a class inside another class. Such classes are known as
nested classes. Nested classes are of 2 types:
 Static Nested Classes
 Non-static Nested Classes
For example,
class OuterClass {
// static nested class
staticclass NestedClass {...}
// non-static nested class
class InnerClass {...}
}
JAVA FINAL KEYWORD
Example
Set a variable to final, to prevent it from being overridden/modified:
public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // will generate an error
System.out.println(myObj.x);
}}
Main.java:6: error: cannot assign a value to final variable x
myObj.x=25;
^
1 error

Definition and Usage


The final keyword is a non-access modifier used for classes, attributes and
methods, which makes them non-changeable (impossible to inherit or override).

The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).

The final keyword is called a "modifier".

JAVA ACCESS CONTROL MODIFIERS


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

class Animal {
public void method1() {...}
private void method2() {...}
}

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.
Note the keyword public and private. These are access modifiers in Java. They
are also known as visibility modifiers.

Types of Access Modifier


There are four access modifiers keywords in Java and they are:

Modifier Description

Default declarations are visible onlywithin the package (package private)

Private declarations are visiblewithin the class only

Protected declarations are visible within the package or all subclasses

Public declarations are visible everywhere

Default Access Modifier


If we do not explicitly specify any access modifier for classes, methods,
variables, etc, then by default the default access modifier is considered.
For example,

package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
Here, the Logger class has the default access modifier. And the class is visible to
all the classes that belong to the defaultPackage package. However, if we try to use
the Logger class in another class outside of defaultPackage, we will get a
compilation error.

Private Access Modifier


When variables and methods are declared private, they cannot be accessed
outside of the class.
For example,
class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main)
{
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Programiz";
}}
In the above example, we have declared a private variable named name. When we
run the program, we will get the following error:

Main.java:18: error: name has private access in Data


d.name = "Programiz";
^

The error is generated because we are trying to access the private variable of
the Data class from the Main class.
You might be wondering what if we need to access those private variables. In this
case, we can use the getters and setters method. For example,

class Data {
private String name;

// getter method
public String getName() {
return this.name;
}
// setter method
public void setName(String name) {
this.name= name;
}}
public class Main {
public static void main(String[] main){
Data d = new Data();
// access the private variable using the getter and setter
d.setName("Programiz");
System.out.println(d.getName());
}}
Output:
The name is Programiz

In the above example, we have a private variable named name. In order to access
the variable from the outer class, we have used
methods: getName() and setName(). These methods are called getter and setter in
Java.
Here, we have used the setter method (setName()) to assign value to the variable
and the getter method (getName()) to access the variable.
We have used this keyword inside the setName() to refer to the variable of the
class. To learn more on this keyword, visit Java this Keyword.

Note: We cannot declare classes and interfaces private in Java. However, the
nested classes can be declared private.

Protected Access Modifier


When methods and data members are declared protected, we can access them
within the same package as well as from subclasses. For example,

class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
Output:
I am an animal

In the above example, we have a protected method named display() inside


the Animal class. The Animal class is inherited by the Dog class.
We then created an object dog of the Dog class. Using the object we tried to
access the protected method of the parent class.
Since protected methods can be accessed from the child classes, we are able to
access the method of Animal class from the Dog class.

Note: We cannot declare classes or interfaces protected in Java.


Public Access Modifier
When methods, variables, classes, and so on are declared public, then we can
access them from anywhere. The public access modifier has no scope restriction.
For example,
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


animal.legCount = 4;
// accessing the public method
animal.display();
}
}

Output:
I am an animal.
I have 4 legs.

Here,

 The public class Animal is accessed from the Main class.


 The public variable legCount is accessed from the Main class.
 The public method display() is accessed from the Main class.

JAVA THIS KEYWORD


Example
Using this with a class attribute (x):
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
OUTPUT
Value of x = 5

Definition and Usage


The this keyword refers to the current object in a method or constructor.

The most common use of the this keyword is to eliminate the confusion between
class attributes and parameters with the same name (because a class attribute is
shadowed by a method or constructor parameter). If you omit the keyword in the
example above, the output would be "0" instead of "5".

JAVA GARBAGE COLLECTION


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.

To do so, 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:

o By nulling the reference


o By assigning a reference to another
o By anonymous object etc.

1) By nulling a reference:
Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:
new Employee();

finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:

protected void finalize(){}


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.

Simple Example of garbage collection in java


public class TestGarbage1{

public void finalize(){System.out.println("object is garbage collected");}

public static void main(String args[]){

TestGarbage1 s1=new TestGarbage1();

TestGarbage1 s2=new TestGarbage1();

s1=null;

s2=null;

System.gc();

}}

OUTPUT
object is garbage collected
object is garbage collected

JAVA NESTED AND INNER CLASS


In this tutorial, you will learn about the nested class in Java and its types with the
help of examples.

In Java, you can define a class within another class. Such class is known as nested
class. For example,

class OuterClass {

// ...
class NestedClass {

// ...

}}

There are two types of nested classes you can create in Java.

 Non-static nested class (inner class)


 Static nested class

Non-Static Nested Class (Inner Class)


A non-static nested class is a class within another class. It has access to members
of the enclosing class (outer class). It is commonly known as inner class.

Since the inner class exists within the outer class, you must instantiate the outer
class first, in order to instantiate the inner class.

Here's an example of how you can declare inner classes in Java.

Example 1: Inner class


class CPU {
double price;
// nested class
class Processor{

// members of nested class


double cores;
String manufacturer;

double getCache(){
return 4.3;
}
}
// nested protected class
protected class RAM{
// members of protected nested class
double memory;
String manufacturer;
double getClockSpeed(){
return 5.5;
}
}
}
public class Main {
public static void main(String[] args) {
// create object of Outer class CPU
CPU cpu = new CPU();
// create an object of inner class Processor using outer class
CPU.Processor processor = cpu.new Processor();
// create an object of inner class RAM using outer class CPU
CPU.RAM ram = cpu.new RAM();
System.out.println("Processor Cache = " + processor.getCache());
System.out.println("Ram Clock speed = " + ram.getClockSpeed());
}
}

Output:
Processor Cache = 4.3
Ram Clock speed = 5.5
In the above program, there are two nested classes: Processor and RAM inside the
outer class: CPU. We can declare the inner class as protected. Hence, we have
declared the RAM class as protected.

Inside the Main class,

 we first created an instance of an outer class CPU named cpu.


 Using the instance of the outer class, we then created objects of inner
classes:

CPU.Processor processor = cpu.new Processor;


CPU.RAM ram = cpu.new RAM();
Note: We use the dot (.) operator to create an instance of the inner class using the
outer class.

Static Nested Class


In Java, we can also define a static class inside another class. Such class is known
as static nested class. Static nested classes are not called static inner classes.

Unlike inner class, a static nested class cannot access the member variables of the
outer class. It is because the static nested class doesn't require you to create an
instance of the outer class.

OuterClass.NestedClass obj = new OuterClass.NestedClass();

Here, we are creating an object of the static nested class by simply using the class
name of the outer class. Hence, the outer class cannot be referenced
using OuterClass.this.

Example 3: Static Inner Class


class MotherBoard {

// static nested class


static class USB{
int usb2 = 2;
int usb3 = 1;
int getTotalPorts(){
return usb2 + usb3;
}
}
}
public class Main {
public static void main(String[] args) {

// create an object of the static nested class


// using the name of the outer class
MotherBoard.USB usb = new MotherBoard.USB();
System.out.println("Total Ports = " + usb.getTotalPorts());
}
}

Output:
Total Ports = 3
In the above program, we have created a static class named USB inside the
class MotherBoard. Notice the line,
MotherBoard.USB usb = new MotherBoard.USB();
Here, we are creating an object of USB using the name of the outer class.

JAVA STRINGS
In Java, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use double quotes to represent a string in Java. For example,
// create a string
String type = "Java programming";
Here, we have created a string variable named type. The variable is initialized with
the string Java Programming.

Example: Create a String in Java


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

// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
OUTPUT
Java
Python
JavaScript

In the above example, we have created three strings named first, second, and third. Here,
we are directly creating strings like primitive types.
However, there is another way of creating Java strings (using the new keyword). We
will learn about that later in this tutorial.
Note: Strings in Java are not primitive types (like int , char , etc). Instead, all strings are
objects of a predefined class named String .

And, all string variables are instances of the String class.

Java String Operations


Java String provides various methods to perform different operations on strings.
We will look into some of the commonly used string operations.
1. Get length of a String
To find the length of a string, we use the length() method of the String. For
example,
class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();
System.out.println("Length: " + length);
}
}
OUTPUT
String: Hello! World
Length: 12
In the above example, the length() method calculates the total number of characters
in the string and returns it. To learn more, visit Java String length().
2. Join Two Java Strings
We can join two strings in Java using the concat() method. For example,
class Main {
public static void main(String[] args) {

// create first string


String first = "Java ";
System.out.println("First String: " + first);

// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
OUTPUT
First String: Java
Second String: Programming
Joined String: Java Programming
In the above example, we have created two strings named first and second.
Notice the statement,
String joinedString = first.concat(second);
Here, the concat() method joins the second string to the first string and assigns it to
the joinedString variable.
We can also join two strings using the + operator in Java. To learn more, visit Java
String concat().
3. Compare two Strings
In Java, we can make comparisons between two strings using the equals() method.
For example,
class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);

// compare first and third strings


boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}
OUTPUT
Strings first and second are equal: true
Strings first and third are equal: false
In the above example, we have created 3 strings named first, second, and third.
Here, we are using the equal() method to check if one string is equal to another.
The equals() method checks the content of strings while comparing them. To learn
more, visit Java String equals().
Note: We can also compare two strings using the == operator in Java. However,
this approach is different than the equals() method. To learn more, visit Java
String == vs equals().

Java Strings are Immutable


In Java, strings are immutable. This means, once we create a string, we cannot
change that string.
To understand it more deeply, consider an example:

// create a string
String example = "Hello! ";

Here, we have created a string variable named example. The variable holds the
string "Hello! ".
Now suppose we want to change the string.

// add another string "World"


// to the previous tring example
example = example.concat(" World");

Here, we are using the concat() method to add another string World to the
previous string.
It looks like we are able to change the value of the previous string. However, this is
not true.
Let's see what has happened here,

1. JVM takes the first string "Hello! "


2. creates a new string by adding "World" to the first string
3. assign the new string "Hello! World" to the example variable
4. the first string "Hello! " remains unchanged
Creating strings using the new keyword
So far we have created strings like primitive types in Java.
Since strings in Java are objects, we can create strings using the new keyword as
well. For example,

// create a string using the new keyword


String name = new String("Java String");

In the above example, we have created a string name using the new keyword.
Here, when we create a string object, the String() constructor is invoked. To learn
more about constructor, visit Java Constructor.

Note: The String class provides various other constructors to create strings. To
learn more, visit Java String (official Java documentation).

Example: Create Java Strings using the new keyword


class Main {
public static void main(String[] args) {
// create a string using new
String name = new String("Java String");
System.out.println(name); // print Java String
}
}
OUTPUT
Java String

Create String using literals vs new keyword


Now that we know how strings are created using string literals and
the new keyword, let's see what is the major difference between them.
In Java, the JVM maintains a string pool to store all of its strings inside the
memory. The string pool helps in reusing the strings.
1. While creating strings using string literals,

String example = "Java";


Here, we are directly providing the value of the string (Java). Hence, the compiler
first checks the string pool to see if the string already exists.
 If the string already exists, the new string is not created. Instead, the new
reference, example points to the already existed string (Java).
 If the string doesn't exist, the new string (Java is created.
2. While creating strings using the new keyword,

String example = new String("Java");


Here, the value of the string is not directly provided. Hence, a new "Java" string is
created even though "Java" is already present inside the memory pool.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy