JAVA Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Object Oriented Programming with Java

Unit – I

What is Java?
Java is a high-Level programming language and it is also called as a platform. Java is a
secured and robust high level object-oriented programming language. Platform: Any
software or hardware environment in which a program runs is known as a platform. Java has
its own runtime environment (JRE) and API so java is also called as platform. Java fallows the
concept of Write Once, Run Anywhere.
Application of java
1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games 8. Robotics etc
History of Java
James Gosling, Patrick Naughton and Mike Sheridan initiated the Java language project in
1991. Team of sun engineers designed for small, embedded systems in electronic appliances
like set-top boxes. Initially it was called "Greentalk" later it was called Oak.
Features of Java
1. Object Oriented –-Java implements basic concepts of Object-oriented programming
System (OOPS) i.e. Object, Class, Inheritance, Polymorphism, Abstraction,
Encapsulation.
2. Platform Independent - Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
3. Simple - Java fallows the basic Syntax of C, C++. If you understand the basic concept
of OOPS then it is easy to master in java.
4. Secure -The primary reason for Java's security is its implementation of the Java
Virtual Machine (JVM). The JVM is responsible for making sure that all Java code
runs securely, regardless of the operating system it is running on. It does this by using
a set of security policies and rules that ensure only authorized code is allowed to run.
It means that malicious code is quickly detected and blocked, and any code that is
deemed to be unsafe is not executed.
5. Portable - Due to the concept of Write Once Run Anywhere (WORA) and platform
independence, Java is a portable language. By writing once through Java, developers
can get the same result on every machine. It is also very portable to various operating
systems and architectures.
6. Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime
checking.
7. Multithreaded − With Java's multithreaded feature in java we can
write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive
applications that can run smoothly.
8. High Performance - With the use of Just-In-Time compilers, Java enables high
performance.
9. Distributed − Java is designed for the distributed environment of the internet.
10. Compiled and Interpreted - Java offers both compilation and interpretation of
programs. It combines the power of compiled languages and the flexibility of
interpreted languages. When a Java program is created, the Java compiler (javac)
compiles the Java source code into byte code. The Java Virtual Machine (JVM) is an
interpreter that converts byte code to machine code, which is portable and can be
executed on any operating system.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. JVMs are available for many hardware
and software platforms (i.e. JVM is platform dependent).
The JVM performs following operation:
1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment

The Bytecode output of a Java compiler is not executable


code. Rather, it is bytecode. Bytecode is a highly optimized set of
instructions designed to be executed by the Java run-time system, which is
called the Java Virtual Machine (JVM)

JRE
JRE (Java Runtime Environment) is a software package that provides Java class libraries,
Java Virtual Machine (JVM), and other components that are required to run Java applications.
JRE is the superset of JVM.
JDK
JDK (Java Development Kit). It is a bundle of software development tools and supporting
libraries combined with the Java Runtime Environment (JRE) and Java Virtual Machine
(JVM).

Compilation Fundamental: First, the source ‘.java’ file is passed through the compiler,
which then encodes the source code into a machine-independent encoding, known as
Bytecode. The content of each class contained in the source file is stored in a separate ‘.class’
file.

Java Source File Structure: Java source file structure describes that the Java source code
file must follow a schema or structure.
A Java program has the following structure:
PACKAGES: A java package is a group of similar types of classes, interfaces and sub-
packages. Package in java can be categorized in two form, built-in package and user-defined
package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
package <fully qualified package name>;
package pkg;
Here, pkg is the name of the package.
There are two types of packages in java :
1. Built in package: In java, we already have various pre-defined packages and these
packages contain large numbers of classes and interfaces that we used in java are
known as Built-in packages.
Eg: java.util , java.lang , java.io, java.sql etc
2. User defined package: As the name suggests user-defined packages are a package that
is defined by the user or programmer.
eg: package test;

import statements: The import statement is used to import a package class, or interface.
From external sources into your current java file.
For example: if you want to use Scanner class which is use to get user input we need to
import the scanner class in current source code using import keyword so that we can access
all the method available in Scanner class.
Syntax:
import packagename.class; // for particular calss
import packagename.*; //for all class
class definition: A class is a user-defined blueprint or prototype from which objects are
created, and it is a passive entity.
Java allows us to create any number of classes in a program. But out of all the classes, at
most, one of them can be declared as a public class. In simple words, the program can contain
either zero public class, or if there is a public class present, it cannot be more than one.
First case
class Today {
}

class Learning {
}
class Programming {
}
In the above java Source file no class is defined as public. We can save this file with any
name. It will compiles successfully without any errors, and corresponding .class files are
generated.
Second case
public class Today {
}

class Learning {
}
class Programming {
}
In this case name of java source file will be Today.java. If we write another name compiler
will generate error

CONSTRUCTORS: Constructor is special member function, it has the same name as class
name. It is called when an instance of object is created and memory is allocated for the
object.
It is a special type of method which is used to initialize the object
Rules for creating java 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 in java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
A constructor is called "Default Constructor" when it doesn't have any parameter. The
default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
class Sample{
Sample()
{
System.out.println("Sample is created");
}
public static void main(String args [])
{
Sample b=new Sample();
}}
Output : Sample is created
A constructor which has a specific number of parameters is called parameterized
constructor.
public class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(11,"Anuj ");
Student s2 = new Student(22,"Preeti ");
s1.display();
s2.display();
}}
METHODS − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.
class Sample{
public void display(){
System.out.println("This is method");
}
public static void main(String args[]){
System.out.println("This is main method");
}}
ACCESS SPECIFIES OR ACCESS MODIFIER
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:
1. private
2. default
3. protected
4. public
Private: The private access modifier is specified using the keyword private. The methods or
data members declared as private are accessible only within the class in which they are
declared. Any other class of the same package will not be able to access these members.
package p1; class B {
class A { public static void main(String args[])
private void display() {
{ A obj = new A();
System.out.println("Calling private obj.display();
Method"); }}
}}

error: display() has private access in A


obj.display();
Default Access Modifier: When no access modifier is specified for a class, method, or data
member – It is said to be having the default access modifier by default. The data members, classes, or
methods that are not declared using any access modifiers i.e. having default access modifiers are
accessible only within the same package.

package p1; package p2;


class First import p1.*;
{ class Second
void display() {
{ public static void main(String args[])
System.out.println("this is default {
method"); First obj = new First();
}} obj.display();
}
}

Error : Compile time error


Protected Access Modifier: The protected access modifier is specified using the keyword
protected. The methods or data members declared as protected are accessible within the same package
or subclasses in different packages.

package p1; package p2;


public class A { import p1.*;
protected void display() class B extends A {
{ public static void main(String args[])
System.out.println("Protected {
Method"); B obj = new B();
}} obj.display();
}}

Output: Protected Method


Public Access modifier: The public access modifier is specified using the keyword public. The public
access modifier has the widest scope among all other access modifiers. Classes, methods, or data
members that are declared as public are accessible from everywhere in the program. There is no
restriction on the scope of public data members.
package p1;
public class A
{
public void display() {
System.out.println("This is public method");
} }
package p2;
import p1.*;
class B {
public static void main(String args[]){
A obj = new A();
obj.display();
}}
Output: This is public

STATIC MEMBERS: The static keyword can be used with methods, fields, classes (inner/nested),
blocks. you can access these members without instantiating the class.
The Static can be:
1. Static Methods − You can create a static method by using the keyword static. Static methods
can access only static fields, methods. To access static methods there is no need to instantiate
the class, you can do it just using the class name as:
public class MyClass {
public static void sample(){
System.out.println("This is static method");
}
public static void main(String args[]){
MyClass.sample();
}
}
Output : This is static method

2. Static Fields − You can create a static field by using the keyword static. The static fields
have the same value in all the instances of the class. These are created and initialized when
the class is loaded for the first time. Just like static methods you can access static fields using
the class name (without instantiation).
public class MyClass {
public static int data = 20;
public static void main(String args[]){
System.out.println(MyClass.data);
}
}
Output : 20

3. Static Blocks − These are a block of codes with a static keyword. In general, these are used to
initialize the static members. JVM executes static blocks before the main method at the time
of class loading.
public class MyClass {
static {
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Output : Hello this is a static block
This is main method

FINAL MEMBERS
Final keyword is used to indicate that a variable, method, or class cannot be modified
or extended
Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized. This is useful for declaring constants or other values that should not be
modified.
Final methods: When a method is declared as final, it cannot be overridden by a subclass.
This is useful for methods that are part of a class’s public API and should not be modified by
subclasses.
Final classes: When a class is declared as final, it cannot be extended by a subclass. This is
useful for classes that are intended to be used as is and should not be modified or extended.
Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class. This ensures that the value of the variable is set and cannot be
changed.

COMMENTS: Comments can be used to explain Java code, and to make it more readable. It can
also be used to prevent execution when testing alternative code.

• Single line comment: // This is a comment


• Multi line comments: /* Multiple Line of comments */
• Documentation Comment : use to write large programs for a project
DATA TYPES: Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
1. Primitive data types: The primitive data types include Boolean, char, byte, short, int,
long, float and double.
byte
• Byte data type is an 8-bit signed two's complement integer
• Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1)
• Default value is 0
• Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an integer.
• Example: byte a = 100, byte b = -50
short

• Short data type is a 16-bit signed two's complement integer


• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767 (inclusive) (2^15 -1)
• Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
• Default value is 0.
• Example: short s = 10000, short r = -20000
int

• Int data type is a 32-bit signed two's complement integer.


• Minimum value is - 2,147,483,648 (-2^31)
• Maximum value is 2,147,483,647(inclusive) (2^31 -1)
• Integer is generally used as the default data type for integral values unless there is a
concern about memory.
• The default value is 0
• Example: int a = 100000, int b = -200000
long

• Long data type is a 64-bit signed two's complement integer


• Minimum value is -9,223,372,036,854,775,808(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
• This type is used when a wider range than int is needed
• Default value is 0L
• Example: long a = 100000L, long b = -200000L
float

• Float data type is a single-precision 32-bit IEEE 754 floating point


• Float is mainly used to save memory in large arrays of floating point numbers
• Default value is 0.0f
• Float data type is never used for precise values such as currency
• Example: float f1 = 234.5f
double

• double data type is a double-precision 64-bit IEEE 754 floating point


• This data type is generally used as the default data type for decimal values, generally
the default choice
• Double data type should never be used for precise values such as currency
• Default value is 0.0d
• Example: double d1 = 123.4
boolean

• boolean data type represents one bit of information


• There are only two possible values: true and false
• This data type is used for simple flags that track true/false conditions
• Default value is false
• Example: boolean one = true
char

• char data type is a single 16-bit Unicode character


• Minimum value is '\u0000' (or 0)
• Maximum value is '\uffff' (or 65,535 inclusive)
• Char data type is used to store any character
• Example: char letterA = 'A'

2. Non-primitive data types: The non-primitive data types include String, Arrays etc
VARIABLES: Variables are the data containers that save the data values during Java program
execution. Every Variable in Java is assigned a data type that designates the type and quantity of value
it can hold.
Example: int t = 10;
Types of Variables:
1. Local Variables These variables are declared in methods, constructors, or blocks and are
used only inside that particular method or block. You cannot access a local variable
outside the method. In Java, methods are described under curly brackets. The area ({….})
between the brackets is called a block or a method.
// Local Variables
class TestLocal {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Output: Local Variable: 10

2. Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block. As instance variables are declared in a class, these
variables are created when an object of the class is created and destroyed when the object
is destroyed. Unlike local variables, we may use access specifiers for instance variables.
If we do not specify any access specifier, then the default access specifier will be used.
// Instance Variables
class TestInstance {

// Declared Instance Variable


public String name;
public int i;
public TestInstance ()
{
// Default Constructor
// initializing Instance Variable
this. name = "Piyush Kumar";
}
public static void main(String[] args)
{
TestInstance t = new TestInstance();
System.out.println("Name is: " +t. name.);
System.out.println("Default value for int is "
+ t.i);
}}
Output: Name is: Piyush Kumar
Default value for int is 0

3. Static variables are also known as class variables. These variables are declared similarly
to instance variables. The difference is that static variables are declared using the static
keyword within a class outside of any method, constructor, or block.
class TestStatic {
public static String name = "Pankaj kumar";
public static void main(String[] args)
{
System.out.println("Name is : " + TestStatic.name);
}}
OPERATORS: 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:

1. Unary Operator: Unary operator is an operator that operates on a single operand.


• Increment (++) It increases the value of variable by 1.
• Decrement (--) It decreases the value of a variable by 1.
• Unary plus (+) Represents a positive value
• Logical complement(!): Flips the value of a boolean expression.

2. Arithmetic Operator: Arithmetic operators are used to perform common mathematical


operations (+, -, %, *).

3. shift Operator: shift operators are the special type of operators that work on the bits of the
data. These operators are used to shift the bits of the numbers from left to right or right to left
depending on the type of shift operator used.

• Left Shift Operator (<<) : left shift operator is a special type of operator used
to move the bits of the expression to the left according to the number
specified after the operator.

• Right Shift Operator (>>) : right shift operator is a special type of operator
used to move the bits of the expression to the right according to the number
specified after the operator.

• Unsigned Right Shift Operator (>>>): unsigned right shift operator is a


special type of right shift operator that does not use the signal bit to fill in the
sequence. The unsigned Right shift operator on the right always fills the
sequence by 0.
Example: x => 40 => 0000 0000 0000 0000 0000 0000 0010 1000

A negative number is the 2's complement of its positive number. So,

Y => -40 => 1111 1111 1111 1111 1111 1111 1101 1000
Thus x >>> 2 = 0000 0000 0000 0000 0000 0000 0000 1010

AND y >>> 2 = 0011 1111 1111 1111 1111 1111 1111 0110

4. Relational Operator: Java Relational Operators are a bunch of binary operators used to
check for relations between two operands, including equality, greater than, less than, etc. They
return a boolean result after the comparison and are extensively used in looping statements as
well as conditional if-else statements and so on.
variable1 relation_operator variable2

5. Bitwise Operator:
These operators are used to perform the manipulation of individual bits of a number. They can
be used with any of the integer types. They are used when performing update and query
operations of the Binary indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.
Example:

6. Logical Operator: You can also test for true or false values with logical operators.
• && is Logical and Returns true if both statements are true.
• || is Logical or Returns true if one of the statements is true.
• ! is Logical not Reverse the result, returns false if the result is true.

7. Ternary Operator: The ternary operator is a shorthand version of the if-else statement. It
has three operands and hence the name Ternary.
The general format is:
condition? if true: if false
The above statement means that if the condition evaluates to true, then execute the statements
after the ‘?’ else execute the statements after the ‘:’.

8. Assignment Operator: Assignment operators are used to assign values to variables.


In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
int x = 10;
x += 5; ( now x is 15)
CONTROL FLOW: Java compiler executes the code from top to bottom. The statements in the code
are executed according to the order in which they appear. However, Java provides statements that can
be used to control the flow of Java code. Such statements are called control flow statements. Java
provides three types of control flow statements.
1. Decision Making statements: decision-making statements decide which statement to execute
and when. Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided.
• if statements
• switch statement
Simple If statement
if(condition) {
statement 1; //executes when condition is true
}

if-else statement
if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
if-else-if
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
switch (expression){
case value1:
statement1;
break;
--
---
.case valueN:
statementN;
break;
default:
default statement;
}

2. Loop statements: In programming, sometimes we need to execute the block of code


repeatedly while some condition evaluates to true. However, loop statements are used to
execute the set of instructions in a repeated order. The execution of the set of instructions
depends upon a particular condition.
• do while loop
• while loop
• for loop
• for-each loop
do while loop
Java do-while loop is used to iterate a part of the program several times.If the number of iteration is
not fixed and you must have to execute the loopat least once, it is recommended to use do-while
loop.The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax: do{ /code to be executed
}while(condition);
While Loop
while loop is used to iterate a part of the program several times. If the number of iteration is not fixed,
it is recommended to use while loop.
while(condition){
//looping statements
}
for loop
for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.
for(initialization, condition, increment/decrement) {
//block of statements
}
for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.
for(datatype var: array name/collection name){
//statements }
3. Jump statements: Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the execution control to the other
part of the program. There are two types of jump statements in Java, i.e., break and continue.
• break statement
• continue statement
break Statement
the break statement is used to break the current flow of the program and transfer the control to the
next statement outside a loop or switch statement. However, it breaks only the inner loop in the case
of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i); } } }
Output: 0
1
2
3
Continue statement :Unlike break statement, the continue statement doesn't break the loop, whereas,
it skips the specific part of the loop and jumps to the next iteration of the loop immediately.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
if (i == 2) {
continue;
}
System.out.println(i);
} }}
Output : 0
1
3
Arrays: Array is an object which contains elements of a similar data type. The elements of an array
are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on i.e. Arrays in Java are 0 base indexed.

Declaring Array Variables


dataType[] a; // preferred way.
or
datatype a[]; // works but not preferred way.
Example: int[] a;
Instantiation of an Array
a = new datatype[size];
example : int a[] = new int[10] ;
Basic example of Declaration, Instantiation and Initialization
class TestArray{
public static void main(String args[]){
int[] a = {4, 7,8,9,1}; //initialization
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output : 4
7
8
9
1
Advantages
● Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
● Random access: We can get any data located at an index position.
Disadvantages
● Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.
Types of Array in java
There are two types of array.
1) Single Dimensional Array
2) Two Dimensional Array
3) Multidimensional Array
Single dimensional array − A single dimensional array of Java is a normal array where, the array
contains sequential elements (of same type) −
int[] myArray = {10, 20, 30, 40}
Two dimensional Array In Two dimensional Array You can store items that have both rows and
columns. A row has horizontal elements. A column has vertical elements.

Datatype arrayname[][] ;
arrayname = new datatype[2][3];
datatype arrayname[][] = new datatype[R][C];
R is size of row and C is size of column
Example : a[][] = new int[2][3];
Multi-dimensional arrays contain more than one dimension, such as rows, columns, etc. These
arrays can be visualized as tables with rows and columns where each element is accessed through its
position.
Example
public class TestArray {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; i++) {
for(int j = 0; j < myNumbers[i].length; j++) {
System.out.print(myNumbers[i][j]+ “ ”);
}
System.out.println(" "); } } }
Output: 1 2 3 4
5 6 7
Strings : A String is a sequence of characters. Which may contain alpha numeric values enclosed in
double quotes (e.g. "Hello World").
A String is immutable. this means that once an Object is created it, cannot be changed.
It contains methods that can perform certain operation on Strings
eg: concat(), equals(), length() etc.
There are two ways to create String object.
1. String Literal :
e.g. String greeting = "Hello world!"; Here, "Hello world!" is a string literal.
Java keep only one copy of a string literal object and reuses them. This process is called String
interning.
In this approach, string objects are not created again and again, but reused.

2. Creating a String object using the new keyword


e.g. String greeting = new String("Hello world!");
Whenever the new keyword is used, an object is created allocating memory from the heap.

Example :
Using String literal
public class TestString{
public static void main(String[] args){
String a = "Hello"; //literal
System.out.println(a); //Hello
String b = "Hello"; //literal
System.out.println(b); // Hello
System.out.println (a==b);
}}
// output: True

Using new keyword


public class TestString{

public static void main(String[] args){


String a = new String("Hello");
System.out.println(a);
String b = new String("Hello");
System.out.println(b);
System.out.println (a==b); // output is false memory location are different
}}
Output: False

Important Methods of String


• length(): Returns the length of the string
• split(): Splits the string at the specified string (regex)
• replace(): Replace all matching characters/text in the string
• substring(): Returns a substring from the given string
• equals() : Compares two strings
• equalsIgnoreCase(): Compares two strings ignoring case differences
• trim(): Removes any leading and trailing whitespace
• charAt(): Returns the character at the given index
• toLowerCase(): Converts characters in the string to lower case
• concat(): Concatenates two strings and returns it
StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
} }
Output: Hello java
StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is
same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming language model organized around
objects rather than actions and data. An object-oriented program can be characterized as data
controlling access to code. Concepts of OOPS
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
OBJECT
Object means a real word entity such as pen, chair, table etc. Any entity that has state and
behavior is known as an object. Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects can communicate without
knowing details of each other's data or code, the only necessary thing is that the type of
message accepted and type of response returned by the objects.
An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
• identity: Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. But it is used internally by the JVM to identify
each object uniquely.
CLASS
Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. A class consists of Data members
and methods. The primary purpose of a class is to hold data/information. The member
functions determine the behavior of the class, i.e. provide a definition for supporting various
operations on data held in the form of an object.Class doesn’t store any space.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from
the parent class. When one object acquires all the properties and behaviors of another object,
it is known as inheritance. It provides code reusability and establishes relationships between
different classes. A class which inherits the properties is known as Child Class (sub-class or
derived class) whereas a class whose properties are inherited is known as Parent class(super-
class or base class). Types of inheritance in java: single, multilevel and hierarchical
inheritance. Multiple and hybrid inheritance is supported through interface only.
1. Single Inheritance
This is the simplest form of inheritance, where one class inherits another class.
In below Diagram A is Superclass (parent class) , B is subclass (child class)
public class SuperClass {
void methodSuper() {
System.out.println("I am a super
class method");
}}

// Inheriting SuperClass to SubClass


public class SubClass extends
SuperClass {
void methodSubclass() {
System.out.println("I am a sub class
method");
}}
public class Main {
public static void main(String args [])
{
SubClass obj = new SubClass();
obj.methodSubclass();
obj.methodSuper();
} }

Output: I am a sub class method


I am a super class method
2. Multilevel Inheritance
This is an extension to single inheritance in Java, where another class again inherits
the subclass, which inherits the superclass. The below figure makes this inheritance
clear
A is Superclass (parent class) , B is first subclass (child class) , C is second
subclass(child class)
public class Bird {
void fly() {
System.out.println("I am a
Bird");
}}
public class Parrot extends Bird {
void color() {
System.out.println("I am
green!");
}}
public class SingingParrot extends
Parrot {
void sing() {
System.out.println("I can
sing");
}}
class Main {
public static void main(String
args []) {
SingingParrot obj = new
SingingParrot();
obj.sing();
obj.color();
obj.fly();
}}

Output: I can sing


I am green!
I am a Bird
3. Hierarchical inheritance
In Hierarchical inheritance, a single superclass is inherited separately by two or more
subclasses. The below figure illustrates this inheritance:
A is Superclass (parent class) , B , C, D are subclass (child class)

public class Bird {


void fly() {
System.out.println("I am a
Bird");
}
}
public class Parrot extends Bird {
void colour() {
System.out.println("I am
green!");
}
}
public class Crow extends Bird {
void colour() {
System.out.println("I am
black!");
}
}
class Main {
public static void main(String
args[]) {
Parrot par = new Parrot();
Crow cro = new Crow();
//Call methods of Parrot Class
par.colour();
par.fly();
//Call methods of Crow Class
cro.colour();
cro.fly();
}}

Output I am green!
I am a Bird
I am black!
I am a Bird
4. Multiple Inheritance in Java: Multiple Inheritance is a feature of an object-oriented
concept, where a class can inherit properties of more than one parent class. The
problem occurs when there exist methods with the same signature in both the
superclasses and subclass. On calling the method, the compiler cannot determine
which class method to be called and even on calling which class method gets the
priority. In Java, we can achieve multiple inheritance through the concept of
interface. An interface is like a class that has variables and methods, however,
unlike a class, the methods in an interface are abstract by default.

5. Hybrid Inheritance in Java: In general, the meaning of hybrid (mixture) is made of


more than one thing. In Java, the hybrid inheritance is the composition of two or more
types of inheritance. The main purpose of using hybrid inheritance is to modularize
the code into well-defined classes. It also provides the code reusability. The hybrid
inheritance can be achieved by using the following combinations:

The this Keyword


this keyword is used to to refer to the object that invoked it. this can be used inside any
method to refer to the current object. That is, this is always a reference to the object on which
the method was invoked. this() can be used to invoke current class constructor.
Example:
public class Student
{
int id;
String name;
Student(int id, String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student stud1 = new Student(1,"Tarun");
stud1.display();
}}
Output:
1 Tarun
Super Keyword: super is the reserved keyword in Java that is used to invoke constructors
and methods of the parent class. This is possible only when one class inherits another class
(child class extends parent class).
// parent class
public class Parent {
int a = 50;
String s = "Hello World!";
}
// child class extending parent class
class Child extends Parent {
int a = 100;
String s = "Happy Coding!";
void print() {
// referencing to the instance variable of parent class
System.out.println("Number from parent class is : " + super.a);
System.out.println("String from parent class is : " + super.s);
// printing a and s of the current/child class
System.out.println("Number from child class is : " + a);
System.out.println("String from child class is : " + s);
}}
public class Main {
public static void main(String[] args) {
// creating instance of child class
Child obj = new Child();
obj.print();
}}
Output:
Number from parent class is : 50
String from parent class is : Hello World!
Number from child class is : 100
String from child class is : Happy Coding!
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.
Polymorphism is classified into two ways:
Method Overloading(Compile time Polymorphism): Method Overloading is a feature that
allows a class to have two or more methods having the same name but the arguments passed
to the methods are different. Compile time polymorphism refers to a process in which a call
to an overloaded method is resolved at compile time rather than at run time.
public class TestMethodOverLoading{
public int addition(int x, int y) {
return x + y;
}
public int addition(int x, int y, int z) {
return x + y + z;
}
public static void main(String[] args) {
TestMethodOverLoading number = new TestMethodOverLoading();
int res1 = number.addition(444, 555);
System.out.println("Addition of two integers: " + res1);
int res2 = number.addition(333, 444, 555);
System.out.println("Addition of three integers: " + res2);
}}
Output: Addition of two integers: 999
Addition of three integers: 1332
Method Overriding(Run time Polymorphism): If subclass (child class) has the same
method as declared in the parent class, it is known as method overriding in java.In other
words, If subclass provides the specific implementation of the method that has been provided
by one of its parent class, it is known as method overriding.
// Java Example: Run Time Polymorphism
class Vehicle {
public void displayInfo() {
System.out.println("Some vehicles are there.");
}
}
class Car extends Vehicle {
public void displayInfo() {
System.out.println("I have a Car.");
}
}
class Bike extends Vehicle {
public void displayInfo() {
System.out.println("I have a Bike.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v1 = new Car();
Vehicle v2 = new Bike();
v1.displayInfo();
v2.displayInfo();
}
}
OUTPUT: I have a Car.
I have a Bike.
ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only functionality
to the user. For example: phone call, we don't know the internal processing. In java, we use
abstract class and interface to achieve abstraction.
Abstraction in Java can be achieved using the following tools it provides:
• Abstract classes
• Interfaces
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must
be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzzz");
}}
public class Cat extends Animal {
public void animalSound() {
System.out.println("The Cat says: meow");
}}
class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.animalSound();
cat.sleep();
}}
OUTPUT: The Cat says: meow
Zzzz
Interfaces
Another way to achieve abstraction in Java, is with interfaces. An interface is a completely
"abstract class" that is used to group related methods with empty bodies.
interface Animal {
public void animalSound();
public void sleep();
}
------------------------------------
class Cat implements Animal {
public void animalSound() {
System.out.println("The Cat says: meow");
}
public void sleep() {
System.out.println("sleeping");
}}
class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.animalSound();
cat.sleep();
}
}}
OUTPUT: The Cat says: meow
sleeping
Multiple Interfaces
To implement multiple interfaces, separate them with a comma.

interface Animal {
public void animalSound();
public void sleep();
}
interface Animal2 {
public void eat();
}
------------------------------------
class Cat implements Animal , Animal2{
public void animalSound() {
System.out.println("The Cat says: meow");
}
public void sleep() {
System.out.println("sleeping");
}
public void eat() {
System.out.println("cat eat food"); }
}
class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.animalSound();
cat.sleep();
cat.eat();
}}
Output: The Cat says: meow
sleeping
cat eat food
ENCAPSULATION
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines. A java class is the example of
encapsulation.
Achieving Encapsulation in Java
• Declare the variables of a class as private.
• Provide public setter and getter methods to modify and view the variables values.
Example:
class Employee{
private String name;// concept of Data hiding
public void setName(String name){
this.name=name;
}

public String getName(){


return name;
}
}
class Test{
public static void main(String[] args){
Employee e = new Employee();
e. setName("Rahul");
System.out.println(e.getName());
} }
Output : Rahul

Packages: A packages is a collection of related classes, Interface and sub packages.


Example: package P1;
public class First {
public void display () {
System.out.println("I am first");
}}
The above source code is stored in First.java file in ‘P1’ folder. It is then compiled, which
produces First.class file in p directory.
The package can be used as follows:
package p2;

import P1.First;
public class Test{
public static void main(String[] args) {
First f = new First();
f.display ();
}}
Package plays an important role in preventing naming conflicts, Controlling access, and
making searching and usage of classes , interfaces and annotation easier.
Naming Conventions : For avoiding unwanted package names we have some following
naming conventions which we use in creating a package.
The name should always be in the lower case.
Static import in Java
In Java, static import concept is introduced in 1.5 version. With the help of static import, we
can access the static members of a class directly without class name or any object. For
Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but
by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance coding.
But according to the programming experts, it will lead to confusion and not good for
programming. If there is no specific requirement then we should not go for static import.
Advantage of static import:
If user wants to access any static member of class then less coding is required.
Disadvantage of static import: Static import makes the program unreadable and
unmaintainable if you are reusing this feature.
Using import Using static import
class TestImportJava { import static java.lang.Math.*;
public static void main(String[] args) class Test2 {
{ public static void main(String[] args)
System.out.println(Math.sqrt(4)); {
System.out.println(Math.pow(2, 2)); System.out.println(sqrt(4));
System.out.println(Math.abs(6.3)); System.out.println(pow(2, 2));
} System.out.println(abs(6.3));
} }
}

Output: 2.0 Output: 2.0


4.0 4.0
6.3 6.3

Classpath
CLASSPATH describes the location where all the required files are available which are used
in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to
locate the required files. If the CLASSPATH is not set, Java Compiler will not be able to find
the required files and hence will throw the following error.
Error: Could not find or load main class <class name>
Set the CLASSPATH in JAVA in Windows
Command Prompt: set PATH=.;C:\Program Files\Java\JDK1.6.20\bin
Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH in the
above command.
Or
Select Start -> Control Panel -> System -> Advanced -> Environment Variables -> System
Variables -> CLASSPATH.
If the Classpath variable exists, prepend .;C:\introcs (C:\Program Files\Java\JDK1.6.20\bin)
to the beginning of the CLASSPATH varible.
If the CLASSPATH variable does not exist, select New. Type CLASSPATH for the variable
name and .;C:\introcs for the variable value.
Click OK
Jar Files
A JAR (Java Archive) is a package file format typically used to aggregate many Java class
files and associated metadata and resources (text, images, etc.) into one file to distribute
application software or libraries on the Java platform.
In simple words, a JAR file is a file that contains a compressed version of .class files, audio
files, image files, or directories. We can imagine a .jar file as a zipped file(.zip) that is created
by using WinZip software. Even, WinZip software can be used to extract the contents of a .jar
So you can use them for tasks such as lossless data compression, archiving, decompression,
and archive unpacking.
In order to create a .jar file, we can use jar cf command in the following ways as discussed
below:

Syntax: jar cf jarfilename inputfiles


Here, cf represents to create the file. For example , assuming our package pack is available in
C:\directory , to convert it into a jar file into the pack.jar , we can give the command as:
C:\> jar cf pack.jar pack
Now, the pack.jar file is created. In order to view a JAR file ‘.jar’ files, we can use the
command as:
Syntax: jar tf jarfilename
Here, tf represents the table view of file contents. For example, to view the contents of our
pack.jar file, we can give the command:
C:/> jar tf pack.jar
In order to extract the files from a .jar file, we can use the commands below listed:
Syntax: jar xf jarfilename

You might also like