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

Java UnitI Ppt

Uploaded by

ayuu19628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views132 pages

Java UnitI Ppt

Uploaded by

ayuu19628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 132

UNIT-I (BCS-

403)
2nd year- 4th Sem (IT1 and IT2),
Monalisa Panigrahi
Topics (Syllabus)
 Introduction: Why Java, History of Java, JVM, JRE, Java
Environment, Java Source File Structure, and Compilation.
Fundamental,
 Programming Structures in Java: Defining Classes in Java,
Constructors, Methods, Access Specifies, Static Members, Final
Members, Comments, Data types, Variables, Operators, Control
Flow, Arrays & String.
 Object Oriented Programming: Class, Object, Inheritance Super
Class, Sub Class, Overriding, Overloading, Encapsulation,
Polymorphism, Abstraction, Interfaces, and Abstract Class.
 Packages: Defining Package, CLASSPATH Setting for Packages,
Making JAR Files for Library Packages, Import and Static Import
Naming Convention For Packages
Introduction to JAVA

 JAVA was developed by Sun Microsystems Inc in


1991, later acquired by Oracle Corporation.

 It was developed by James Gosling and Patrick


Naughton. It is a simple programming language.

 Writing, compiling and debugging a program is


easy in java. It helps to create modular programs
and reusable code.
Why to learn JAVA (key
Features)
 Object Oriented − In Java, everything is an Object. Java can be
easily extended since it is based on the Object model.
 Platform Independent − Unlike many other programming
languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the
web and interpreted by the Virtual Machine (JVM) on whichever
platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand
the basic concept of OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-
free, tamper-free systems. Authentication techniques are based
on public-key encryption.
 Architecture-neutral − Java compiler generates an
architecture-neutral object file format, which makes the compiled
code executable on many processors, with the presence of Java
runtime system.
 Portable − Being architecture-neutral and having no implementation
dependent aspects of the specification makes Java portable. Compiler
in Java is written in ANSI C with a clean portability boundary, which is
a POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime
checking.
 Multithreaded − With Java's multithreaded feature it is possible to
write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive
applications that can run smoothly.
 Interpreted − Java byte code is translated on the fly to native
machine instructions and is not stored anywhere. The development
process is more rapid and analytical since the linking is an
incremental and light-weight process.
 High Performance − With the use of Just-In-Time compilers, Java
enables high performance.
 Distributed − Java is designed for the distributed environment of the
internet.
 Dynamic − Java is considered to be more dynamic than C or C++
since it is designed to adapt to an evolving environment. Java
programs can carry extensive amount of run-time information that
can be used to verify and resolve accesses to objects on run-time.
Application

There are many devices where Java is currently used.


Some of them are as follows:

1.Desktop Applications such as acrobat reader, media


player, antivirus, etc.
2.Web Applications such as irctc.co.in, javatpoint.com, etc.
3.Enterprise Applications such as banking applications.
4.Mobile
5.Embedded System
6.Smart Card
7.Robotics
8.Games, etc.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application
Standalone applications are also known as desktop applications or window-
based applications. These are traditional software that we need to install on
every machine. Examples of standalone application are Media player, antivirus,
etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates a dynamic page is called
a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is
called enterprise application. It has advantages of the high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise
applications.

4) Mobile Application
An application which is created for mobile devices is called a mobile
application. Currently, Android and Java ME are used for creating mobile
applications.
Java is an Object Oriented
language

Object oriented programming is a way of organizing


programs as collection of objects, each of which
represents an instance of a class.
4 main concepts of Object Oriented programming
are:

1.Abstraction

2.Encapsulation

3.Inheritance

4.Polymorphism
Object-Oriented Programming is a
methodology or paradigm to design a
program using classes and objects.
 Object means a real-world entity such as a pen, chair,
table, computer, watch, etc. An Object can be defined as
an instance of a class. An object contains an address and
takes up some space in memory. Objects can
communicate without knowing the details of each other's
data or code.
 Class: Collection of objects is called class. It is a logical entity. A class can also be
defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.

 Inheritance: When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.

 Polymorphism: If one task is performed in different ways, it is known as


polymorphism. For example: to convince the customer differently, to draw
something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.

 Abstraction: Hiding internal details and showing functionality is known as


abstraction. For example phone call, we don't know the internal processing. In Java,
we use abstract class and interface to achieve abstraction.

 Encapsulation: Binding (or wrapping) code and data together into a single unit are
known as encapsulation. For example, a capsule, it is wrapped with different
medicines. A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
What is the difference
between an object-oriented
programming language and
object-based programming
language?
 Object-based programming language
follows all the features of OOPs except
Inheritance. JavaScript and VBScript are
examples of object-based programming
languages.
C++ vs Java
Comparison Index C++ Java
Platform-independent C++ is platform-dependent. Java is platform-independent.

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

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

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

Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved
by interfaces in java.

Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading.
Pointers C++ supports pointers. You can Java supports pointer internally. However, you can't write the pointer
write pointer program in C++. program in java. It means java has restricted pointer support in java.

Compiler and Interpreter C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java source code is converted into
compiled and run using the compiler bytecode at compilation time. The interpreter executes this bytecode at
which converts source code into runtime and produces output. Java is interpreted that is why it is platform
machine code so, C++ is platform independent.
dependent.
Call by Value and Call by C++ supports both call by value and call by Java supports call by value only. There is no
reference reference. call by reference in java.

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

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

Documentation comment C++ doesn't support documentation comment. Java supports documentation comment (/** ...
*/) to create documentation for java source
code.

Virtual Keyword C++ supports virtual keyword so that we can decide Java has no virtual keyword. We can override
whether or not override a function. all non-static methods by default. In other
words, non-static methods are virtual by
default.

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

Inheritance Tree C++ creates a new inheritance tree always. Java uses a single inheritance tree always
because all classes are the child of 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 language. However, in C Java is also an object-oriented language.


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

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello
World
}
}
JAVA PROGRAM
STRUCTURE
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello
would have different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case. Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter
should be in Upper Case. Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class
name. When saving the file, you should save it using the class name (Remember Java is
case sensitive) and append '.java' to the end of the name (if the file name and the class
name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then file name
can be different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.
Java Identifiers

All Java components require names. Names used for classes, variables, and
methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as
follows −
All identifiers should begin with a letter (A to Z or a to z), currency character
($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers

Like other languages, it is possible to modify classes, methods,


etc., by using modifiers. There are two categories of modifiers −
Access Modifiers − default, public , protected, private
Non-access Modifiers − final, abstract, strictfp
File compilation and
execution
 Save this file as MyFirstJavaProgram.java
 To compile write command
javac MyFirstJavaProgram.java in
command prompt.
 To execute this file write command
java MyFirstJavaProgram in command prompt.
Compilation and Execution
flow
JVM Architecture
How JVM Works
 Class Loader: The class loader reads the .class file and save the byte code in the
method area.
 Method Area: There is only one method area in a JVM which is shared among all
the classes. This holds the class level information of each .class file.
 Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a
Class object for each .class file.
 Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing
temporary variables.
 PC Registers: This keeps the track of which instruction has been executed and
which one is going to be executed. Since instructions are executed by threads,
each thread has a separate PC register.
 Native Method stack: A native method can access the runtime data areas of
the virtual machine.
 Native Method interface: It enables java code to call or be called by native
applications. Native applications are programs that are specific to the hardware
and OS of a system.
 Garbage collection: A class instance is explicitly created by the java code and
after use it is automatically destroyed by garbage collection for memory
management.
JVM Vs JRE Vs JDK
Variables in Java
 To declare a variable follow this syntax:
 data_type variable_name = value;
Ex: int num;
char ch = 'A';
int number = 100;
 Types of Variables in Java :
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable
 Variables naming convention in java
1) Variables naming cannot contain white spaces, for example: int num ber
= 100; is invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with
a lower case letter, for example int number; For lengthy variables names
that has more than one words do it like this: int smallNumber; int
bigNumber; (start the second word with capital letter).
4) Variable names are case sensitive in Java.
Data Types
Operators in Java

 An operator is a character that represents an


action, for example + is an arithmetic operator
that represents addition.
 Types of Operator in Java
1) Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement
Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof

equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&


logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=
Operator examples
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);
System.out.println(b++ + b++);

}
}

Output: 22
21
Arithmetic operator

class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}

Output: 21
Type Casting in Java

 Type casting is used to convert an object or variable of one type into


another.
 Syntax: dataType variableName = (dataType)
variableToConvert;
 There are two casting directions: narrowing (larger to smaller type) and
widening (smaller to larger type). Widening can be done automatically
(for example, int to double), but narrowing must be done explicitly (like
double to int).
 Widening or Automatic Type Conversion: Widening conversion
takes place when two data types are automatically converted. This
happens when:
1. The two data types are compatible.
2. When we assign value of a smaller data type to a bigger data
type.
Example:
class Test
{
public static void main(String[] args)
{
int i = 100;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f); } }

Output: Int value 100


Long value 100
Float value 100.0
Narrowing or Explicit
Conversion

 If we want to assign a value of larger data type to a smaller data type we


perform explicit type casting or narrowing.

 This is useful for incompatible data types where automatic conversion


cannot be done.
 Here, target-type specifies the desired type to convert the specified value
to.
Example:
//Java program to illustrate incompatible data
// type for explicit type conversion
public class Test
{
public static void main(String[] argv)
{
char ch = 'c';
int num = 88;
ch = num;
}
}
Output:error: incompatible types: possible lossy conversion from int to char
ch = num;
^
1 error
Explicit Conversion
//Java program to illustrate explicit type conversion
class Test
{ public static void main(String[] args)
{ double d = 100.04;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i); } }

Output: Double value 100.04


Long value 100
Int value 100
Control Statement

 If Statement:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
} } }
Output: Age is greater than 18
If-else statement

public class LeapYearExample {


public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !
=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
} } }

Output: LEAP YEAR


If else-if Statement

public class PositiveNegativeExample {


public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
Output: NEGATIVE
Switch statement
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30"); } } }
Output: 20
Java Break Statement

When a break statement is encountered inside a


loop, the loop is immediately terminated and the
program control resumes at the next statement
following the loop.

The Java break 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.
For Loops
class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}
Output: The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
For loop example to iterate an
array:
Here we are iterating and displaying array elements using the for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}

Output: 2
11
45
9
Enhanced For loop
 Enhanced for loop is useful when you want to iterate
Array/Collections, it is easy to write and understand.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
Outpu
}
t: 2
11
45
9
Practice for loop

 Write a Java Program to find sum of natural


numbers using for loop.
 Write a Java Program to find factorial of a number
using loops.
 Write a Java Program to print Fibonacci Series
using for loop.
While Loop
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
} } } Output:10
9
8
7
6
5
4
3
2
Practice while loop

 Write a Java Program to display Fibonacci Series


using while loop.
 Write a Java Program to find factorial using while
loop.
Do-while statement

class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
Output :10
}while(i>1); 9
8
}
7
} 6
5
4
3
2
Continue Statement
 Continue statement is mostly used inside loops. Whenever it is
encountered inside a loop, control directly jumps to the beginning of
the loop for next iteration, skipping the execution of statements inside
loop’s body for the current iteration. This is particularly useful when
you want to continue the loop but do not want the rest of the
statements(after continue statement) in loop body to execute for that
particular iteration.
public class ContinueExample {
public static void main(String args[]){
for (int j=0; j<=6; j++) {
if (j==4)
{
continue;
}
System.out.print(j+" "); } } }
Output: 0 1 2 3 5 6
public class MyClass { // Class declaration

// Fields (instance variables)


private String name;
private int age;

// Constructor
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}

// Methods
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Object and class example
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{ Classname objname = new constructor
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
Output: 0
} null
}
main outside the class

//Java Program to demonstrate having the main method in


//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
Output: 0
System.out.println(s1.name); null
}
}
Ways to initialize object

 There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor
By reference variable

class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Balagurusamy";
System.out.println(s1.id+" "+s1.name);//printing members with a white
space
} Output: 101 Balagurusamy
}
By method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n; }
void displayInformation(){System.out.println(rollno+" "+name); } }
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan"); Output: 111 Karan
s1.displayInformation(); 222 Aryan
s2.displayInformation(); } }
Constructor

 a constructor is a block of codes similar to the


method. It is called when an instance of the class
is created. At the time of calling constructor,
memory for the object is allocated in the memory.
 It is a special type of method which is used to
initialize the object.
 Every time an object is created using the new()
keyword, at least one constructor is called.
Example of Constructor
Rules for creating Java
constructor

There are some rules defined for the constructor.


Constructor name must be the same as its class
name.
A Constructor must have no explicit return type.
A Java constructor cannot be abstract, static, final,
and synchronized.
We can use access modifiers while declaring a
constructor. It controls the object creation. In other
words, we can have private, protected, public or
default constructor in Java.
Types of Java constructors

 There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor

//Java Program to create and call a default


constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1(); Output: Bike is created

}
}
Parameterized Constructor
 A constructor which has a specific number of parameters is called a parameterized constructor.

//Java Program to demonstrate the use of the parameterized constructor.

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n; }

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

//creating objects and passing values

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

//calling method to display the values of object

s1.display();

s2.display(); } }
Copy Constructor

 Copy constructors in Java are special constructors,


which is used to copy the properties of one object
into another.

 They allow the creation of a new object by


copying the values of an already present object of
the same class.

 You can create an exact duplicate of an object by


deploying copy constructors.
Copy Constructor
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and breadth of rectangle
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("Copy Constructor Invoked");
length = obj.length;
breadth= obj.breadth;
}
//method to calcuate area of rectangle
int area()
{
return (length * breadth);
}}
//class to create Rectangle object and calculate area
class CopyConstructor {
public static void main(String[] args) {
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect= new Rectangle(firstRect);
System.out.println("Area of First Rectangle : "+ firstRect.area());
System .out.println("Area of First Second Rectangle : "+
secondRect.area()); }}
Arrays

 An array is a collection of similar type of elements


which have a contiguous memory location.
 Java array is an object which contains elements of
a similar data type. Additionally, The elements of
an array are stored in a contiguous memory
location. It is a data structure where we store
similar elements. We can store only a fixed set of
elements in a Java array.
 There are two types of array.

1. Single Dimensional Array

2. Multidimensional Array
Creating an array
 Creation of an array involves three steps:

1. Declaring the array.

2. Creating memory locations.

3. Putting values into the memory locations.

1. Syntax for declaring an one dimensional array

type var-name[];

OR

type[] var-name;

2. Creating memory locations.

Java allows us to create array using new operator only.

arrayname=new type[size];

The above statement does two things −

It creates an array using new type[Size].

It assigns the reference of the newly created array to the variable array name

Putting values into memory locations:

Type[] arrayname = {value0, value1, ..., valuek};


Example of array
/Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50; Output: 10
//traversing array 20
70
for(int i=0;i<a.length;i++)//length is the property of array
40
System.out.println(a[i]); 50
}}
Multidimensional
Arrays
 Multidimensional arrays are arrays of arrays with
each element of the array holding the reference of
other array. These are also known as Jagged
Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per
dimension. Examples:

 int[][] intArray = new int[10][20]; //a 2D array or


matrix
 int[][][] intArray = new int[10][20][10]; //a 3D
array
 class multiDimensional {
public static void main(String args[]) {
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++) {
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
} }}
Output:

279
361
742
Passing Arrays to Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr); }
public static void sum(int[] arr) {
// getting sum of array values
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum); } }

Output: sum of array values :


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

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

is same as:
String s="javatpoint”
There are two ways to create String object:
By string literal: String s="welcome";
By new keyword: String s=new String("Welcome")
Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new
keyword
System.out.println(s1);
System.out.println(s2);
Output: java
System.out.println(s3); strings
}} example
No. Method Description

1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.

4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.

5 String substring(int beginIndex) returns substring for given begin index.


6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index.

7 boolean contains(CharSequence s) returns true or false after matching the sequence of


char value.

8 static String join(CharSequence delimiter, CharSequence... elements) returns a joined string.

9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string.

10 boolean equals(Object another) checks the equality of string with the given object.

11 boolean isEmpty() checks if string is empty.


12 String concat(String str) concatenates the specified string.
13 String replace(char old, char new) replaces all occurrences of the specified char value.

14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.

15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.

16 String[] split(String regex) returns a split string matching regex.


17 String[] split(String regex, int limit) returns a split string matching regex and limit.

18 String intern() returns an interned string.

19 int indexOf(int ch) returns the specified char value index.

20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.

21 int indexOf(String substring) returns the specified substring index.

22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.

23 String toLowerCase() returns a string in lowercase.

24 String toLowerCase(Locale l) returns a string in lowercase using specified locale.

25 String toUpperCase() returns a string in uppercase.

26 String toUpperCase(Locale l) returns a string in uppercase using specified locale.

27 String trim() removes beginning and ending spaces of this string.

28 static String valueOf(int value) converts given type into string. It is an overloaded method.
What is a class?

 Early languages had only arrays


 all elements had to be of the same type
 Then languages introduced structures
(called records, or structs)
 allowed different data types to be grouped
 Then Abstract Data Types (ADTs)
became popular
 grouped operations along with the data
So, what is a class?

 A class consists of
 a collection of fields, or variables, very much like the
named fields of a struct
 all the operations (called methods) that can be
performed on those fields
 can be instantiated
 A class describes objects and operations defined
on those objects
Name conventions

 Java is case-sensitive; maxval, maxVal, and MaxVal are three


different names
 Class names begin with a capital letter
 All other names begin with a lowercase letter
 Subsequent words are capitalized: theBigOne
 Underscores are not used in names
 These are very strong conventions!
The class hierarchy

 Classes are arranged in a hierarchy


 The root, or topmost, class is Object
 Every class but Object has at least one superclass
 A class may have subclasses
 Each class inherits all the fields and methods of its (possibly
numerous) superclasses
An example of a class

class Person {
String name;
int age;
void birthday ( ) {
System.out.println (name + ' is
now ' + age);
}
}
Creating and using an
object
 Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
 Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );
Object and class Example

//Java Program to illustrate how to define a class and fields


//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Inheritance

 Inheritance in Java is a mechanism in which one object


acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented
programming system).
 The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
 Inheritance represents the IS-A relationship which is also
known as a parent-child relationship.
 Child Class:
The class that extends the features of another class is
known as child class, sub class or derived class.
 Parent Class:
The class whose properties and functionalities are
used(inherited) by another class is known as parent class,
super class or Base class.
 extends Keyword: extends is the keyword used to inherit the
properties of a class. Following is the syntax of extends
keyword.

Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example:
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}
public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics"; Output: Beginnersbook
public static void main(String args[]){
Teacher
Physics
PhysicsTeacher obj = new PhysicsTeacher();
Teaching
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
Types of inheritance in
java
 On the basis of class, there can be three types of
inheritance in java: single, multilevel and
hierarchical.
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:

barking...
eating...
Multilevel Inheritance
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output: weeping...
barking...
eating...
Hierarchical Inheritance
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{ Output: meowing...
public static void main(String args[]){ eating...
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Encapsulation
 Encapsulation in Java is a process of wrapping code and
data together into a single unit, for example, a capsule
which is mixed of several medicines.

 We can create a fully encapsulated class in Java by


making all the data members of the class private. Now we
can use setter and getter methods to set and get the data
in it.
Polymorphism
Method Overloading
 Method Overloading is a feature that allows a class to have more than one method
having the same name, if their argument lists are different.
 If we have to perform only one operation, having same name of the methods
increases the readability of the program.
 Method overloading increases the readability of the program.
 Method overloading is an example of Static Polymorphism.
 Static Polymorphism is also known as compile time binding or early binding.
 Static binding happens at compile time. Method overloading is an example of
static binding where binding of method call to its definition happens at Compile
time.
 Invalid case of method overloading: if two methods have same name, same
parameters and have different return type, then this is not a valid method
overloading example. This will throw compilation error.

 int add(int, int)


 float add(int, int)
Three ways to overload a
method
 In order to overload a method, the argument lists of the methods
must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Example 1: Overloading – Different Number of parameters in
argument list
class DisplayOverloading
{ public void disp(char c)
{
System.out.println(c); }
public void disp(char c, int num) {
System.out.println(c + " "+num);
}}
class Sample
{ public static void main(String args[])
{ DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
} } Output:
a
a 10
Example 2: Overloading – Difference in data type of
parameters
class DisplayOverloading2
{ public void disp(char c)
{ System.out.println(c); }
public void disp(int c)
{ System.out.println(c ); } }
class Sample2
{ public static void main(String args[])
{ DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a'); Output : a
5
obj.disp(5); } }
Example3: Overloading – Sequence of data type of
arguments
class DisplayOverloading3
{ public void disp(char c, int num)
{ System.out.println("I’m the first definition of method disp” +c);
}
public void disp(int num, char c)
{ System.out.println("I’m the second definition of method disp”
+ c );
} }
class Sample3
{ public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y'); } }
Output: I’m the first definition of method disp x
I’m the second definition of method disp y
Constructor overloading

 Constructor overloading is a concept of having


more than one constructor with different
parameters list, in such a way so that each
constructor performs a different task.
class Student {

int Roll;

String Name;

double Marks;

Student(int R,String N,double M) // Constructor 1 {

Roll = R;

Name = N;

Marks = M; }

Student(String N,double M,int R) // Constructor 2 {

Roll = R;

Name = N;

Marks = M; }

void Display() {

System.out.print("\n\t" + Roll+"\t" + Name+"\t" + Marks); } }

class ConstructorOverloadingDemo {

public static void main(String[] args) {

Student S1 = new Student(1,"Kumar",78.53); // Statement 2

Student S2 = new Student("Sumit",89.42,2); // Statement 1


Output: Roll Name Marks
System.out.print("\n\tRoll\tName\tMarks\n");

S1.Display();
1 Kumar 78.53
2 Sumit 89.42
S2.Display(); } }
role of this () in
constructor overloading
public class OverloadingExample2{

private int rollNum;

OverloadingExample2() {

rollNum =100; }

OverloadingExample2(int rnum) {

this(); /*this() is used for calling the default

* constructor from parameterized constructor.

* It should always be the first statement

* inside constructor body.

*/

rollNum = rollNum+ rnum; }

public int getRollNum() {

return rollNum; }

public void setRollNum(int rollNum) {

this.rollNum = rollNum; }

public static void main(String args[]) {

OverloadingExample2 obj = new OverloadingExample2(12);

System.out.println(obj.getRollNum()); } }

Output: 112
this keyword
 There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object.

Usage of java this keyword: Here is given the 6 usage of java this keyword.

 this can be used to refer current class instance variable.


 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
static keyword
 Static keyword can be used with class, variable,
method and block. Static members belong to the
class instead of a specific instance, this means if you
make a member static, you can access it without
object.
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
 Nested class
Java static variable
 If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
 The static variable gets memory only once in the class area at the time of class loading.
 Advantages of static variable: It makes your program memory efficient (i.e., it saves
memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
 Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.
 //Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n; }
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);} }
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Output: 111 Karan ITS
Student s1 = new Student(111,"Karan"); 222 Aryan ITS
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display(); } }
Java static method

 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance
of a class.
 A static method can access static data member and can change the value
of it.
 Example of static method
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x; } Output: 125
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result); } }
Java static block

 Is used to initialize the static data member.


 It is executed before the main method at the time
of classloading.
 Example:
class A2{
static{System.out.println("static block is invoked");}

public static void main(String args[]){ Output:static block is invoked


Hello main
System.out.println("Hello main");
}
}
Method overriding
 Declaring a method in sub class which is already present in parent
class is known as method overriding.
 Overriding is done so that a child class can give its own
implementation to a method which is already provided by the parent
class.
 In this case the method in parent class is called overridden method
and the method in child class is called overriding method.
 The main advantage of method overriding is that the class can give
its own specific implementation to a inherited method without even
modifying the parent class code.
 Method Overriding is an example of runtime polymorphism. When
a parent class reference points to the child class object then the call
to the overridden method is determined at runtime, because during
method call which method(parent class or child class) is to be
executed is determined by the type of object. This process in which
call to the overridden method is resolved at runtime is known as
dynamic method dispatch
Example
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy(); Output:Boy is eating
//This will call the child class version of eat()
obj.eat();
}
}
Example of dynamic dispatch
class ABC{

//Overridden method

public void disp()

{ System.out.println("disp() method of parent class"); } }

class Demo extends ABC{

//Overriding method

public void disp(){

System.out.println("disp() method of Child class"); }

public void newMethod(){

System.out.println("new method of child class"); }

public static void main( String args[]) {

// When Parent class reference refers to the parent class object then in this case overridden method (the method of
parent class) is called. //

ABC obj = new ABC();

obj.disp();

/* When parent class reference refers to the child class object then the overriding method (method of child class) is
called.

* This is called dynamic method dispatch and runtime polymorphism */

ABC obj2 = new Demo();

obj2.disp(); } }
Output: disp() method of parent class
disp() method of Child class
Super

keyword
The super keyword is used for calling the parent class method/constructor.
super.myMethod() calls the myMethod() method of base class while super() calls
the constructor of base class.

class ABC{
public void myMethod()
{
System.out.println("Overridden method");
} }
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
System.out.println("Overriding method"); }
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod(); } }

Output: Overridden method


Overriding method
Final keyword

 final is a non-access modifier applicable only to a


variable, a method or a class.
Final variables

 When a variable is declared with final keyword, its value can’t be


modified, essentially, a constant. This also means that you must
initialize a final variable.
 We cannot change the value of a final variable once it is initialized. Ex:
class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}

Output:Exception in thread "main" java.lang.Error: Unresolved compilation pr


The final field Demo.MAX_VALUE cannot be assigned
Abstract Methods and
Classes
 A method without body (no implementation) is known as abstract method. A
method must always be declared in an abstract class, or in other words you can
say that if a class has an abstract method, it should be declared abstract as well.
 A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
 This is how an abstract method looks in java:
public abstract int myMethod(int n1, int n2);
Rules of Abstract Method:
1. Abstract methods don’t have body, they just have method signature.
2. If a class has an abstract method it should be declared abstract, the vice versa
is not true, which means an abstract class doesn’t need to have an abstract
method compulsory.
3. If a regular class extends an abstract class, then the class must have to
implement all the abstract methods of abstract parent class or it has to be
declared abstract as well.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Output: running safely


Interfaces
 The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
 In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
 Declaring Interfaces: The interface keyword is used to declare an interface.
interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}
 An interface is similar to a class in the following
ways −
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with
the name of the interface matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding
bytecode file must be in a directory structure that
matches the package name.
 However, an interface is different from a class in
several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields
that can appear in an interface must be declared both
static and final.
 An interface is not extended by a class; it is implemented
by a class.
interface MyInterface
{
public void method1();
public void method2();}
class Demo implements MyInterface{
// This class must have to implement both the abstract
methods else you will get compilation error
public void method1() {
System.out.println("implementation of method1"); }
public void method2() {
System.out.println("implementation of method2"); }
public static void main(String arg[]) {
MyInterface obj = new Demo();
obj.method1(); } }
Multiple Inheritance
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Difference between abstract class
and interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.

4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.

7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".

8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Packages
 A java package is a group of similar types of
classes, interfaces and sub-packages
 Package in java can be categorized in two form,
built-in package and user-defined package.
 There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
Advantages of using a
package in Java

 Reusability
 Better Organization
 Name Conflicts
Types of packages in Java
As mentioned in the beginning of this guide that we have two types of packages in
java.

1) User defined package: The package we create is called user-defined


package.

2) Built-in package: The already defined package like java.io.*, java.lang.* etc
are known as built-in packages.
Example of package

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
Syntax: javac -d directory javafilename
Ex: javac -d . Simple.java
To Run: java mypack.Simple
How to access package

 There are three ways to access the package from


outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using
packagename.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
How to send the class file to another
directory or drive
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run: To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
e:\sources> java -classpath c:\classes mypack.Simple
How to put two public classes
in a package

//save as A.java

package javatpoint;
public class A{}
//save as B.java

package javatpoint;
public class B{}
Sub packages in Java
 A package inside another package is known as sub package. For example If I
create a package inside letmecalculate package then that will be called sub
package.
 Lets say I have created another package inside letmecalculate and the sub
package name is multiply. So if I create a class in this subpackage it should have
this package declaration in the beginning:
Syntax: package letmecalculate.multiply;
Multiplication.java
package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b;} }
Now if I need to use this Multiplication class I have to either import the package like
this:
import letmecalculate.multiply;
or I can use fully qualified name like this:
letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();
Static import

 Static import is a feature introduced in Java programming


language ( versions 5 and above ) that allows members ( fields
and methods ) defined in a class as public static to be used in
Java code without specifying the class in which the field is
defined.
 Simple Example of static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
Access Modifier in JAVA

You might also like