Core Java 1
Core Java 1
S A G AR S A R K A R
T E C H N I C A L F A C U L T Y - T A L E N T D E V E L O P ME N T - P UN E
B S @ IIT M A DRA S
S T R E AM S - C# , P YT H O N , J A VA , M A CH I N E L E A R N I N G , BI G D A T A , A Z U R E - I O T
Contents
Introduction.
JDK,JVM and JRE.
Variables
Data Types
Operator
Control Statements
OOPS Concept
Static and this Keyword
Package
Access Modifiers and Encapsulation
Method Overloading
Memory Allocation
Array
Introduction
Java is a programming language. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java.
Java was originally designed for interactive television, but it was too advanced technology for
the digital cable television industry at the time. However, it was suited for internet
programming.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".
Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc.
Types of Java Applications
1) Standalone Application
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate5 etc. technologies are used for creating web applications in Java.
3) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android is used for
creating mobile applications.
4) Embedded System
5) Smart Card
6) Robotics
Features of Java
Simple
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms.
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and
Run Anywhere(WORA)
Secured
Java is best known for its security. Java is secured because:
No explicit pointer that prohibits anyone to make any reference based modifications on data
Java Programs run inside a virtual machine sandbox
Robust
Robust simply means strong. Java is robust because:
It uses strong memory management and garbage collection system.
There are exception handling and the type checking mechanism in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI(Remote Method Injection) and EJB(Enterprise Java Beans) are used for creating distributed
applications.
This feature of Java makes us able to access files by calling the methods from any machine on
the internet.
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.
Threads are important for multi-media, Web applications, etc.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
Object-oriented
Java is an object-oriented programming language.
Everything in Java is an object. Object-oriented means we organize our software as a
combination of different types of objects that incorporates both data and behavior.
JDK,JRE and JVM
Java Development Kit (JDK) is a software development environment used for developing Java
applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader
(Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other
tools needed in Java development.
JRE (Java Runtime Environment) is an installation package that provides an environment to only
run(not develop) the java program(or application)onto your machine. JRE is only used by those
who only want to run Java programs that are end-users of your system.
JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is contained
or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is
responsible for executing the java program line by line, hence it is also known as an interpreter.
How does Java Program gets executed-[Link]
java-program/
Creating Hello World Example
class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
Parameters used in First Java Program
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main method is executed by the JVM, so it doesn't require to create an object to invoke
the main method.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument.
[Link]() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
int data=50;//Here data is variable
Data Type Default Value Default size
boolean False 1 bit
char 0 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is used for simple
flags that track true/false conditions.
Example: Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves
space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example: byte a = 10, byte b = -20
Short Data Type
Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller
than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about
memory.
Example: int a = 100000, int b = -200000
Long Data Type
Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -
1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0L. The long data type is used when you need a range of values
more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. Its default value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
Its value range is unlimited. The double data type is generally used for decimal values just like
float. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between ' (or 0) to (or
65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
Types of Operators
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Operator Type Category Precedence
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
default:
code to be executed if all cases are not matched;
}
While Loop
The Java 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.
Syntax:
while(condition){
//code to be executed
}
Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){
//code to be executed
Example:
while(true){
}
Java do-while Loop
The 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 loop at 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);
Java Infinitive do-while Loop
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while
loop.
Syntax:
jump-statement;
break;
Java Continue Statement
The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In case of an inner loop, it
continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-
while loop.
Syntax:
jump-statement;
continue;
Comments
The Java comments are the statements that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable,
method, class or any statement. It can also be used to hide program code.
There are three types of comments in Kava.
Single Line Comment
Multi Line Comment
Documentation Comment
Java Documentation Comment
The documentation comment is used to create documentation API.
Syntax:
1./**
[Link]
[Link]
[Link]
[Link]
6.*/
Example:
1./** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
[Link] class Calculator {
3./** The add() method returns addition of given numbers.*/
[Link] static int add(int a, int b){return a+b;}
5./** The sub() method returns subtraction of given numbers.*/
[Link] static int sub(int a, int b){return a-b;}
7.}
Now, there will be HTML files created for your Calculator class in the current directory.
OOPs Concepts
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology to design a program using classes and objects.
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class.
An object contains an address and takes up some space in memory.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
[Link] provides code [Link] is used to achieve runtime polymorphism
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to draw
something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
We use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Coupling
Coupling refers to the dependency of another class. It arises when classes are aware of each
other. If a class has the details information of another class, there is strong coupling. In Java, we
use private, protected, and public modifiers to display the visibility level of a class, method, and
field. You can use interfaces for the weaker coupling because there is no concrete
implementation.
Advantage of OOPs over Procedure-oriented
programming language
0
null
3 Ways to initialize object
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
Object and Class Example: Initialization
through reference
Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
File: [Link]
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
[Link]=101;
[Link]="Sonoo";
[Link]([Link]+" "+[Link]);//printing members with a white space
}
}
Output:
101 Sonoo
Object and Class Example: Initialization
through method
In this example, we are creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan
Object and Class Example: Initialization
through a constructor
Eclipse-TestEmployee
TestAccount
Creating multiple objects by one type only
class Student4{
int id;
String name;
id = i;
name = n;
The Java compiler provides a default The method is not provided by the compiler in
constructor if you don't have any constructor any case.
in a class.
The constructor name must be same as the The method name may or may not be same as
class name. the class name.
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than
an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Java static variable
The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
The static variable gets memory only once in the class area at the time of class loading.
It makes your program memory efficient (i.e., it saves memory).
Static variable1
Understanding the problem without static
variable
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.
Java static property is shared to all objects.
Another example of a static method that
performs a normal calculation
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
class A{
int a=40;//non static
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is
not possible to execute a Java class without the main method.
class A3{
static{
[Link]("static block is invoked");
[Link](0);
}
}
this keyword in java
There can be a lot of usage of java this keyword.
In java, this is a reference variable that refers to the current object
Usage of java this keyword
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Example testStatic1
this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example
class A{
void m(){[Link](“Hello m");}
void n(){
[Link]("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output
Hello n
Hello m
this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
Calling default constructor from parameterized constructor-teststatic5
Calling parameterized constructor from default constructor-teststatic6
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining.
Testthis7
this: to pass as an argument in the method
Example s2
this: to pass as argument in the constructor
call
Exampel A4
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this,
output of both variables are same.
class A5{
void m(){
[Link](this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
[Link](obj);//prints the reference ID
obj.m();
}
}
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
1) [Link]: Contains language support classes(e.g classes which defines primitive data types, math
operations). This package is automatically imported.
2) [Link]: Contains classed for supporting input / output operations.
3) [Link]: Contains utility classes which implement data structures like Linked List, Dictionary and
support .
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
How to access package from another
package?
There are three ways to access the package from outside the package.
import package.*;
import [Link];
fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Using [Link]
If you import [Link] then only declared class of this package will be accessible.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Access Modifiers
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
There are four types of Java access modifiers:
Access Modifier within class within package outside package by outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
If you make any class constructor private, you cannot create the instance of that class from
outside the class
A class cannot be private or protected
Default
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
//save by [Link]
package mypack;
import pack.*;
class B{
}
It provides more accessibility than private.
But, it is more restrictive than protected and public.
Public
/save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
} //save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Protected
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B extends A{
[Link]();
}
Java Access Modifiers with Method Overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
class A{
protected void msg(){[Link]("Hello java");}
}
public class Simple extends A{
void msg(){[Link]("Hello java");}//[Link]
public static void main(String args[]){
Simple obj=new Simple();
[Link]();
}
}
Encapsulation
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
Advantage of Encapsulation in Java
By providing only a setter or getter method, you can make the class read-only or write-only. In
other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should
be greater than 100 only, you can write the logic inside the setter method. You can write the
logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and
fast to create an encapsulated class in Java.
Simple Example of Encapsulation in Java
Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.
File: [Link]
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package [Link];
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
[Link]=name
}
}
File: [Link]
//A Java class to test the encapsulated class.
package [Link];
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
[Link]("vijay");
//getting value of the name member
[Link]([Link]());
}
}
Output:
vijay
Read-Only class
//A Java class which has only getter methods.
public class Student{
//private data member
private String college="AKG";
//getter method for college
public String getCollege(){
return college;
}
}
Now, you can't change the value of the college data member which is "AKG".
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
Output:
22
33
Method Overloading: changing data type of
arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}
Output:
22
24.9
Why Method Overloading is not possible by
changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because
of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
[Link]([Link](11,11));//ambiguity
}}
Output-Compile Time Error-method add(int,int) is already defined in the Adder Class
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
class TestOverloading4{
public static void main(String[] args){[Link]("main with String[]");}
public static void main(String args){[Link]("main with String");}
public static void main(){[Link]("main without args");}
}
Output-main with String[]
Method Overloading and Type Promotion
Example of Method Overloading with
TypePromotion
class OverloadingCalculation1{
void sum(int a,long b){[Link](a+b);}
void sum(int a,int b,int c){[Link](a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
[Link](20,20);//now second int literal will be promoted to long
[Link](20,20,20);
}
}
Output:40
60
Example of Method Overloading with Type
Promotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2{
void sum(int a,int b){[Link]("int arg method invoked");}
void sum(long a,long b){[Link]("long arg method invoked");}
class OverloadingCalculation3{
void sum(int a,long b){[Link]("a method invoked");}
void sum(long a,int b){[Link]("b method invoked");}