You are on page 1of 87

DIGITAL NOTES

ON
JAVA PROGRAMMING

B.TECH II YEAR - II SEM


KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
AN AUTONOMOUS INSTITUTION - ACCREDITED BY NAAC WITH 'A' GRADE ( Powered by GENESIS )

3-5-2016, Narayanaguda,Hyderabad-500029, Telangana. India


Phone: 04023261407,Website: http://www.kmit.in,

B.Tech. II Year SEM II Syllabus (KR20 Regulations)


Computer Science and Engineering

CS401PC JAVA PROGRAMMING

II YEAR B.TECH CSE II-SEM LTPC


3104

Course Objectives: To learn


• The object oriented programming concepts,
• To understand object oriented programming concepts, and apply them in solving problems,
• To introduce the principles of inheritance and polymorphism; and demonstrate how they relate
• To the design of abstract classes and to introduce the implementation of packages and interfaces,
• To introduce the concepts of exception handling and multithreading.

Course Outcomes: After learning the contents of this course the student is able to
 Use concepts of OOPs such as data abstraction, inheritance, polymorphism, encapsulation and method
overloading principles in structuring computer applications for solving problems.
 Choose appropriate collections to solve programming problems.
 Utilize the concepts of I/O streams and exception handling in a given real time problem.
 Build java applications to utilize advanced mechanisms like multi threading, database connectivity, etc.
 Apply the concepts and principles of the programming language to the real-world problems and solve the
problems through project-based learning.

UNIT - I
Object-Oriented Thinking- A way of viewing world –Methods, Responsibilities, Classes and Instances, Class
Hierarchies- Inheritance, Method binding, Encapsulation, Abstraction.

Summary of Object - Oriented concepts. Java buzzwords, An Overview of Java, Data types, Variables and
operators, expressions, control statements, Introducing classes, Methods and Classes,

Arrays - One Dimensional Array, Second Dimensional Array, Jagged Arrays, String handling. String Builder,
String Buffer, String Tokenizer() String API‘s like length(),substring(), charAt(), indexOf(), replace(),
toCharArray() .

Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors, Types of constructors ,
Creating Multilevel hierarchy, super uses, this uses , static uses, static and instance blocks, using final with
inheritance, Polymorphism Method overriding method overloading, abstract classes, Object class, forms of
inheritance-specialization, benefits of inheritance, costs of inheritance.
UNIT - II
Introduction to Packages- Defining a Package, CLASSPATH, Access protection, importing packages. Interfaces-
defining an interface, implementing interfaces, Nested interfaces, applying interfaces, variables in interfaces and
extending interfaces.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading console Input and
Writing Console Output, File class, Reading and writing Files, Reading and Writing Objects to a file, Serialization,
De-Serialization ,transient keyword , transient and static variables .

UNIT - III
Exception handling - Fundamentals of exception handling, Exception types, Termination or resumptive models,
Uncaught exceptions, using try and catch, multiple catch clauses, nested try statements, throw, throws and finally,
built- in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-based multitasking, Java thread
model, thread life cycle, different ways of creating threads, thread priorities, synchronized keyword and
synchronized block, inter thread communication, Producer Consumer Problem. Thread class API‘s

UNIT - IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces List, Map and Set, The
Collection classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing a
Collection via an Iterator, Using an Iterator, The For-Each alternative, Map Interfaces and Classes, Comparators,
Arrays, Stack, Vector, Enumerations, Auto boxing, Scanner class

UNIT - V
An overview of Advanced JAVA : Introduction to JDBC , Types of JDBC Drivers,Connectivity with
Oracle/MySQL, Driver Manager API , Connection API , Statement API- Prepared Statement, invoking stored
procedure using Callable Statement, Result Set , Properties of Result Set . Transaction Management using JDBC
API , autocommit , savepoint and rollback methods.Exception Handling in JDBC.

TEXT BOOKS:
1. Herbert Schildt, ― Java The complete reference‖, 9th edition, McGraw Hill Education (India) Pvt. Ltd, 2014. 2.
2. George Reese, ―Java Database Best Practices‖, O'Reilly Media, 2003.
REFERENCES:
1. J. Nino and F.A. Hosch, ―An Introduction to programming and OO design using Java‖, John Wiley & sons,
2008.
2. Y. Daniel Liang, Introduction to Java programming, Pearson Education, 2012.
Unit-1
OOP Concepts

Object Oriented Programming is a paradigm that provides many concepts such as


inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object is known as truly object-oriented
programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

JAVA PROGRAMMING Page 1


Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: 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.

Benefits of Inheritance

 One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units.
 Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a
method is superclass
 Reusability - facility to use public methods of base class without rewriting the same.
 Extensibility - extending the base class logic as per business logic of the derived class.

JAVA PROGRAMMING Page 2


 Data hiding - base class can decide to keep some data private so that it cannot be
altered by the derived class

Procedural and object oriented programming paradigms

JAVA PROGRAMMING Page 3


Java Programming- History of Java

The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc.

For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions etc. There are given the major points that describes the history of java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.

2) Originally designed for small, embedded systems in electronic appliances like set-
top boxes.

3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green
project.

Java Version History

There are many java versions that has been released. Current stable release of Java
is Java SE 8.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10.Java SE 8 (18th March, 2014)

JAVA PROGRAMMING Page 4


Features of Java

There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Compiled and Interpreted
10. High Performance
11. Multithreaded
12.Distributed

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment
Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

1. //This is single line comment


JAVA PROGRAMMING Page 5
Example:

public class CommentExample1 {


public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}

Output:

10

Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

/*
This
is
multi line
comment
*/

Example:

public class CommentExample2 {


public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}}

Output:

10

JAVA PROGRAMMING Page 6


Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you need
to use javadoc tool.

Syntax:

/**
This
is
documentation
comment
*/

Example:

/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}

Compile it by javac tool:

javac Calculator.java

Create Documentation API by javadoc tool:

javadoc Calculator.java

Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.

JAVA PROGRAMMING Page 7


Ways to read input from console in Java
In Java, there are four different ways for reading input from the user in the command line environment(console).
1.Using Buffered Reader Class

This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping the
System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read
input from the user in the command line.
 The input is buffered for efficient reading.
 The wrapping code is hard to remember.
Implementation:
 Java

// Java program to demonstra BufferedReader

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Test {

public static void main(String[] args)throws IOException

{ // Enter data using BufferReader

BufferedReader reader = new BufferedReader(

new InputStreamReader(System.in));

// Reading data using readLine

String name = reader.readLine();

// Printing the read line

System.out.println(name);

Input: rama
Output: rama
Note:

JAVA PROGRAMMING Page 8


To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we
use split().

2. Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse
primitive types and strings using regular expressions, however, it is also can be used to read input from the user
in the command line.
 Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
 Regular expressions can be used to find tokens.
 The reading methods are not synchronized

 Java

// Java program to demonstrate working of Scanner in Java

import java.util.Scanner;

class GetInputFromUser {

public static void main(String args[])

{ // Using Scanner for Getting Input from User

Scanner in = new Scanner(System.in);

String s = in.nextLine();

System.out.println("You entered string " + s);

int a = in.nextInt();

System.out.println("You entered integer " + a);

float b = in.nextFloat();

System.out.println("You entered float " + b);

// closing scanner

in.close();

Input:
Rama is a good boy

JAVA PROGRAMMING Page 9


12
3.4
Output:

You entered string Rama is a good boy


You entered integer 12
You entered float 3.4
3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In addition, it can be used
for reading password-like input without echoing the characters entered by the user; the format string syntax can
also be used (like System.out.printf()).

Advantages:

 Reading password without echoing the entered characters.


 Reading methods are synchronized.
 Format string syntax can be used.
 Does not work in non-interactive environment (such as in an IDE).

 Java

// Java program to demonstrate working of System.console()

// Note that this program does not work on IDEs as

// System.console() may require console

public class Sample {

public static void main(String[] args)

{ // Using Console to input data from user

String name = System.console().readLine();

System.out.println("You entered string " + name);

Input: god is great


Output:You entered string god is great

JAVA PROGRAMMING Page 10


4. Using Command line argument

Most used user input for competitive coding. The command-line arguments are stored in the String format. The
parseInt method of the Integer class converts string argument into Integer. Similarly, for float and others during
execution. The usage of args[] comes into existence in this input form. The passing of information takes place
during the program run. The command line is given to args[]. These programs have to be run on cmd.

Code: Java// Program to check for command line arguments

class Hello {

public static void main(String[] args)

{ // check if length of args arra is greater than 0

if (args.length > 0) {

System.out.println( "The command line arguments are:");

// iterating the args array and printingthe command line arguments

for (String val : args)

System.out.println(val);

else

System.out.println("No command line "+ "arguments found.");

Command Line Arguments:


javac Hello.java
java Hello Hello World
Output:

The command line arguments are:


Hello
World

JAVA PROGRAMMING Page 11


Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:

o Primitive data types


o Non-primitive data types

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Java Variable Example: Add Two Numbers


class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}

Output:20

JAVA PROGRAMMING Page 12


Variables and Data Types in Java
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.

There are two types of data types in java: primitive and non-primitive.

Types of Variable
There are three types of variables in java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.

3) Static variable

A variable that is declared as static is called static variable. It cannot be local.

We will have detailed learning of these variables in next chapters.

Example to understand the types of variables in java

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.

Syntax
modifier final dataType variableName = value; //global constant

modifier static final dataType variableName = value; //constant within a c

JAVA PROGRAMMING Page 13


Scope and Life Time of Variables
The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block.
The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refers to deallocating the memory that was allotted to the variables when
declaring it. We have written a few classes till now. You might have observed that not all
variables are the same. The ones declared in the body of a method were different from those
that were declared in the class itself. There are three types of variables: instance variables,
formal parameters or local variables and local variables.

Instance variables

Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have already seen about it earlier.
The lifetime of these variables is the same as the lifetime of the object to which it belongs.
Object once created do not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.

Argument variables

These are the variables that are defined in the header oaf constructor or a method. The scope
of these variables is the method or constructor in which they are defined. The lifetime is
limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.

Local variables

A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.

One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.

In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the block
itself.

JAVA PROGRAMMING Page 14


Operators in java

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

There are many types of operators in java which are given below:

o Unary Operator,
o Arithmetic Operator,
o shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Operators Hierarchy

JAVA PROGRAMMING Page 15


Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:

 Those that produce a value, i.e. the result of (1 + 1)


 Those that assign a variable, for example (v = 10)
 Those that have no result but might have a "side effect" because an expression can include
a wide range of elements such as method invocations or increment operators that modify
the state (i.e. memory) of a program.

Java Type casting and Type conversion

Widening or Automatic Type Conversion


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

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

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.



JAVA PROGRAMMING Page 16


Java Enum

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.

Java Enums can be thought of as classes that have fixed set of constants.

Simple example of java enum


class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {


for (Season s : Season.values())
System.out.println(s);
}}
Output:
WINTER
SPRING
SUMMER
FALL

Control Flow Statements

The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.

The “if” Statement


The “if” statement in Java works exactly like in most programming languages. With the help of
“if” you can choose to execute a specific block of code when a predefined condition is met. The
structure of the “if” statement in Java looks like this:

if (condition) {
// execute this code
}

JAVA PROGRAMMING Page 17


The condition is Boolean. Boolean means it may be true or false. For example you may put a
mathematical equation as condition. Look at this full example:

Classes and Objects in Java


Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities.

Class

A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods
that are common to all objects of one type. In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for details).
2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state of the class and its objects, and
methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications such as nested classes, anonymous classes, lambda
expressions.

Object

It is a basic unit of Object-Oriented Programming and represents the real life entities. A typical Java program creates many
objects, which as you know, interact by invoking methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other objects.
Example of an object: dog

JAVA PROGRAMMING Page 18


Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”,
“square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior
of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of
instances.
Example:

As we declare variables like (type name;). This notifies the compiler that we will use name to refer to data whose type is type.
With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference
variable, type must be strictly a concrete class name. In general, we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and
assigned to it. Simply declaring a reference variable does not create an object.

Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new
operator also invokes the class constructor.

Java

// Class Declaration

JAVA PROGRAMMING Page 19


public class Dog{

// Instance Variables

String name;

String breed;

int age;

String color;

// Constructor Declaration of Class

public Dog(String name, String breed,

int age, String color)

this.name = name;

this.breed = breed;

this.age = age;

this.color = color;

// method 1

public String getName()

return name;

// method 2

public String getBreed()

return breed;

JAVA PROGRAMMING Page 20


// method 3

public int getAge()

return age;

// method 4

public String getColor()

return color;

@Override

public String toString()

return("Hi my name is "+ this.getName()+

".\nMy breed,age and color are " +

this.getBreed()+"," + this.getAge()+

","+ this.getColor());

public static void main(String[] args)

Dog tuffy = new Dog("tuffy","papillon", 5, "white");

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

}
Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
JAVA PROGRAMMING Page 21
 This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the
class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the
arguments. The constructor in the Dog class takes four arguments. The following statement provides
“tuffy”,”papillon”,5,”white” as values for those arguments:
Dog tuffy = new Dog("tuffy","papillon",5, "white");
 The result of executing this statement can be illustrated as :

Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically
provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-
argument constructor (as it contain only one statement i.e super();), or the Object class constructor if the class has no other
parent (as Object class is parent of all classes either directly or indirectly).

Ways to create object of a class

There are four ways to create objects in java.Strictly speaking there is only one way(by using new keyword),and the rest
internally use new keyword.
 Using new keyword: It is the most common and general way to create object in java. Example:
// creating object of class Test
Test t = new Test();
 Using Class.forName(String className) method: There is a pre-defined class in java.lang package with name Class. The
forName(String className) method returns the Class object associated with the class with the given string name.We have
to give the fully qualified name for a class. On calling new Instance() method on this Class object returns new instance of
the class with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
 Using clone() method: clone() method is present in Object class. It creates and returns a copy of the object.

// creating object of class Test


Test t1 = new Test();

// creating clone of above object


Test t2 = (Test)t1.clone();
 Deserialization: De-serialization is technique of reading an object from the saved state in a file. Refer Serialization/De-
Serialization in java

JAVA PROGRAMMING Page 22


FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)

 In real-time, we need different objects of a class in different methods. Creating a number of references for storing them is
not a good practice and therefore we declare a static reference variable and use it whenever required. In this case, wastage
of memory is less. The objects that are not referenced anymore will be destroyed by Garbage Collector of java. Example:

Test test = new Test();


test = new Test();
 In inheritance system, we use parent class reference variable to store a sub-class object. In this case, we can switch into
different subclass objects using same referenced variable. Example:
class Animal {}

class Dog extends Animal {}


class Cat extends Animal {}

public class Test


{
// using Dog object
Animal obj = new Dog();

// using Cat object


obj = new Cat();
}

Creating a Stand-Alone Java Application


1. Write a main method that runs your program. You can write this method anywhere. In this
example, I'll write my main method in a class called Main that has no other methods. For
example:
2. public class Main
3. {
4. public static void main(String[] args)
5. {
6. Game.play();
7. }}
8. Make sure your code is compiled, and that you have tested it thoroughly.
9. If you're using Windows, you will need to set your path to include Java, if you haven't
done so already. This is a delicate operation. Open Explorer, and look inside
JAVA PROGRAMMING Page 23
C:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder, and
then open the bin folder. Select the complete path from the top of the Explorer window, and
press Ctrl-C to copy it.

Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select
properties. Click on the Advanced tab, and then click on the Environment variables button.
Look at the variables listed for all users, and click on the Path variable. Do not delete the
contents of this variable! Instead, edit the contents by moving the cursor to the right end,
entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go
ahead and save your changes. (If you have any Cmd windows open, you will need to close
them.)

10. If you're using Windows, go to the Start menu and type "cmd" to run a program that
brings up a command prompt window. If you're using a Mac or Linux machine, run the
Terminal program to bring up a command prompt.
11. In Windows, type dir at the command prompt to list the contents of the current directory.
On a Mac or Linux machine, type ls to do this.
12.
13. Now we want to change to the directory/folder that contains your compiled code. Look at
the listing of sub-directories within this directory, and identify which one contains your code.
Type cd followed by the name of that directory, to change to that directory. For example, to
change to a directory called Desktop, you would type:

cd Desktop

To change to the parent directory, type:

cd ..

Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains
your .class files.

14. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll need to
recompile your code from the command line, by typing:

javac -target 1.5 *.java

15. Now we'll create a single JAR file containing all of the files needed to run your program.

Examples
//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;
JAVA PROGRAMMING Page 24
//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);
}
}

/Java Program to demonstrate having the main method in


//another class
//Creating Student class.
class Student{
int id= 222;
String name=”Rao”;
}
//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);
System.out.println(s1.name);
}
}

Object and Class Example: Employee


Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {

JAVA PROGRAMMING Page 25


14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23. }
24. }

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0
Object and Class Example: Rectangle
There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java

1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. }
10. class TestRectangle1{
11. public static void main(String args[]){
12. Rectangle r1=new Rectangle();
13. Rectangle r2=new Rectangle();
14. r1.insert(11,5);
15. r2.insert(3,15);
16. r1.calculateArea();
17. r2.calculateArea();
18. }
19. }

Output:

55
45

JAVA PROGRAMMING Page 26


What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
o //Java Program to demonstrate the working of a banking-system
o //where we deposit and withdraw amount from our account.
o //Creating an Account class which has deposit() and withdraw() methods
o class Account{
o int acc_no;
o String name;
o float amount;
o //Method to initialize object
o void insert(int a,String n,float amt){
o acc_no=a;
o name=n;
o amount=amt;
o }
o //deposit method
o void deposit(float amt){
o amount=amount+amt;
o System.out.println(amt+" deposited");
o }
o //withdraw method
o void withdraw(float amt){
o if(amount<amt){
o System.out.println("Insufficient Balance");
o }else{
o amount=amount-amt;
o System.out.println(amt+" withdrawn");
o }
o }
o //method to check the balance of the account
o void checkBalance(){System.out.println("Balance is: "+amount);}
o //method to display the values of an object
o void display(){System.out.println(acc_no+" "+name+" "+amount);}
o }
o //Creating a test class to deposit and withdraw amount
o class TestAccount{

JAVA PROGRAMMING Page 27


o public static void main(String[] args){
o Account a1=new Account();
o a1.insert(832345,"Ankit",1000);
o a1.display();
o a1.checkBalance();
o a1.deposit(40000);
o a1.checkBalance();
o a1.withdraw(15000);
o a1.checkBalance();
o }}
Test it Now

Output:

832345 Ankit 1000.0


Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

Constructors in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value?
4. Copying the values of one object into another
5. Does constructor perform other tasks instead of the initialization

In Java, 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.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default
constructor by default.

38.2M
807
C++ vs Java
Next
Stay

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a
constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

JAVA PROGRAMMING Page 28


Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: 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

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
1. //Java Program to create and call a default constructor
2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}

JAVA PROGRAMMING Page 29


5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }

Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.

Declaring Array Variables:


To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType
arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.

Example:
The following code snippets are examples of this syntax:

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays:
You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];


The above statement does two things:

JAVA PROGRAMMING Page 30


 It creates an array using new dataType[arraySize];

 It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];


Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};


The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.

Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:

double[] myList = new double[10];


Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.

JAVA PROGRAMMING Page 31


Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.

Example:
Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray


{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

JAVA PROGRAMMING Page 32


This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}}}

// Sort a numeric array and a string array


import java.util.Arrays;
public class Exercise1 {
public static void main(String[] args){

int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};

String[] my_array2 = {
"Java",

"Python",
"PHP",
"C#",
"C Programming",
"C++"
};
System.out.println("Original numeric array : "+Arrays.toString(my_array1));
Arrays.sort(my_array1);
System.out.println("Sorted numeric array : "+Arrays.toString(my_array1));

System.out.println("Original string array : "+Arrays.toString(my_array2));


Arrays.sort(my_array2);
System.out.println("Sorted string array : "+Arrays.toString(my_array2));
}
}
JAVA PROGRAMMING Page 33
Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254,
1472, 2365, 1456, 2165, 1457, 2456]
Sorted numeric array : [1254, 1456, 1456, 1457, 1458, 1472, 1789, 1899,
2013, 2035, 2165, 2365, 2456, 2458]
Original string array : [Java, Python, PHP, C#, C Programming, C++]
Sorted string array : [C Programming, C#, C++, Java, PHP, Python]

Sum values of an array


public class Exercise2 {
public static void main(String[] args) {
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;

for (int i : my_array)


sum += i;
System.out.println("The sum is " + sum);
}
}

Multi dimentional arrays:


Example

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

int[][] arr = new int[10][20];


arr[0][0] = 1;

System.out.println("arr[0][0] = " + arr[0][0]);


}
}

Example 3

class GFG {

public static void main(String[] args)

int[][] arr = { { 1, 2 }, { 3, 4 } };

JAVA PROGRAMMING Page 34


for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

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

System.out.println();

Output:
1 2
3 4

Example 3

class GFG {

public static void main(String[] args)

int[][][] arr = { { { 1, 2 }, { 3, 4 } }, {
{ 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++)

for (int j = 0; j < 2; j++)

for (int z = 0; z < 2; z++)

System.out.println("arr[" + i + "][" + j +
"][" + z + "] = " + arr[i][j][z]);

JAVA PROGRAMMING Page 35


}}

Output:
arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8

Test if an array contains a specific value


public class Exercise5 {
public static boolean contains(int[] arr, int item) {
for (int n : arr) {
if (item == n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2265, 1457, 2456};
System.out.println(contains(my_array1, 2013));
System.out.println(contains(my_array1, 2015));
}
}

Jagged arrays

A jagged array is an array of arrays such that member arrays can be of different sizes, i.e.,
we can create a 2-D array but with a variable number of columns in each row. These types
of arrays are also known as Jagged arrays.
Pictorial representation of Jagged array in Memory:
JAVA PROGRAMMING Page 36
Declaration and Initialization of Jagged array :

Syntax: data_type array_name[][] = new data_type[n][]; //n: no. of rows


array_name[] = new data_type[n1] //n1= no. of columns in row-1
array_name[] = new data_type[n2] //n2= no. of columns in row-2
array_name[] = new data_type[n3] //n3= no. of columns in row-3
.
.
.
array_name[] = new data_type[nk] //nk=no. of columns in row-n

lternative, ways to Initialize a Jagged array :

int arr_name[][] = new int[][] {


new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};

OR

int[][] arr_name = {
new int[] {10, 20, 30 ,40},
JAVA PROGRAMMING Page 37
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};

OR

int[][] arr_name = {
{10, 20, 30 ,40},
{50, 60, 70, 80, 90, 100},
{110, 120}
};

Example 1// Program to demonstrate 2-D jagged array


in Java

class Main {

public static void main(String[] args)

// Declaring 2-D array with 2 rows

int arr[][] = new int[2][];

// Making the above array Jagged

// First row has 3 columns

arr[0] = new int[3];

// Second row has 2 columns

arr[1] = new int[2];

// Initializing array

int count = 0;

JAVA PROGRAMMING Page 38


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

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

arr[i][j] = count++;

// Displaying the values of 2D Jagged


array

System.out.println("Contents of 2D Jagged
Array");

for (int i = 0; i < arr.length; i++) {

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

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

System.out.println();

Output
Contents of 2D Jagged Array
0 1 2
3 4

Example 2

// Another Java program to demonstrate 2-D jagged

// array such that first row has 1 element, second

// row has two elements and so on.

class Main {

public static void main(String[] args)

JAVA PROGRAMMING Page 39


{ int r = 5;

// Declaring 2-D array with 5 rows

int arr[][] = new int[r][];

// Creating a 2D array such that first row

// has 1 element, second row has two

// elements and so on.

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

arr[i] = new int[i + 1];

// Initializing array

int count = 0;

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

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

arr[i][j] = count++;

// Displaying the values of 2D Jagged


array

System.out.println("Contents of 2D Jagged
Array");

for (int i = 0; i < arr.length; i++) {

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

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

System.out.println();

JAVA PROGRAMMING Page 40


Output
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14

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

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

ssame as:

1. String s="javatpoint";
2. Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
3. The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

CharSequence InterfaceThe CharSequence interface is used to represent sequence of characters.


It is implemented by String, StringBuffer and StringBuilder classes. It means, we can create
JAVA PROGRAMMING Page 41
string in java by using these 3 classes.

The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder
classes.
There are two ways to create String object:
1. By string literal
2. By new keyword

String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object
in heap (non pool).

Java String 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);
System.out.println(s3);
}}
java

JAVA PROGRAMMING Page 42


strings
example
Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
} }
Output:Sachin
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
} } Output:Sachin Tendulkar

Example1

import java.io.*;

import java.lang.*;

class Test {

public static void main(String[] args)

// Declare String without using


new operator

String s = "GeeksforGeeks";

// Prints the String.

System.out.println("String s = " +
s);

// Declare String using new


operator

String s1 = new

JAVA PROGRAMMING Page 43


String("GeeksforGeeks");

// Prints the String.

System.out.println("String s1 = "
+ s1);

Output:
String s = GeeksforGeeks
String s1 = GeeksforGeeks

Creating a String
 There are two ways to create a string in Java:
 String literal
String s = “GeeksforGeeks”;
 Using new keyword
String s = new String (“GeeksforGeeks”);
 StringBuffer:
StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents
fixed-length, immutable character sequences while StringBuffer represents growable and writable character
sequences.
Syntax:
StringBuffer s = new StringBuffer("GeeksforGeeks");
 StringBuilder:
The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java
creates an immutable sequence of characters, the StringBuilder class provides an alternate to String Class,
as it creates a mutable sequence of characters.
Syntax:
StringBuilder str = new StringBuilder();
str.append("GFG");
 StringTokenizer:
StringTokenizer class in Java is used to break a string into tokens.
Example:

JAVA PROGRAMMING Page 44


 A StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters
processed. A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.
StringJoiner:
StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings)
separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner
provides an easy way to do that without much code to write.
Syntax:
public StringJoiner(CharSequence delimiter)
Above we saw we can create string by String Literal.
For ex- // String s=”Welcome”;
Here the JVM checks the String Constant Pool. If the string does not exist, then a new string instance is created
and placed in a pool. If the string exists, then it will not create a new object. Rather, it will return the reference to
the same instance. The cache which stores these string instances is known as the String Constant pool or String
Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation)
space. But in JDK 7 it is moved to the main heap area.

String Methods
1. int length(): Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i): Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
1. String substring (int i): Return the substring from the i th index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
String concat( String str): Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGee
1. int indexOf (String s): Returns the index within the string of the first occurrence of the specified string.
JAVA PROGRAMMING Page 45
2. String s = ”Learn Share Learn”;
3. int output = s.indexOf(“Share”); // returns 6
4. int indexOf (String s, int i): Returns the index within the string of the first occurrence of the specified string,
starting at the specified index.
5. String s = ”Learn Share Learn”;
6. int output = s.indexOf("ea",3);// returns 13
7. Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the specified string.
8. String s = ”Learn Share Learn”;
9. int output = s.lastIndexOf("a"); // returns 14
10. boolean equals( Object otherObj): Compares this string to the specified object.
11. Boolean out = “Geeks”.equals(“Geeks”); // returns true
12. Boolean out = “Geeks”.equals(“geeks”); // returns false
13. boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case
considerations.
14. Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
15. int compareTo( String anotherString): Compares two string lexicographically.
16. int out = s1.compareTo(s2); // where s1 ans s2 are
17. // strings to be compared
18.
19. This returns difference s1-s2. If :
20. out < 0 // s1 comes before s2
21. out = 0 // s1 and s2 are equal.
22. out > 0 // s1 comes after s2.
23. int compareToIgnoreCase( String anotherString): Compares two string lexicographically, ignoring case
considerations.
24. int out = s1.compareToIgnoreCase(s2);
25. // where s1 ans s2 are
26. // strings to be compared
27.
28. This returns difference s1-s2. If :
29. out < 0 // s1 comes before s2
30. out = 0 // s1 and s2 are equal.
31. out > 0 // s1 comes after s2.
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).
32. String toLowerCase(): Converts all the characters in the String to lower case.
33. String word1 = “HeLLo”;
34. String word3 = word1.toLowerCase(); // returns “hello"
35. String toUpperCase(): Converts all the characters in the String to upper case.
36. String word1 = “HeLLo”;

JAVA PROGRAMMING Page 46


37. String word2 = word1.toUpperCase(); // returns “HELLO”
38. String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect
whitespaces in the middle.
39. String word1 = “ Learn Share Learn “;
40. String word2 = word1.trim(); // returns “Learn Share Learn”
41. String replace (char oldChar, char newChar): Returns new string by replacing all occurrences
of oldChar with newChar.
42. String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”

StringBuffer is a peer class of String that provides much of the functionality of strings. The
string represents fixed-length, immutable character sequences while StringBuffer
represents growable and writable character sequences. StringBuffer may have characters
and substrings inserted in the middle or appended to the end. It will automatically grow to
make room for such additions and often has more characters preallocated than are actually
needed, to allow room for growth.
Some Interesting Facts about the StringBuffer class
Do keep in the back of mi while applying so which are as follows:
 java.lang.StringBuffer extends (or inherits from) Object class.
 All Implemented Interfaces of StringBuffer class: Serializable, Appendable,
CharSequence.
 public final class StringBuffer extends Object implements Serializable, CharSequence,
Appendable.
 String buffers are safe for use by multiple threads. The methods can be synchronized
wherever necessary so that all the operations on any particular instance behave as if
they occur in some serial order.
 Whenever an operation occurs involving a source sequence (such as appending or
inserting from a source sequence) this class synchronizes only on the string buffer
performing the operation, not on the source.
 It inherits some of the methods from the Object class which such as clone(), equals(),
finalize(), getClass(), hashCode(), notifies(), notifyAll().
Remember: StringBuilder, J2SE 5 adds a new string class to Java’s already powerful string
handling capabilities. This new class is called StringBuilder. It is identical to StringBuffer
except for one important difference: it is not synchronized, which means that it is not thread-
safe. The advantage of StringBuilder is faster performance. However, in cases in which you
are using multithreading, you must use StringBuffer rather than StringBuilder.
Constructors of StringBuffer class
1. StringBuffer(): It reserves room for 16 characters without reallocation
StringBuffer s = new StringBuffer();
2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the
buffer.
StringBuffer s = new StringBuffer(20);
3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.
StringBuffer s = new StringBuffer("GeeksforGeeks");
JAVA PROGRAMMING Page 47
Methods of StringBuffer class
Methods Action Performed

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

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

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

charAt()

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

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

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

insert() Inserts text at the specified index position

length() Returns length of the string

reverse() Reverse the characters within a StringBuffer object

replace() Replace one set of characters with another set inside a StringBuffer object

The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates
an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it
creates a mutable sequence of characters. The function of StringBuilder is very much similar to the StringBuffer
class, as both of them provide an alternative to String Class by making a mutable sequence of characters.
However the StringBuilder class differs from the StringBuffer class on the basis of synchronization. The
StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class does. Therefore this
class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being
used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in
preference to StringBuffer as it will be faster under most implementations. Instances of StringBuilder are not safe
for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
Class Hierarchy:

java.lang.Object
↳ java.lang
↳ Class StringBuilder

JAVA PROGRAMMING Page 48


Syntax:

public final class StringBuilder


extends Object
implements Serializable, CharSequence
Constructors in Java StringBuilder:

 StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16 characters.

 StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial capacity
specified by the capacity argument.

 StringBuilder(CharSequence seq): Constructs a string builder that contains the same characters as the
specified CharSequence.

 StringBuilder(String str): Constructs a string builder initialized to the contents of the specified string.

Below is a sample program to illustrate StringBuilder in Java:

Java

// Java code to illustrate StringBuilder

import java.util.*;

import
java.util.concurrent.LinkedBlockingQueue;

public class GFG1 {

public static void main(String[] argv)

throws Exception

// create a StringBuilder object

// using StringBuilder()
constructor

StringBuilder str

= new StringBuilder();

JAVA PROGRAMMING Page 49


str.append("GFG");

// print string

System.out.println("String = "

+
str.toString());

// create a StringBuilder object

// using
StringBuilder(CharSequence) constructor

StringBuilder str1

= new
StringBuilder("AAAABBBCCCC");

// print string

System.out.println("String1 = "

+
str1.toString());

// create a StringBuilder object

// using StringBuilder(capacity)
constructor

StringBuilder str2

= new StringBuilder(10);

// print string

System.out.println("String2
capacity = "

+
str2.capacity());

// create a StringBuilder object

JAVA PROGRAMMING Page 50


// using StringBuilder(String)
constructor

StringBuilder str3

= new
StringBuilder(str1.toString());

// print string

System.out.println("String3 = "

+
str3.toString());

Output:
String = GFG
String1 = AAAABBBCCCC
String2 capacity = 10
String3 = AAAABBBCCCC

Methods in Java StringBuilder:

1. StringBuilder append(X x): This method appends the string representation of the X type argument to the
sequence.

2. StringBuilder appendCodePoint(int codePoint): This method appends the string representation of the
codePoint argument to this sequence.

3. int capacity(): This method returns the current capacity.

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

5. IntStream chars(): This method returns a stream of int zero-extending the char values from this sequence.

6. int codePointAt(int index): This method returns the character (Unicode code point) at the specified index.

7. int codePointBefore(int index): This method returns the character (Unicode code point) before the specified
index.

8. int codePointCount(int beginIndex, int endIndex): This method returns the number of Unicode code points
in the specified text range of this sequence.

9. IntStream codePoints(): This method returns a stream of code point values from this sequence.

10. StringBuilder delete(int start, int end): This method removes the characters in a substring of this sequence.

JAVA PROGRAMMING Page 51


11. StringBuilder deleteCharAt(int index): This method removes the char at the specified position in this
sequence.

12. void ensureCapacity(int minimumCapacity): This method ensures that the capacity is at least equal to the
specified minimum.

13. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): This method characters are copied from
this sequence into the destination character array dst.

14. int indexOf(): This method returns the index within this string of the first occurrence of the specified substring.

15. StringBuilder insert(int offset, boolean b): This method inserts the string representation of the
booalternatelean argument into this sequence.

16. StringBuilder insert(): This method inserts the string representation of the char argument into this sequence.

17. int lastIndexOf(): This method returns the index within this string of the last occurrence of the specified
substring.

18. int length(): This method returns the length (character count).

19. int offsetByCodePoints(int index, int codePointOffset): This method returns the index within this sequence
that is offset from the given index by codePointOffset code points.

20. StringBuilder replace(int start, int end, String str): This method replaces the characters in a substring of
this sequence with characters in the specified String.

21. StringBuilder reverse(): This method causes this character sequence to be replaced by the reverse of the
sequence.

22. void setCharAt(int index, char ch): In this method, the character at the specified index is set to ch.

23. void setLength(int newLength): This method sets the length of the character sequence.

24. CharSequence subSequence(int start, int end): This method returns a new character sequence that is a
subsequence of this sequence.

25. String substring(): This method returns a new String that contains a subsequence of characters currently
contained in this character sequence.

26. String toString(): This method returns a string representing the data in this sequence.

27. void trimToSize(): This method attempts to reduce storage used for the character sequence.

Write a Java program to reverse a string using recursion

import java.util.*;
class Main {
void reverseString(String str1) {
if ((str1 == null) || (str1.length() <= 1))
System.out.println(str1);
JAVA PROGRAMMING Page 52
else {
System.out.print(str1.charAt(str1.length() - 1));
reverseString(str1.substring(0, str1.length() - 1));
}
}
public static void main(String[] args) {
String str1 = "The quick brown fox jumps";
System.out.println("The given string is: " + str1);
System.out.println("The string in reverse order is:");
Main obj = new Main();
obj.reverseString(str1);
}

Inheritance in Java

Java Console Class

The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.

If you read password using Console class, it will not be displayed to the user.

The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.

Let's see a simple example to read text from console.

1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console Example

import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n); } }
JAVA PROGRAMMING Page 53
Output

Enter your name: Nakul Jain


Welcome Nakul Jain

Constructors

Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}}
Output: Bike is created

Example of parameterized constructor

JAVA PROGRAMMING Page 54


In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id;
String name;

Student4(int i,String n){


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

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}

Output:

111 Karan
222 Aryan

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();

JAVA PROGRAMMING Page 55


}}

Output:

111 Karan 0
222 Aryan 25
Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of 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.
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 PROGRAMMING Page 56


Java - Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.

Creating Method
Considering the following example to explain the syntax of a method −

Syntax

public static int methodName(int a, int b) {


// body
}
Here,

 public static − modifier

 int − return type

 methodName − name of the method

 a, b − formal parameters

 int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in the
following syntax −

Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}
The syntax shown above includes −

 modifier − It defines the access type of the method and it is optional to use.

 returnType − Method may return a value.

 nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.

JAVA PROGRAMMING Page 57


 Parameter List − The list of parameters, it is the type, order, and number of parameters
of a method. These are optional, method may contain zero parameters.

 method body − The method body defines what the method does with the statements.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the
calling method.

Example of call by value in java


In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}
Output:before change 50
after change 50

In Java, parameters are always passed by value. For example, following program prints
i = 10, j = 20.
// Test.java
class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);

JAVA PROGRAMMING Page 58


}
}

Static Fields and Methods

The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

Java static variable

If you declare any variable as static, it is known static variable.

o The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.

o The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Example of static variable


//Program of static variable
class Student8{
int rollno;

JAVA PROGRAMMING Page 59


String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}}
Output:111 Karan ITS
222 Aryan ITS

Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of a class.


o A static method can be invoked without the need for creating an instance of a class.
o static method can access static data member and can change the value of it.

Example of static method


//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;

JAVA PROGRAMMING Page 60


}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Java static block

o Is used to initialize the static data member.


o It is executed before main method at the time of class loading.

Example of static block


class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}}
Output: static block is invoked
Hello main

Access Control

Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.

There are 4 types of java access modifiers:

JAVA PROGRAMMING Page 61


1. private
2. default
3. protected
4. public

private access modifier


The private access modifier is accessible only within class.

Simple example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");} }
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}}

2) default access modifier


If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from outside
the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

JAVA PROGRAMMING Page 62


class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error } }

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.

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

4) public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

JAVA PROGRAMMING Page 63


Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}}
Output:Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

this keyword in java

Usage of java this keyword

Here is given the 6 usage of java this keyword.

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


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
JAVA PROGRAMMING Page 64
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:
111 ankit 5000
112 sumit 6000

Difference between constructor and method in java

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.

Constructor name must be same as the class name. Method name may or may not be

JAVA PROGRAMMING Page 65


same as class name.

There are many differences between constructors and methods. They are given belo

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:

JAVA PROGRAMMING Page 66


111 Karan 0
222 Aryan 25

Method Overloading in java

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling
methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:

22
33

Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

JAVA PROGRAMMING Page 67


Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.

Java Recursion Example 1: Factorial Number

public class RecursionExample3 {


static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
} }
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}}

Output:

Factorial of 5 is: 120

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.

gc() method

JAVA PROGRAMMING Page 68


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

public static void gc(){}

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();
}}
object is garbage collected
object is garbage collected

JAVA PROGRAMMING Page 69


Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}}

Programer salary is:40000.0

JAVA PROGRAMMING Page 70


Bonus of programmer is:10000

Types of inheritance in java

Single Inheritance Example


File: TestInheritance.java

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


File: TestInheritance2.java

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{

JAVA PROGRAMMING Page 71


public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


File: TestInheritance3.java

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{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

JAVA PROGRAMMING Page 72


Member access and Inheritance

A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.

super keyword in java

The super keyword in java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

super is used to refer immediate parent class instance variable.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();

JAVA PROGRAMMING Page 73


d.printColor();
}}

Output:

black
white
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Test it Now

Output:

animal is created
dog is created

Final Keyword in Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank
JAVA PROGRAMMING Page 74
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.

34M
670
HTML Tutorial
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){

JAVA PROGRAMMING Page 75


9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:

1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.
JAVA PROGRAMMING Page 76
If you want to create a variable that is initialized at the time of creating object and once initialized
may not be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output: 70

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.

Learn more

volume is gedempt
Example of static blank final variable
JAVA PROGRAMMING Page 77
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
Output: Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.

Object class in Java

The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:

JAVA PROGRAMMING Page 78


1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.

JAVA PROGRAMMING Page 79


Usage of Java Method Overriding
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example of method overriding


Class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}

Output:Bike is running safely

1. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}

Output:
SBI Rate of Interest: 8

JAVA PROGRAMMING Page 80


ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Abstract class in Java

A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.

Example abstract class


1. abstract class A{}

abstract method
1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


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();
}
1. }
running safely..
Java Inner Classes
Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }}

JAVA PROGRAMMING Page 81


Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

Forms of inheritance-specialization, benefits of inheritance,


costs of inheritance.
In contrast to generalization, specialization means creating new subclasses from an existing class. ... If it turns out
that certain attributes, associations, or methods only apply to some of the objects of the class, a subclass can be created.
the class Freight (1) has the attribute Degree of Hazardousness (2), which is needed only for cargo, but not for
passenger luggage. Additionally (not visible in Figure 4.28), only passenger luggage has a connection to a coupon.
Obviously, here two similar but different domain concepts are combined into one class. Through specialization the two
special cases of freights are formed: Piece of Cargo (3) and Piece of Luggage (4). The attribute Degree of
Hazardousness (5) is placed where it belongs—in Piece of Cargo. The attributes of the class Freight (1) also apply to the
two subclasses Piece of Cargo (3) and Piece of Luggage (4):

JAVA PROGRAMMING Page 82


Example of specialization

Inheritance helps in code reuse. The child class may use the code defined in the parent class without re-writing it. ... An
inheritance leads to less development and maintenance costs. In inheritance base class can decide to keep some
data private so that it cannot be altered by the derived class.

import java.io.*;
import java.util.*;

class Append1 {

public static void main(String[] args)


{
Scanner in=new Scanner(System.in);
System.out.print("Enter string");
StringBuffer s = new StringBuffer(in.nextLine());

System.out.print("Enter string to be append");


String s1 = new String();
s1=in.nextLine();
s.append(s1);
System.out.println(s);

}
}
JAVA PROGRAMMING Page 83
import java.util.*;
public class Factorial {

public static void main(String[] args) {


Scanner in=new Scanner(System.in);
System.out.print("enter a number");
int num = in.nextInt();
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}

JAVA PROGRAMMING Page 84

You might also like