0% found this document useful (0 votes)
5 views40 pages

Unit 1 Java

The document provides an introduction to Java programming, detailing its features, types of applications, and differences from C++. It covers the Java Development Kit (JDK), Java Virtual Machine (JVM), and Java Runtime Environment (JRE), along with data types, tokens, naming conventions, and operators. Additionally, it includes a simple Java program example and instructions on compiling and running it.

Uploaded by

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

Unit 1 Java

The document provides an introduction to Java programming, detailing its features, types of applications, and differences from C++. It covers the Java Development Kit (JDK), Java Virtual Machine (JVM), and Java Runtime Environment (JRE), along with data types, tokens, naming conventions, and operators. Additionally, it includes a simple Java program example and instructions on compiling and running it.

Uploaded by

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

Core Java Programming

(BCA 512)
By
Anuj Kumar Raghav
(TMU07531)
Unit 1

Introduction of Java

 Java is an object oriented programming language originally developed by Sun Micro


System and released in 1995.
 Java was originally by James Gosling at Sun Microsystems (which has since merge in
Oracle Corporation).
 Java programs are platform independent which means they can be run on any operating
system.
 Java codes that run on one platform does not need to recompile to run on another
platform, it’s called “write once run anywhere”.

Java Features or Buzzwords

1. Object Oriented
Java is an object oriented programming language which follows the concepts of oop’s.
2. Platform Independent
Java application programs written on one operating system can be able to run on any
platform. So the java is platform independent. On compilation java program is compiled
into byte code (.class file). This byte code is platform independent and can be run on any
machine.
3. Simple
Java syntax is similar to c and c++ and it follow the oop’s concepts so it is easy to learn.
4. Secure
Java’s securing feature it enable to develop virus free, tamper free (software which is not
modify by attacker). Authentication techniques are based on public key encryption
Architectural Neutral
5. Portable
We may carry the java byte code to any platform.
6. Robust
Robust simply means strong. Java uses strong memory management. There is lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points make
java robust.
7. Multi Threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications etc.
8. Interpreted
Java is a compiled programming language, but rather than compile straight to executable
machine code, it compiles to an intermediate binary form called JVM byte code. The byte
code is then compiled and/or interpreted to run the program.
9. High Performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Types of java Application
1. Web Application
Java is used to create server side applications. Currently, servlet, jsp, struts, jsf etc.
technology are used.
2. Stand- Alone Application
It is also known as desktop application or window based application. An application
that we need to install on every machine such as antivirus, media player etc. AWT and
Swing is used in java for creating standalone application.
3. Enterprise Application
An application that is distributed in nature, such as banking application etc. In java
EJB is used to create enterprise application.
4. Mobile application
Java is used to create application software for mobile devices. Currently
java ME is used for creating application for small devices and java is programming for
Google Android application development.

Different Editions of java Technology


1. Java SE
Java SE or Java Standard Edition provides tools and API’s that can use to create
server application, desktop application and even applets. These programs developed
using java SE can be run on almost every popular operating system include Linux,
Macintosh, Solaris, and Windows.
2. JEE
Based on the foundation framework of the standard edition, java Enterprise Edition
helps in web application service, component model and enterprise class service
oriented architecture.
3. JME
Java Micro Edition or JME is use for the development of software for devices like
mobile phones, PDA’s, TV set-top box, game programming.
C++ v/s Java

Comparison C++ Java


Platform-
C++ is platform-dependent. Java is platform-independent.
independent
Java is mainly used for application
C++ is mainly used for system programming. It is widely used in
Mainly used for
programming. window, web-based, enterprise and
mobile applications.
Goto C++ supports goto statement. Java doesn't support goto statement.
Java doesn't support multiple inheritance
Multiple C++ supports multiple
through class. It can be achieved by
inheritance inheritance.
interfaces in java.
Operator C++ supports operator Java doesn't support operator
Overloading overloading. overloading.
C++ supports pointers. You you can't write the pointer program in
Pointers can write pointer program in java. It means java has restricted pointer
C++. support in java.
Compiler and
C++ uses compiler only. Java uses compiler and interpreter both.
Interpreter
Call by Value and C++ supports both call by Java supports call by value only. There is
Call by reference value and call by reference. no call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
C++ doesn't have built-in
support for threads. It relies
Thread Support Java has built-in thread support.
on third-party libraries for
thread support.
Java supports documentation comment
Documentation C++ doesn't support
(/** ... */) to create documentation for
comment documentation comment.
java source code.
Java has no virtual keyword. We can
C++ supports virtual keyword
override all non-static methods by
Virtual Keyword so that we can decide whether
default. In other words, non-static
or not override a function.
methods are virtual by default.
Java supports unsigned right shift >>>
unsigned right C++ doesn't support >>> operator that fills zero at the top for the
shift >>> operator. negative numbers. For positive numbers,
it works same like >> operator.
Java uses single inheritance tree always
C++ creates a new inheritance because all classes are the child of Object
Inheritance Tree
tree always. class in java. Object class is the root of
inheritance tree in java.
Setting Path for Java

 Java is freely available on the oracle website Download the latest version of JDK(java
Development Kit)on your machine.
 Install JDK on your machine.
 Once you have installed java on your machine it need to set environment variable to point
to correct installation directory.
 An environment variable is a dynamic “object ” on a computer that stores a value (like a key
value ), which can be reference by one or more software programs in Windows. Like in java ,
we will set environment variable with name ”java” and its values will be the path of /bin
directory present variable which will give it the path to the execution.

Step: 1 Right click on My Computer icon and select properties.

Step: 2 Go to Advance Setting Tab


Step: 3 Click on Environment Variable Button

Step:4 Now alter the path variable so that it also contains the path to jdk installed
directory.
First java Program

public class FirstJava


{
public static void main(String[] args)
{
System.out.println("Welcome in Aims");
}

}
 class: class is a keyword is used to declare classes in java
 public: It is an access specifiers . Public means this function is visible to all.
 static: static is used to make a function static. To execute a static function you
do not have to create an Object of the class. The main () method here is called
by jvm, without creating any object for class.
 void: void is return type, meaning this function will not return anything.
 main(): main() method is the most important method in a java program . this
is the method which is executed hence all logic must be inside the main()
method. If a java class is not having a main() method, it causes compilation
error.
 System.out.println(): This is used to print anything on the consol like
printf()in c.

Steps to compile and Run FirstJava Program

Step: 1 Open a text editor like Notepad and write the code as above.
Step: 2 save the file as FirstJava.java
Step: 3Open command prompt and go to the directory where you saved your first java
program
Step: 4 Type javac FirstJava.java then enter to compile the program

Step: 5 Now Type java FirstJava on command prompt the enter to run program.

Step: 6 Now you will be able to see Welcome in Aims oriented on your command
prompt.
Java Development Kit (JDK)

JDK is an acronym for Java Development Kit.


It physically exists. It contains JRE + the complete set of class file for all the java technology
package, which include basic language classes.GUI components classes, an advanced
collection API, and so no.

Java Virtual Machine (JVM)

It is an abstract machine or imaginary machine that is implemented by emulating it in


software on a real machine. Code for JVM is stored in .class file. It is a specification that
provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.

Java Runtime Environment (JRE)

It is used to provide runtime environment. It is the implementation of JVM. It physically


exists. It contains set of libraries + other files that JVM uses at runtime.
Implementation of JVMs is also actively released by other companies besides Sun Micro
Systems.
Data Types:
Data type are the keyword which assign a type to a variable.

There are two data types available in Java


 Primitive Data Types
 Reference/Object Data Types

Primitive Data Types


Eight Primitive datatypes are predefined by the java.

Byte: Byte data type is an 8-bit signed two's complement integer

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

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

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

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

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

boolean
 boolean data type represents one bit of information
 There are only two possible values: true and false

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

Byte Code:
When the java program compile the source code is converted in intermediate code with
extension .class called, Byte Code which is read by the JVM machine.
 Byte code and JVM both makes java platform independent.
Tokens

 Each and every smallest individual unit in a program is known as tokens.


 Tokens are the basic buildings blocks in language which are constructed together to
write a program.
 The keywords, identifiers, constants, string literals, and operators are examples
of tokens. Punctuation characters such as brackets [ ], braces { }, parentheses ( ), and
commas (,) are also tokens.

1. Keywords

 Keywords are those words whose meaning is already defined by language


 There are 50 Keywords in java.
 Keywords are also called as reserved words.
 const and goto are two keywords which are reserved in java but not defined by java
language.

abstract continue goto package switch


assert default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extern int short try
catch final interface static void
char finally long stricfp volatile
class float native super while
const for new synchronized

2. Identifiers
Identifiers are the name given to various programming element like variable name, class
name, object name array name, function name interface name, package name.
Rules for constructing identifier name
 All the identifiers must start with either a letter (a to z or A to z) or currency
character ($) or an underscore.
 They can have alphabets, digits, and the underscore (_) and dollar sign ($)
characters.
 They must not begin with a digit.
 Identifiers in java are case sensitive abc and ABC are two different identifiers.
Uppercase and lowercase are distinct.
Naming conventions

1. When more than one word are used in a public methods and instance name, the
second and subsequent words are marked with a leading letters.
Examples: dayTemperature, firstDayOfMonth, totalMarks
2. All private and local variable use only lowercase letters combine with
underscores.
Examples: length, batch_strength
3. All classes and interface start with uppercase letter(and each subsequent word
with a leading uppercase)
Example: Student, HelloJava, Vehical, MotorCycle
4. Variables that represent constant values use all uppercase letter and
underscore between words.
Example: TOTAL, F_MAX, PRINCIPAL_AMOUNT
5. Package name should be in lowercase
Example: java, lang, sql, util, etc.
6. Method name should be in lowercase letters.
Example: print (), println().

3. Operator

Operator is the special symbols the perform the mathematical and logical manipulation.

Types of operator
1. Arithmetic operator

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

2. Relational operator

Relational Operators Meaning


< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to

3. Logical operator

Operators Meaning operation


|| OR a||b is true
&& AND a&&b is false
! NOT (!a) is false
4. Bitwise operator

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One ‘Complement
>> Bitwise right shift
<< Bitwise left Shift

1. Ternary operator
Operator that performs operation on three operands called ternary operator.

Conditional Operator
 The conditional operator? : is called ternary operator as it requires three
operands.
Syntax:
Conditional Exp? Exp1: Exp2
If the value of conditional expression is true then the exp1 is evaluated, otherwise exp2 is
evaluated.

2. Assignment operator
Operator ('=') which is used for assigning a value to a variable is called assignment
operator. This operator takes the expression on its right-hand-side and places it into
the variable on its left-hand-side.
For example: m = 5;

Operator Example Equivalent to


+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ = 2 A=A/2
*= A*=2 A=A*2

3. Increment or decrement operator


Operator which perform operation only on one operand are called Unary operator.

1. Increment Operator
++ Operator increment the value of a variable by 1 is called increment operator.
 Pre-increment
++ is written before variable name. Value is incremented first then
incremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=++a;
System.out.println(i);
}
}OUTPUT: 6
Post-increment
 ++ is written after variable name. Value is assigned to expression after that the
value is increment.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a++;
System.out.println(i);
}
}OUTPUT:5
2. Decrement Operator
-- Operator decrement the value of a variable by 1 is called decrement operator.
 Pre-decrement
-- is written before variable name. Value is decremented first then
decremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=--a;
System.out.println(i);
}
}OUTPUT: 4
 Post-decrement
-- is written after variable name. Value is assigned in expression then the
decrement the value.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a--;
System.out.println(i);
}
}OUTPUT:5

4. Separator
The separators define the structure of a program. The separators are used parentheses (
), braces { }, the period (.) and (;) semicolon.

Comments
Comments are special part of the program, to describe or explain the code which make
easy to understand.
Comments are those lines which are not read by the compilers.
Types of Comments
1. Single line comments
Single line comments starts with two forward slash (//)
It useful when only single lines are commented.
final int a=5// a is constants variable
2. Multiline comments
Multiline comments are starts with forward slash/ and after that star (*) and
the text or comment line put then again star(*) put the again forward slash(/)
put to comment .
It is useful when we comment multiple line in program.

Control flow statements.


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

1) If Statement:

 Simple if statement
 if-else statement
 if-else-if ladder
 Nested if-statement

1) Simple if statement:

Syntax
if(condition) {
statement 1; //executes when condition is true
}

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output: x + y is greater than 20

2) if-else statement

Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output: x + y is greater than 20

3) if-else-if ladder:

Syntax
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
}

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Output: Delhi

4. Nested if-statement

Syntax

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
}
}

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output: Delhi

Switch Statement:

The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Consider the following example to understand the flow of the switch statement.

Student.java

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:

Loop Statements

for loop
while loop
do-while loop

for loop

for(initialization, condition, increment/decrement) {


//block of statements
}

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output: The sum of first 10 natural numbers is 55

while loop

The syntax of the while loop is given below.

while(condition){
//looping statements
}

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}}}
Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10
do-while loop

do
{
//statements
} while (condition);

public class Calculation {


public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10

Jump Statements

break statement

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 BreakExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}}}}
Output:

0
1
2
3
4
5
6
continue statement

Consider the following example to understand the functioning of the continue statement in Java.

public class ContinueExample {

public static void main(String[] args) {


// TODO Auto-generated method stub

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

for (int j = i; j<=5; j++) {

if(j == 4) {
continue;
}
System.out.println(j);
} }}}
Output:

0
1
2
3
5
1
2
3
5
2
3
5

Arrays:-
 Array is a final class inheritance is not possible.
 Arrays are used to store the multiple numbers of elements of single type.
 The length of the array is established at the time of array creation. After creation the length is fixed.

single dimensional array declaration:-

int[] a;
int []a;
int a[];

declaration & instantiation & initialization :-

approach 1:- int a[]={10,20,30,40};


approach 2:- int[] a=new int[100];
a[0]=10;
a[1]=20;
a[2]=30;
a[4]=40;

Ex:-printing the array elements

class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
}
}

Ex:-printing the array elements by using for loop

class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}

declaration of two dimensional array:-


int[][] a;
int [][]a;
int a[][];
int []a[];

Ex:-
class Test
{
public static void main(String[] args)
{
int[][] a={{10,20,30},{40,50,60}};
System.out.println(a[0][0]);//10
System.out.println(a[1][0]);//40
System.out.println(a[1][1]);//50
}
}
OOP’s Concepts

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:

 Object
 Class
 Inheritance
 Abstraction
 Encapsulation
 Polymorphism

Class

 It is similar to structures in C language. A class is a group of objects which have


common properties. So, class is basically a blueprint for object.
 A class enclosed both the data and function that operate on the data, into a single
unit. The variable and function enclosed in a class are called member and member
functions respectively.

Object
 Objects are the basic unit of OOP. They are instances of class, which have data
members and use various member functions to perform tasks.
 Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class.

Class
“Class is a user defined data types, which holds variables and, which can be accessed and
used by creating instance of that class.”
Class is just a blue print, which declare and defined variables and methods. All objects
of this class will share these data member and function.
About Class:
1. Class name start with an uppercase letter. If class name is made then one word, the
first letter of each word must be in uppercase.
Ex: - Class Study, class AimsTutorial
2. Objects of the class holds separate copies of data member. We can create as many
objects of a class as we need.
How to declare class:
Syntax:
public class Class_Name
{
variables;
methods( );
public static void main(String[] args)
{
Class_Name obj=new Class_Name ()
}
};
Example:
public class Aims
{
int i=10;
public static void main(String[] args)
{
Aims a1=new Aims ();
System.out.println (a1.i);
}
}
Output: 10;

Objects
Objects are the variable which declare using class name, it holds the data variable, declared in
the class and the member function works on these class objects.

How to declare objects:


public class Abc
{
int x=10;
void display( )
{
System.out.println(x);
}

public static void main(String[] args)


{
Abc obj=new Abc();
Obj.display();
}
}
Output:10
 Each object has different data variables.
 Object are initialized using special methods are called constructor.

A class can contain any of the following variable types.

 Local variables − Variables which defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the method
and the variable will be destroyed when the method has completed.
class Test
{
public static void main(String[] args)
{
int a=10; Local variables
int b=20;
System.out.println(a+b);
}
}

 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
class Test
{
int a=10;
int b=20;
void add()
{
System.out.println (a+b);
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.a+t.b);
t.add();
}
}

Methods (behaviors):-
1) Methods are used to provide the business logic of the project.
2) The methods like a functions in C-language called functions, in java language is called
methods.
3) Inside the class it is possible to declare any number of methods based on the developer
requirement.
4) As a software developer while writing method we have to fallow the coding standards like
the method name starts with lower case letters if the method contains two words every inner
word also starts uppercase letter.
5) It will improve the reusability of the code. By using methods we can optimize the code.

Syntax:-
[modifiers-list] return-Type Method-name (parameter-list)throws Exception
Ex:-
public void m1()
public void m2(int a, int b)
Method Signature:-

The name of the method and parameter list is called Method Signature. Return type and
modifiers list not part of a method signature.
Ex:- m1(int a,int b)------Method Signature
m2(); ------------------Method signature
There are two types of methods:-
 Instance method
Method which are declare and defined inside a class and without static keyword and
called using object.
class Test
{
void display()
{
System.out.println("Aims Tutorial");
}

public static void main(String[] args)


{
Test t=new Test();
t.display();

}
}
 Static method
Method which are declare and defined inside a class and with static keyword and
called using classname.
class Test
{
Static void display ()
{
System.out.println ("Aims Tutorial");
}

public static void main(String[] args)


{

Test.display ();

}
}

Constructor
Constructor is a special type of method which has same as class that is used to initialize the
object. Constructor is called at the time of object creation. It constructs the value or provides
data for the object that is why it is known as constructor.

Rules for creating constructor


1. Constructor name must be same as its class name.
2. Constructor must have no return type.
Types of constructor
1. Default constructor.
A Constructor that have no parameter is known as default constructor.
Purpose of default constructor
 Default constructor provide the default value to the object 0,null etc depending on the
type.
class Bike
{
public static void main(String args[])
{
Bike b=new Bike();
}
Bike()
{
System.out.println(“Default constructor is created”);
}
}

2. Parameterized constructor.
A Constructor that has parameter is known as parameterized
constructor.
 Why use parameterized Constructor
 parameterized constructor provide the different values to the
distinct object

class Square
{
public static void main(String args[])
{
Square b=new Square (5);
}
Square(int n)
{
System.out.println(n*n);
}
}
this heyword:-
This keyword is used to represent
1. Current class variables.
2. Current class methods.
3. Current class constructors.

class Test
{
int a=10;
int b=20;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
}
public static void main(String[] args)
{
Test t=new Test();
t.add(100,200);
}
}

POLYMORPHISM
1) One thing can exhibits more than one form called polymorphism.
2) The ability to appear in more forms.
3) Polymorphism is a Greek word poly means many and morphism means forms.

Types of Polymorphism
1. Compile Time Polymorphism (Early binding, Static binding)
2. Run Time Polymorphism (Late binding, Dynamic binding)
Ex:-Method Overloading Ex:-Method Overriding

A. Method overloading ( Compile Time Polymorphism ,Early binding, Static binding)


 If any class has multiple method with same name but different parameters then they
are said to be overloaded.
 Function overloading allows to use the same name for different function to
performed either same or different action in the same class.
 Method overloading is usually used to enhance the readability of the program. If you
have to perform one single operation but with different number or types of
arguments, then you can simply overload the method There are two types of
method overloading in java
1. By Changing number of arguments
Class Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void add(int a, int b, int c)
{
System.out.prinln(a+b+c);
}
public static void main(String args[])
{
Cal C1=new Cal();
C1.add(2,4);
C1.add(2,3,4);
}
}
2. By having different types of arguments
Class Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void add(float a, float b)

{
System.out.prinln(a+b);
}
public static void main(String args[])
{
Cal C1=new Cal();
C1.add(2,4);
C1.add(2.5f,3.4f);
}
}

B. Method Overriding
 If we inherit a class into the derived class and provide a definition for one of the
base class’s method again. The method is said to be overriding.
 Requirement for method overriding
 Inheritance should be there. method overriding cannot be done within a class, for
this we require a derived class and a base class.
 method signature should be same in base class and derived class.
class Base
{

void show()
{
System.out.prinln(“Base Class”+”\t");

}
}

class Derived extends Base


{

void show()
{
System.out.prinln("Derived Class");
}
public static void main(String[]args)
{
Base B=new Base();
Derived D=new Derived();
B.show();
D.show();

}
}

Output:
Base Class
Derived Class
 In the above example, we are calling the overridden function using Base Class and Derived
Class object. Base class object call base class version of function and derived class’s object
call Derived class version of function.

Difference between method overloading and method overriding in java


There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

Method overriding is used to provide


Method overloading is used to increase the readability of the specific implementation of the
1)
the program. method that is already provided by its
super class.

Method overriding occurs in two classes


2) Method overloading is performed within class. that have IS-A (inheritance)
relationship.

In case of method overloading, parameter must be In case of method overriding,


3)
different. parameter must be same.

Method overloading is the example of compile time Method overriding is the example of
4)
polymorphism. run time polymorphism.
In java, method overloading can't be performed by
changing return type of the method only. Return type Return type must be same or covariant
5)
can be same or different in method overloading. But you in method overriding.
must have to change the parameter.

ABSTRACTION

Hiding the internal implementation details and highlighting the essential functionality to the
user this mechanism is called abstraction.
Ex:
a. Bank ATM Screens (Hiding thee internal implementation and highlighting set of services
like withdraw, money transfer, mobile registration).
b. Mobile phones (The mobile persons are hiding the internal circuit implementation and
highlighting touch screen).
Abstraction concepts are implemented in java by abstract class and interface
1. Abstract Class
Abstract class is a java class which contains at least one abstract method.
To specify the particular class is abstract and particular method is abstract method by
using abstract modifier.
For the abstract classes it is not possible to create an object. Because it contains the
unimplemented methods.
For any class if we don’t want instantiation then we have to declare that class as abstract
i.e., for abstract classes instantiation (creation of object) is not possible.
abstract class Test
{

abstract void m3();


}

Abstract class:-
class Test
{
abstract void m1();
abstract void m2();
abstract void m3();
}
abstract class Add
{
abstract void add(int a, int b);
}
class Cal extends Add
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Cal C1=new Cal();
C1.add(3,4);
}
}

Abstract methods:-
The method which is having declaration but not implementations such type of methods are
called abstract Method. Hence every abstract method should end with “;”.
The child classes are responsible to provide implementation for parent class abstract
methods.
public abstract Add
{
abstract void add(int a, int b);//it is abstract method which has no definition

}
class Cal
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Cal C1=new Cal();
C1.add(3,4);
}
}

2. Interface
1. Interface is also one of the type of class it contains only abstract methods.
2. For the interfaces also .class files will be generated.
3. Each and every interface by default abstract hence it is not possible to create an
object.
4. Interfaces not alternative for abstract class it is extension for abstract classes.
5. 100 % pure abstract class is called interface.
6. The Interface contains only abstract methods means unimplemented methods.
7. Interfaces giving the information about the functionalities it are not giving the
information about internal implementation.
8. To provide implementation for abstract methods we have to take separate class that
class we can called it as implementation class for that interface.
9. Interface can be implemented by using implements keyword.
10. For the interfaces also the inheritance concept is applicable.
Syntax:-
Interface interface-name
Ex:- interface it1
Note: -
if we are declaring or not By default interface methods are public abstract
interface it1 abstract interface it1
{ {
Void m1(); Both are same public abstract void m1();
Void m2(); public abstract void m2();
} }

interface Cal
{
void add(int a, int b);
void sub(int a, int b);
}
class Solution implements Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void sub(int a, int b)
{
System.out.prinln(a-b);
}
public static void main(String[] args)
{
Solution S1=new Solution()’
S1.add();
S1.sub();
}

Encapsulation
The process of binding the data and code as a single unit is called encapsulation.
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.
We are able to provide more encapsulations by taking the private data(variables) members.
To get and set the values from private members use getters and setters to set the data and to
get the data.

Example of Encapsulation in Java


1. //A Account class which is a fully encapsulated class.
2. //It has a private data member and getter and setter methods.
3. class Account {
4. //private data members
5. private long acc_no;
6. private String name,email;
7. private float amount;
8. //public getter and setter methods
9. public long getAcc_no() {
10. return acc_no;
11. }
12. public void setAcc_no(long acc_no) {
13. this.acc_no = acc_no;
14. }
15. public String getName() {
16. return name;
17. }
18. public void setName(String name) {
19. this.name = name;
20. }
21. public String getEmail() {
22. return email;
23. }
24. public void setEmail(String email) {
25. this.email = email;
26. }
27. public float getAmount() {
28. return amount;
29. }
30. public void setAmount(float amount) {
31. this.amount = amount;
32. }
33.
34. }
1. //A Java class to test the encapsulated class Account.
2. public class TestEncapsulation {
3. public static void main(String[] args) {
4. //creating instance of Account class
5. Account acc=new Account();
6. //setting values through setter methods
7. acc.setAcc_no(7560504000L);
8. acc.setName("Sonoo Jaiswal");
9. acc.setEmail("sonoojaiswal@javatpoint.com");
10. acc.setAmount(500000f);
11. //getting values through getter methods
12. System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.getAmount());
13. }
14. }

What is Garbage Collection?


In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a
certain point, sufficient memory may not be available to create new objects, and the entire
program will terminate abnormally, causing OutOfMemoryErrors.

But in Java, the programmer need not care for all those objects which are no longer in use.
Garbage collector destroys these objects. The main objective of Garbage Collector is to free
heap memory by destroying unreachable objects.

How Does Garbage Collection in Java works?


Java garbage collection is an automatic process. Automatic garbage collection is the process
of looking at heap memory, identifying which objects are in use and which are not, and
deleting the unused objects.

What is the destructor in Java?


It is a special method that automatically gets called when an object is no longer used. When
an object completes its life-cycle the garbage collector deletes that object and deallocates or
releases the memory occupied by the object.

Java finalize() Method


It is difficult for the programmer to forcefully execute the garbage collector to destroy the
object. But Java provides an alternative way to do the same. The Java Object class provides
the finalize() method that works the same as the destructor. The syntax of the finalize()
method is as follows:

Syntax:

protected void finalize throws Throwable()


{
//resources to be close
}
Parameter Passing Techniques
Parameter passing in Java refers to the mechanism of transferring data between methods or
functions. Java supports two types of parameters passing techniques

1. Call-by-value
2. Call-by-reference.

Call-by-value

In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }

Output:before change 50
after change 50

Use recursion to add all of the numbers up to 10.

public class Main {


public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0

Call-by-reference

public class A{
int d=50;
public void add(int d){
d=d+100;//These changes will happen locally, that means it will be reflected only in this function
System.out.println("The value in function after performing addition is " + d);
}
public static void main(String args[]){
A obj=new A();
System.out.println("before change "+obj.d);
obj.add(500);
System.out.println("after change "+obj.d);
}
}

The java command-line argument

The java command-line argument is an argument i.e. passed at the time of running the java program.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java program, you
must pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line. For this purpose, we
have traversed the array using for loop.
1. package com.journaldev.examples;
2.
3. public class CommandLineArguments {
4.
5. public static void main(String[] args) {
6. System.out.println("Number of Command Line Argument = "+args.length);
7.
8. for(int i = 0; i< args.length; i++) {
9. System.out.println(String.format("Command Line Argument %d is %s", i, args[i]));
10. }
11. }
12.
13. }
14. compile by > javac A.java
15. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

Scanner Class in Java



In Java, Scanner is a class in java.util package used for obtaining the input of the primitive
types like int, double, etc. and strings.
Using the Scanner class in Java is the easiest way to read input in a Java program,

import java.util.Scanner;

// Driver Class
public class ScannerDemo1 {
// main function
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);

// String input
String name = sc.nextLine();

// Character input
char gender = sc.next().charAt(0);

// Numerical data input


// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();

// Print the values to check if the input was


// correctly obtained.
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
System.out.println("Mobile Number: " + mobileNo);
System.out.println("CGPA: " + cgpa);
}
}

Input
Geek
F
40
9876543210
9.9
Output
Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9

You might also like