Core JAVA 1 - Content
Core JAVA 1 - Content
PRINCIPLES
There were five primary goals in the creation of the Java language:
PLATFORM INDEPENDENT
One characteristic of Java is portability, which means that computer programs written in the Java
language must run similarly on any hardware / operating-system platform. This is achieved by
compiling the Java language code to an intermediate representation called Java byte code,
instead of directly to platform-specific machine code. Java byte code instructions are analogous
to machine code, but they are intended to be interpreted by a virtual machine (VM) written
specifically for the host hardware.
End-users commonly use a Java Runtime Environment (JRE) installed on their own machine for
standalone Java applications, or in a Web browser for Java applets. Standardized libraries
provide a generic way to access host-specific features such as graphics, threading,
and networking.
A major benefit of using byte code is porting. However, the overhead of interpretation means
that interpreted programs almost always run more slowly than programs compiled to native
executables would. Just-in-Time (JIT) compilers were introduced from an early stage that
compiles byte codes to machine code during runtime.
* Java Platform Enterprise Edition (Java EE) — Targeting large distributed enterprise or
Internet environments.
JDK
The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java
EE or Java ME platforms released by Oracle Corporation in the form of a binary product aimed
at Java developers on Solaris, Linux, Mac OS X or Windows. Since the introduction
of Java platform, it has been by far the most widely used Software Development Kit (SDK). On
17 November 2006, Sun announced that it would be released under the GNU General Public
License (GPL), thus making it free software.
The JDK has as its primary components a collection of programming tools, including:
appletviewer – This tool can be used to run and debug Java applets without a web browser
java – The loader for Java applications. This tool is an interpreter and can interpret the class
files generated by the javac compiler.
javac – The Java compiler, which converts source code into Java byte code
javadoc – The documentation generator, which automatically generates documentation
from source code comments
jar – The archiver, which packages related class libraries into a single JAR file. This tool
also helps manage JAR files.
jdb – The debugger
JRE
The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java
Development Kit (JDK), a set of programming tools for developing Java applications. The Java
Runtime Environment provides the minimum requirements for executing a Java application; it
consists of the Java Virtual Machine (JVM), core classes, and supporting files.
JVM
A Java virtual machine (JVM) is a virtual machine that can execute Java byte code. It is the code
execution component of the Java platform. According to SUN Microsystems, there are over 5.5
billion JVM-enabled devices.
Program:
class Message
{
public static void main(String[] args)
{
System.out.println("\n HELLO WORLD");
}
}
Output:
HELLO WORLD
Practical - 2
Aim: Write a program in JAVA to initialize 3 variables, compute their sum and display the
result.
Tokens: The smallest unit of a JAVA program is called a Token. Tokens are indivisible. Tokens
include Keywords, Identifiers, Literals, Operators, Separators and Comments.
Keywords: These are pre-defined words or reserved words; each keyword has a specific
meaning and a specific purpose. They are always written in lower case. They can only be used
for the purpose, for which they are already defined; we can‟t redefine their purpose, nor can they
be used as names of identifiers or variables.
Some common keywords of JAVA include boolean, class, catch, extends, final, finally,
implements, import, interface, new, package, private, protected, public, return, static, super,
synchronized, this, throw, throws, assert, etc.
Operators: They are the special symbols used to perform operations. JAVA support Arithmetic
operators (+, -, *, / and %), Assignment operators (=, +=, -=, *=, /= and %=), Relational
operators (<, <=, >, >=, == and !=), Unary operators (-, ++ and --), Logical operators (&&, || and
!), Bitwise operators (&, |, ^ and ~), Shift operators (<< and >>) and Ternary operator (condition
? TRUE Statement : FALSE Statement;).
class SimpleSum
{
public static void main(String[] args)
{
int a = 5, b = 7, c = 8, s = 0;
s = a + b + c;
System.out.println(“Sum of 3 Numbers is : “ + s);
}
}
Output:
Sum of 3 Numbers is : 20
Practical - 3
Aim: Write a program in JAVA to compute average of 3 numbers and perform necessary type
casting.
Type Casting: It is a technique that converts a data type to another, both automatically and
manually. The automatic conversion is done implicitly by the Compiler; the manual conversion
is done by the Programmer. The type casting done by the Compiler is called Implicit Type
Casting; the type casting done by the programmer is called Explicit Type Casting.
Type Casting is further categorized as Narrowing and Widening. The technique of converting a
higher data type into a lower data type is called Narrowing. Alternatively, the technique of
converting a lower data type into a higher data type is called Widening.
Command Line Arguments: It represents the input or data passed at the time of running a
JAVA program. The data passed from the Console is received by the JAVA program as input
through „args[]‟ of „main()‟.
Program:
class TypeCastCommandLine
{
public static void main(String[] args)
{
int a = 0, b = 0, c = 0, s = 0;
double avg = 0.0;
s = a + b + c;
avg = s / 3.0;
// Type Casting – Taking DOUBLE Denominator to get DOUBLE Result
System.out.println(“Average of Three Numbers is : ” + avg);
}
}
Output:
Location_Of_JAVA_File>javac TypeCastCommandLine.java
Location_Of_JAVA_File>java TypeCastCommandLine 5 7 8
Scanner: There are three main components of a program, namely Input, Process and Output. A
Program is a way to interact with Computer; it represents a task to perform. Scanner class is a
pre-defined class in JAVA, used to take Input from User. Scanner class is defined in the „util‟
package.
Built-In Library of JAVA is available in form of Packages; a Package comprise of Classes and
Sub-Packages. A Class contains multiple Methods used to carry out the specified operations. To
use a Class, first we need to call or import the Package in which it is specified. A Built-In
Package of JAVA can be called / imported in the Program, as:
import java.Package_Name.*;
import java.util.*;
import java.Package_Name.Class_Name;
// For using the specified Class of the specified Package in our Program
import java.util.Scanner;
To use a Class, first we need to create its Object and then carry out the operations by calling the
Methods of the Class using Member Selection Operator (.), as:
scan.nextInt();
Program:
import java.util.*;
class ScannerExample
{
public static void main(String[] args)
{
int a = 0, b = 0, c = 0, s = 0;
double avg = 0.0;
Scanner scan = new Scanner(System.in);
s = a + b + c;
avg = s / 3.0;
System.out.println("Average of Three Numbers is : " + avg);
}
}
Output:
There are two common ways of implementing Branching Logic in a Program, namely IF ELSE
Statements and SWITCH CASE Statement. IF ELSE Statements are further categorized into 4
types, as Simple IF, IF ELSE, IF ELSE Ladder and Nested Conditions.
Simple IF: It is used when we need to handle only one state of condition in the program, i. e.,
only TRUE state. Typically, the condition to test is associated with IF. The statements specified
in the IF Block will execute, if the condition associated with IF is TRUE; otherwise, the
statements will not execute. The syntax to implement Simple IF is:
IF ELSE: It is typically implemented, when we need to handle both the outcomes of the
condition, i. e., TRUE as well as FALSE. It comprises two blocks, namely IF Block with which
the condition is associated and an ELSE Block. The statements of IF Block will execute, when
the condition associated is TRUE; if the condition associated with IF is FALSE, the statements
of ELSE Block will execute. In every case, either statements of IF Block will execute or
statements of ELSE Block will execute, but not both. The syntax to implement IF ELSE is:
else if(condition_2) {
Statements 2; // Execute when condition_1 is FALSE and condition_2 is TRUE }
else { Statements 4; // Execute when all conditions mentioned above are FALSE }
Nested Condition: Nesting in programming means implementing the same programming
concept in that concept, i. e., condition inside another condition is called Nested Condition, loop
inside another loop is called Nested Loop, method inside another method is called Nested
Method, class inside another class is called Nested Class, etc.
If a condition is specified another condition, i. e., if another condition is tested as part of the
outcome of a condition, then it is called Nested Condition. It is implemented using Nested IF
ELSE as:
if(external_condition) {
if(internal_condition_1) {
Statements 1; // Execute when both external_condition and internal_condition_1 are TRUE
}
else {
Statements 2;
// Execute when external_condition is TRUE and internal_condition_1 is FALSE
} }
else {
if(internal_condition_2) {
Statements 3;
// Execute when external_condition is FALSE and internal_condition_2 is TRUE
}
else {
Statements 4; // Execute when both external_condition and internal_condition_2 are FALSE
} }
Program:
import java.util.Scanner;
class EvenOdd01 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
System.out.println("Enter a Positive Integer (>= 0) : ");
num = scan.nextInt();
if(num == 0)
System.out.println("Number is 0 !");
else if(num == 1)
System.out.println("Number is 1 !");
else if((num % 2) == 0)
System.out.println("Number is Even !");
else
System.out.println("Number is Odd !");
}
}
Output:
Run 1
Enter a Positive Integer (>= 0) : 5
Number is Odd !
Run 2
Enter a Positive Integer (>= 0) : 8
Number is Even !
Run 3
Enter a Positive Integer (>= 0) : 1
Number is 1 !
Run 4
Enter a Positive Integer (>= 0) : 0
Number is 0 !
Practical - 6
Aim: Write a program in JAVA to implement simple arithmetic calculator using SWITCH
CASE.
There is a drawback with SWITCH CASE that in case, if a CASE Block is executed after its
condition is TRUE, all CASE Blocks specified after it will also execute. This drawback can be
overcomed by using a BREAK Statement at the end of each CASE Block. BREAK terminates
the execution of the current Block (SWITCH or Loop). The execution of SWITCH CASE
depends on the “choice”, passed as an argument in the SWITCH Block. The syntax to implement
SWITCH CASE is:
switch(choice) {
case 1: { Statements 1; break; } // Execute when “choice” passed is 1
case 2: { Statements 2; break; } // Execute when “choice” passed is 2
case 3: { Statements 3; break; } // Execute when “choice” passed is 3
default: { Statements 4; break; }
// Execute when “choice” is any number except 1, 2 or 3
}
Program:
import java.util.*;
class SwitchCaseCalc {
public static void main(String[] args) {
int x = 0, y = 0, c = 0;
Scanner scan = new Scanner(System.in);
switch(c) {
case 1: { int r = x + y; System.out.println("SUM is : " + r); break; }
default:
System.out.println("INVALID CHOICE \n PLEASE SELECT A VALID OPERATION");
}
} }
Output:
Run 1
Enter 2 Numbers : 12 7
1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 1
SUM is : 19
Run 2
Enter 2 Numbers : 12 5
1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 2
DIFFERENCE is : 7
Run 3
Enter 2 Numbers : 7 5
1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 3
PRODUCT is : 35
Run 4
Enter 2 Numbers : 25 7
1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 4
DIVISION is : 3.5714285
Run 5
Enter 2 Numbers : 97 11
1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 5
REMAINDER is : 9
Run 6
Enter 2 Numbers : 25 5
1 for ADD 2 for SUB 3 for MUL 4 for DIV 5 for MOD
Enter Your Choice : 6
INVALID CHOICE
PLEASE SELECT A VALID OPERATION
Practical - 7
Aim: Write a program in JAVA to take a number as Input from User and print its Table.
Iteration: Iteration in programming means to perform same operation repeatedly, one after
another, at a specific point in a program. Iteration is a synonym for repetition in programming. It
is mainly implemented using Loops or Looping structures.
Loops are broadly categorized into 2 types, as Entry Controlled Loops and Exit Controlled
Loops. The looping structure in which first, the condition is checked; if TRUE, statements are
executed; otherwise not, are called Entry Controlled Loops. The statements will never execute, if
condition is FALSE. WHILE Loop and FOR Loop are examples of Entry Controlled Loops.
The loops in which first the statements are executed and then the condition is checked are called
Exit Controlled Loops. In this, the statements will execute once, even when the condition is
FALSE. DO WHILE Loop falls in this category of Loops.
Break: It is a statement used to terminate a Loop or any other programming structure; before
reaching the boundary, based on another condition.
Continue: It is a statement used to skip some iterations of loop, based on some conditions.
WHILE Loop
initiailize loop_var;
FOR Loop
DO WHILE
initialize loop_var;
BREAK
CONTINUE
initialize loop_var;
while(condition) {
if(continue_condition) continue;
import java.util.Scanner;
class Table {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
System.out.println("Enter a Positive Integer (> 0) : ");
num = scan.nextInt();
} }
Output:
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
Practical - 8
Aim: Write a program in JAVA to display the „*‟ Pyramid of order „n‟ shown below:
*
* *
* * *
* * * *
* * * * *
Nested Loop: A loop implemented inside another loop is called a Nested Loop. It is mainly used
to draw 2 D structures, patterns, etc or to work with 2 D arrays, usually Matrices. The syntax for
Nested Loop is:
If the external loop will execute „n‟ times and internal loop will execute „m‟ times; then
„Statements‟ will execute „n * m‟ times for a Nested Loop. For example, if external loop
executes 5 times and internal loop executes 10 times; then in total, there will be „5 * 10 = 50‟
iterations of this Nested Loop.
Program:
import java.util.*;
class NestedLoopPyramid
{
public static void main(String[] args)
{
int n = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the Size of * Pyramid to display : ");
n = s.nextInt();
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if((i + j) >= (n - 1))
System.out.print("*");
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
}
Output:
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
Practical - 9
Aim: Write a program in JAVA to initialize a 1 D Array through User Input, compute sum and
display the result.
Compared to C++, where an Array must have static / constant size, unless Pointers are used for
dynamic memory allocation, the standard implementation of Array in JAVA allows you to keep
size of Array either constant or variable; the only concern is that the variable representing the
size of Array must be initialized before declaring the Array.
Elements are referred using Indices in an Array; by default, the index of first element is 0, the
index of second element is 1, index of third element is 2 and so on. An Array is a linear data
structure that allows random access to all elements using index.
The common operations to perform on an Array include insertion, deletion, update, traversing,
search and sort. Insertion and Deletion in Array can be performed at beginning, end or at any
random position / index. Arrays are mainly classified as 1 Dimensional Arrays and Multi
Dimensional Arrays.
1 D Array: The simplest implementation of Arrays is 1 D Array. In this, each element is referred
using a single index. A 1 D Array is declared as:
To declare an Array, we must specify the Data Type and Size, as represented in the above
statement. Here, „num‟ is an Array of „int‟ type having size of „10‟. „[]‟ is used to represent an
Array and each element of the Array is referred as „num[x]‟, where „x‟ is the index of the Array,
whose element is to be accessed.
A variable sized Array in JAVA is declared as:
Here, „num‟ is an Array comprising „Size‟ number of Integers; however, to pass „Size‟, we must
initialize it before specifying it in the Array.
Program:
import java.util.*;
class ArrayExample {
public static void main(String[] args) {
int n = 0; Scanner sc = new Scanner(System.in);
sum = num[0];
for(i = 1; i < n; i++) { sum = sum + num[i]; }
Output:
In the above example, a 2 D Array „m‟ is declared. Consider, „m‟ as a Matrix having number of
rows, equal to Size1, i. e., 5 and number of columns as Size2, i. e., 3. Depending on the
requirement, both sizes can be same or different.
For 2 D Array also, the memory allocation must be contiguous. If the sizes of 2 D Array are
„Size1‟ and „Size2‟, then it will have a total of „Size1 * Size2‟ elements. For example, in „m‟,
there will be „5 * 3 = 15‟ elements.
Program:
import java.util.Scanner;
class MatrixOp {
public static void main(String[] args) {
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] s = new int[3][3];
int[][] p = new int[3][3];
System.out.println(); }
System.out.println(); }
System.out.println(); }
System.out.println(); }
} }
Output:
The benefits of OOP over Procedure Oriented Programming (POP) include Reusability,
Extensibility, Modifiability, etc. POP focuses on Procedures and Data is globally accessible; in
contrast, OOP focuses on Objects and Data. In OOP, access to Data is restricted; this is possible
by using the Access Specifiers. POP follows Top Down approach, while OOP follows Bottom
Up approach. Modularity using Classes forms the basis of Bottom Up approach in OOP.
The common principles of OOP include Class, Objects, Abstraction, Encapsulation, Data Hiding,
Dynamic Binding, Polymorphism, Inheritance, Message Passing or Object Interaction. The
common programming languages that follow OOP paradigm include C++, JAVA, PYTHON,
C#, Visual Basic, R, Kotlin, Swift, LISP, etc.
Class: A Class is a blue-print that specifies the creation of Objects. It is a logical entity that can
be considered as collection of Objects. “class” Keyword is used to specify a Class in JAVA. It
comprises of Data Members (Attributes) and Member Methods (Code); all Objects of this Class
have a specific value for Attributes and can invoke all associated Methods.
The access to Class Members can be restricted using Access Specifiers. JAVA supports 4 Access
Specifiers, namely Private, Protected, Package and Public. By default, the access is Package.
Object: It is a real world or run time entity. An Object is an instance of a Class. It consumes
Memory Space; in contrast, Class doesn‟t consume any Memory Space. Objects can interact with
each other. An entity that has State and Behavior is an Object.
Encapsulation: Binding of Data and Code together as a single unit is called Encapsulation.
Class promotes Encapsulation, as it contains Data (Attributes) and Methods (Code). It is the most
striking feature of Class.
Abstraction: The principle that allows showcasing only necessary functionality and hides the
implementation details is called Abstraction. Class implements Abstraction and encapsulates all
essential properties of the Object to be created. Objects perform the operations; however they do
not specify the implementation details.
Data Hiding: Due to Encapsulation, the Data Members of the class area accessible only to the
Member Methods defined in the Class. Normally, Member Methods are declared as Public, so
that they are accessible from outside the Class, but the Data Members are declared Private, so
that they are accessible only to Methods of the same Class. The Data Members of the Class are
not accessible to the outside world, due to restrictions imposed on them using Access Specifiers.
This concept is known as Data Hiding or Information Hiding, as Data Members are local to
Class.
Dynamic Binding: Binding refers to the Linking of a Procedure Call to the Code to be executed,
in response to that Call. Mostly, the Binding is Static, performed at Compile Time. However,
OOP supports Dynamic Binding also. Dynamic Binding means that the Code associated with a
given Procedure Call is unknown, until the time of the Call at Run Time. Dynamic Binding is
also known as Run Time Binding.
Polymorphism: The word „Polymorphism‟ is a Greek Word that means “Ability to take more
than one Form”. Objects are Polymorphic in nature; they behave differently in different
situations, just as Humans do. An operation may exhibit different behavior at different instances,
depending on the type of data used on that instance. In JAVA, Polymorphism is achieved using
Method Overloading and Method Overriding.
Inheritance: It is the most striking feature of OOP that promotes Reusability of Code. It is the
process in which Object of a Class acquire properties of Object of another Class. Inheritance
creates a hierarchical relationship among Classes. It is a process in which a Derived Class
exhibits the characteristics or properties of Base Class.
The Class whose properties are being reused or derived is called Base Class or Parent Class or
Super Class. The Class that reuses the properties of Base Class is called Derived Class or Sub
Class or Child Class. The Child Class inherits the properties of the Base Class.
Object Interaction: An Object Oriented Program consists of a set of Objects that communicate
with each other. Communication among Objects occur by sending and receiving Messages; just
as People pass Messages with one another using some Message Passing mechanism.
Traditionally, Method Calls are used to achieve communication among Objects, where Data to
share is passed as Arguments in the Method Call.
class CLASS_NAME {
private DATA_MEMBERS;
-----
public MEMBER_METHODS() {
Method Definition;
}
-----
}
Program:
import java.util.Scanner;
class ClassObject
{
private String name;
private int age;
private float cgpa;
Scanner scan;
Output:
By changing the number of Arguments: All overloaded methods must have different number
of arguments, if all arguments are of the same data type.
By changing the data type: If the number of arguments in all overloaded methods is same, their
type must be different. No two overloaded methods can have same sequence of data types in 2
definitions.
Simply by changing the Return Type of the Methods, it is not possible to implement Method
Overloading. This is because it results in Ambiguity.
Program:
import java.util.*;
class MethodOverload {
public void add() {
Scanner sc = new Scanner(System.in);
int n1 = 0, n2 = 0, n3 = 0, sum = 0;
sum = n1 + n2 + n3;
System.out.println("SUM of 3 Numbers by Overloaded Method 1 is : " + sum); }
Output:
Enter 2 Integers : 25 34
Enter 3 Floating Point Numbers : 4.567 3.444 12.876
Enter 3 Integers : 25 50 100
Properties of Constructor:
Mostly, a Constructor is specified as Public. There are 2 types of Constructors in JAVA, as:
Default: It doesn‟t have any argument list associated with it. It will assign same default values of
Attributes to all Objects. Although, you can write I/O statements in its body, to retrieve values
for different Attributes of Object from User.
Parameterized: It will accept parameters or arguments while invoking or calling. It will assign
the passed values to the Attributes of Objects.
There is no Copy Constructor in JAVA. However, there are 3 techniques for copying the values
of one Object to another, as:
import java.util.Scanner;
class ParamConstructor {
private String name;
private int age;
private float cgpa;
Output:
String: JAVA String is an Object that represents a sequence of Characters. It can be considered
as an Array of Characters or a Character Array. String is a Class in JAVA; it is a part of “lang”
Package that is included in all JAVA programs by default, so there is no need to import it
explicitly, just like other Packages.
Strings are immutable; once created, they can‟t be modified or overridden. It provides Methods
for performing operations on Strings, like compare(), concat(), split(), length(), replace(), etc.
In this approach, JVM checks the “String Constant Pool” for existence of the String; if String
already exists there, a Reference to a Pooled Instance is returned. It means two Strings having
same value will have same reference in Pool. If String doesn‟t exist in the Pool, then only a new
String instance is created in the Pool. This results in efficient utilization of Memory.
By ‘new’ Keyword: In this approach, JVM creates a new String Object in Heap and the value
assigned to it will be placed in the Pool. The Object will always point to the Heap. It can be
implemented as:
Program:
import java.util.*;
class StringExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String instr = "";
sc.nextLine();
String instr1 = "", instr2 = "";
System.out.println("Enter the First String to Concat : ");
instr1 = sc.nextLine();
System.out.println("Enter the Second String to Concat : ");
instr2 = sc.nextLine();
System.out.println("Enter a String with few Leading, In Between and Trailing Spaces : ");
sc.nextLine();
String spstr = sc.nextLine();
System.out.println("Entered String with Invalid Spaces is : " + spstr);
Enter a String with few Leading, In Between and Trailing Spaces : ___He__llo__India__
Entered String with Invalid Spaces is : ___He__llo__India__
Valid String after Eliminating Invalid Spaces is : He__llo__India
Practical - 15
Aim: Write a program to demonstrate the use of String Buffer in JAVA.
StringBuffer: StringBuffer Class in JAVA allows the creation of Mutable Strings. By default,
Strings are immutable. It allows changes in Strings, thereby making them mutable. It is Thread
Safe, i. e., multiple Threads can‟t access it simultaneously.
CONSTRUCTOR DESCRIPTION
StringBuffer() It creates an Empty StringBuffer with Initial Capacity of 16.
StringBuffer(String str) It creates a StringBuffer with specified String „str‟.
StringBuffer(int capacity) It creates an Empty String Buffer with „capacity‟ as Length.
Program:
import java.util.*;
class StringBufferDemo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String to initialize a String Buffer : ");
String s1 = scan.nextLine();
StringBuffer str_buf = new StringBuffer(s1);
System.out.println("String in String Buffer is : " + str_buf);
System.out.println("Capacity : " + str_buf.capacity());
str_buf.delete(6, 16);
System.out.println("String Buffer after DELETE is : " + str_buf);
System.out.println("Capacity : " + str_buf.capacity());
Output:
‘this’: It is a JAVA Keyword that refers to the current Object. It can be used as a Reference
Variable to point to the current Object, current Class Data, Members or Constructor. The most
common use of „this‟ is to eliminate the confusion between Class Attributes and Parameters with
the same name. There are 6 main uses of „this‟ in JAVA. They are:
~ It can be used to return the Instance of the current Class from the Method.
Program:
import java.util.*;
class ThisExample
{
int x, y, z, product;
Output:
Enter 3 Integers :
5
7
11
Inheritance: It is the most striking feature of OOP that promotes Reusability of Code. It is the
process in which Object of a Class acquire properties of Object of another Class. Inheritance
creates a hierarchical relationship among Classes. It is a process in which a Derived Class
exhibits the characteristics or properties of Base Class.
The Class whose properties are being reused or derived is called Base Class or Parent Class or
Super Class. The Class that reuses the properties of Base Class is called Derived Class or Sub
Class or Child Class. The Child Class inherits the properties of the Base Class. Inheritance
represents “is a” relationship among Classes.
Types of Inheritance: JAVA supports 4 types of Inheritance, namely Simple or Single Level
Inheritance, Multi Level Inheritance, Hierarchical Inheritance and Hybrid Inheritance. “extends”
Keyword is used to specify Inheritance relationship among Classes.
When a Child Class inherits the properties of a Base Class, then it is called Simple or Single
Level Inheritance. When a Child Class inherits the properties of a Base Class and then this Child
Class later becomes Base Class for another Class, then it is called Multi Level Inheritance. When
a single Base Class is derived to multiple Child Classes, then it is called Hierarchical Inheritance.
A Inheritance hierarchy in which there exists Multi Level Inheritance among some Classes and
Hierarchical Inheritance among some Classes, then it is called Hybrid Inheritance in JAVA.
class Base {
Data Members of Base Class;
Member Methods of Base Class; }
Program:
import java.util.*;
class Base {
private String name;
private int age;
class TestSimpleInherit {
public static void main(String[] args) {
Child obj = new Child();
obj.getBaseData();
obj.getChildData();
obj.showBaseData();
obj.showChildData();
} }
Output:
Method Overriding: If the Child Class redefines or modifies the inherited Method of the Base
Class, then it is called Method Overriding. If the Child Class provides the specific
implementation of the Method, already declared in the Base Class, it is known as Method
Overriding. It is a technique to achieve Run Time Polymorphism.
The overridden method of the Child Class must have the same name as in the Base Class. The
overridden method must have the same parameters as in the Base Class. There must be a “is a”
relationship among Classes, i. e., Inheritance.
Program:
class Base {
public void show () {
System.out.println("SHOW METHOD IN BASE CLASS"); }
}
class TestOverriding {
public static void main(String[] args) {
Base objbase = new Base(); objbase.showOverride();
Output:
‘super’: It is a reference variable that refers to an Object of the immediate Base Class. Whenever
an Instance of Child Class is created, an Instance of Base Class is created implicitly, which is
referred by using “super” Keyword. There are 3 main uses of “super” in JAVA as:
Program:
class SuperExampleParent {
public void show() {
System.out.println("This is SHOW() in Parent Class"); }
}
Output:
Abstract Class: A Class which is declared with “abstract” Keyword is called an Abstract Class
in JAVA. It can have Abstract Methods, as well as non abstract methods. It can only be used as
Base Class for extension. Mostly, Abstract Class is used to create a new Inheritance hierarchy.
Abstract Class can never be instantiated; this means that it is not possible to create an Object of
Abstract Class.
Abstract Method: A Method declared using Abstract Keyword is called an Abstract Method.
Final: “final” Keyword in JAVA is used to restrict the usage of programming structures. A
Variable, Method or Class can be declared as “final”. If a variable is declared as “final”, its value
can‟t be changed. If a method is declared as “final”, it can‟t be overridden. If a Class is declared
as “final”, it can‟t be extended.
Abstract Class is mainly used to initialize the new Inheritance hierarchy among Classes; in
contrast, the Final Class is mainly used to terminate the existing Inheritance hierarchy among
Classes.
Program:
class AbstractDemo
{
public static void main(String[] args)
{
Shape rect = new Rectangle();
rect.draw();
Output:
Similar to Abstract Class, Interface can‟t be instantiated. It is used to achieve Loose Coupling.
“interface” Keyword is used to declare an Interface in JAVA. All the Methods in an Interface are
declared with “empty body”; all the fields are Public, Static and Final by default. A Class that
implements an Interface must define or implement all Methods declared in the Interface.
“implements” Keyword is used to associate a Class with an Interface.
A Class can extend only one another Class; however, a Class can implement multiple Interfaces
simultaneously. Similar to Class, an Interface can extend another Interface. The syntax to
implement Interface in JAVA is:
interface INTERFACE_NAME {
static constants;
abstract methods;
}
interface I2 extends I1 {
// abstract methods 1 will be the part of I2, due to „extends‟
abstract methods 2;
}
Program:
import java.util.Scanner;
class C1 implements I1
{
private String name;
public C1()
{
System.out.println("Enter Your Name : ");
Scanner scan = new Scanner (System.in);
name = scan.nextLine();
}
class TestInterface
{
public static void main(String[] args)
{
C1 obj1 = new C1();
obj1.show();
} }
Output:
class C1 implements I {
Data Members of C1;
Member Methods of C1;
public void Method_Name() { Definition for Class C1; }
}
class C2 implements I {
Data Members of C2;
Member Methods of C2;
public void Method_Name() { Definition for Class C2; }
}
class C3 implements I {
Data Members of C3;
Member Methods of C3;
public void Method_Name() { Definition for Class C3; }
}
Program:
import java.util.*;
class OneInterfaceMultipleClassExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int c_m = 0, c_r = 0, c_w = 0, c_c = 0, t_m = 0, t_t = 0, t_gs = 0, f_m = 0, f_g = 0;
System.out.println("Specify the Matches Played, Runs Scored, Wickets Taken and Catches
Taken by Cricketer : ");
c_m = scan.nextInt();
c_r = scan.nextInt();
c_w = scan.nextInt();
c_c = scan.nextInt();
System.out.println("Specify the Matches Played, Titles Wons and Grand Slams Won by Tennis
Player : ");
t_m = scan.nextInt();
t_t = scan.nextInt();
t_gs = scan.nextInt();
Specify the Matches Played, Titles Won and Grand Slams Won by Tennis Player :
700 125 15
Specify the Matches Played and Goals Hit by Footballer :
800 700
Program:
import java.util.*;
public Calculator(int n1, int n2, int n3, double d1, double d2, double d3) {
this.n1 = n1;
this.n2 = n2;
this.n3 = n3;
this.d1 = d1;
this.d2 = d2;
this.d3 = d3;
}
class OneClassMultipleInterfaceExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1 = 0, num2 = 0, num3 = 0;
double dnum1 = 0.0, dnum2 = 0.0, dnum3 = 0.0;
System.out.println("Enter 3 Integers : ");
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();
Output:
Enter 3 Integers :
25 50 100
Enter 3 Floating Point Numbers :
23.6 24.8 25.7