Core Java
Core Java
Java Introduction
• Example:
• person taking red carpet with him and instead of walking on floor,
he always walks on red carpet, no matter where he is walking.
That red carpet is the JVM, your Java program runs on JVM rather
on any particular platform or machine.
How byte code work?
What is JVM, JRE & JDK
JVM
• java Virtual Machine (JVM) is an abstract computer machine
that is responsible for executing java byte code.
• The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
JRE & JDK
class class-name {
public static void main(String args[]) {
statement1;
statement2;
…
…
}
}
Example Program
“First.java”
class First {
}
Compiling & Running the Program
• double
Numbers with decimal point
like 12.453, 3.432, 0.0000002
• Characters
‘a’, ‘A’, ‘c’ , ‘?’ , ‘3’ , ‘ ’
(last is the single space)
• Enclosed in single quotes
• Character variable declaration
char ch;
• Character assignment
ch = ‘k’;
*******
*****
***
*
***
*****
*******
**********
* *
* *
* *
**********
if(condition){
//code to be executed
}
Java if-else Statement
• The Java if-else statement also tests the condition. It executes
the if block if condition is true otherwise else block is executed.
• Syntax
if(condition){
//code if condition is true
}
else{
//code if condition is false
}
Java if-else-if ladder
• The if-else-if ladder statement executes one condition from multiple
statements.
• Syntax
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
Java Switch Statement
• The Java switch statement executes one statement from
multiple conditions. It is like if-else-if ladder statement.
switch(expression){
case value1:statement;
break;
case value2:statement;
break;
default:
//code to be executed if all cases are not matched;
}
Type Conversion/Casting
• Type Conversion or Type Casting is the process of converting a
variable of one predefined type into another. If these data types
are compatible with each other, the compiler automatically
converts them and if they are not compatible, then the
programmer needs to typecast them explicitly
1.Implicit (Automatic) Type Conversion
2.Explicit Type Conversion
Implicit Type Conversion
• Implicit Type Conversion or Automatic type conversion is a
process of automatic conversion of one data type to another by
the compiler, without involving the programmer.
• This process is also called Widening Conversion because the
compiler converts the value of smaller size into a value of a
larger size data type without loss of information.
Conversions:
• Byte(size 1 byte) ——— is convertible to ————-> short, int,
long, float, or double
Short(2 byte) ——— is convertible to ————-> int, long, float,
or double
char(2 byte) ——— is convertible to ————-> int, long, float,
or double
int (4 byte)——— is convertible to ————-> long, float, or
double
long (8 byte)——— is convertible to ————-> float or double
float(4 byte)——— is convertible to ————-> double
Example:
int intVariable = 25;
long longVariable = intVariable;
float floatVariable = longVariable;
double doubleVariable = floatVariable;
System.out.println("Integer value is: " +intVariable);//25
System.out.println("Long value is: " +longVariable);//25
System.out.println("Float value is: " +floatVariable);//25.0
System.out.println("Double value is: " +doubleVariable);//25.0
Explicit Type Conversion
44
For Loop
• The Java 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.
• Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
e.g
For(i=1;i<=5;i++)
{
Sop(“Hello”);
}
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
}
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.
do{
//code to be executed
}while(condition);
Java Break
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Array of Objects in Java
• Java is an object-oriented programming language. Most of the
work done with the help of objects. We know that an array is a
collection of the same data type that dynamically creates
objects and can have elements of primitive types.
• An array that conations class type elements are known as
an array of objects.
• Syntax:
54
Object
• Object: A real-world entity that has state and behavior is called
object in java. Here, state represents properties and behavior
represents actions and functionality. For example, a person,
chair, pen, table, keyboard, bike, etc.
• The object is an instance of a class.
Class
• Class: A class is basically user-defined data types. It
represents the common properties and actions (functions) of an
object.
• For example, bus and car are objects of vehicle class. Sparrow
and parrot are objects of birds class. Similarly, MS Dhoni,
Sachin Tendulkar, and Virat Kohali are objects of cricketer
class.
Syntax:
Class:
• <access-modifier> class <ClassName>
•{
• //Class body containing variables and methods
•}
• Object:
• ClassName objectName = new ClassName();
Methods in Java
• method is a way to perform some task. Similarly, the method in
Java is a collection of instructions that performs a specific task.
It provides the reusability of code. We can also easily modify
code using methods.
• The main() method is the first method that is executed by JVM
(Java Virtual Machine) in java program.
Method Declaration
Constructor in Java
class Demo{
static{
System.out.println(“this is static block");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Can we execute a program without main() method?
• 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{
System.out.println("static block is invoked");
}
}
What is Inheritance?
• Inheritance is one of the main four pillars (core concepts) of
OOPs (Object Oriented Programming) concepts in Java. It is a
technique of organizing information in a hierarchical form.
• Inheritance is a mechanism in which one class acquires the
property of another class. For example, a child inherits the traits
of his/her parents. With inheritance, we can reuse the fields and
methods of the existing class.
Class A Class B
Class C
Package
• PACKAGE in Java is a collection of classes, sub-packages,
and interfaces. It helps organize your classes into a folder
structure and make it easy to locate and use them. More
importantly, it helps improve code reusability.
• 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.
• E.g package Demopkg2;
• package Demopkg;
import Demopkg.*;
public class B {
• public class A {
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Use of Wrapper classes in Java
• Java is an object-oriented programming language, so we need
to deal with objects many times like in Collections,
Synchronization, etc.
1) Synchronization: Java synchronization works with objects in
Multithreading.
2) Collection Framework: Java collection framework works with
objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
Primitive to Wrapper
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
• The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class.
• There are four types of Java access modifiers:
1.Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
2.Default: The access level of a default modifier is only within
the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the
default.
3.Protected: The access level of a protected modifier is within
the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.
4.Public: The access level of a public modifier is everywhere.
It can be accessed from within the class, outside the class,
within the package and outside the package.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
The protected access modifier is accessible within package and outside the package
but through inheritance only.
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method of
this package is declared as protected, so it can be accessed from outside the class only
through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
Encapsulation in Java
• The process of binding data and corresponding methods
(behavior) together into a single unit is called encapsulation in
Java.
• Every Java class is an example of encapsulation because we
write everything within the class only that binds variables and
methods together.
• Realtime Example 1:
School bag is one of the most real examples of Encapsulation.
School bag can keep our books, pens, etc.
package encapPrograms;
public class Student
{
private String name;
public String getName()
{
return name;
}
public void setName(String studentName)
{
name = studentName;
}
}
• 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.
• Private variable can only be accessed within the same
class(an outside class has no access to it).
• It is possible to access them if we provide public get and
set method.
• get method returns the variable value and set method sets
the value.
class EncapsulationTest
{
public static void main(String[] args)
{
Student obj = new Student();// Creating object of Student class
by using new keyword.
obj.setName("Amit"); // setting the value of variable.
String studentName = obj.getName(); // reading the value of
variable.
System.out.println(studentName);
}
}
Solve Ex:
Customer
TestClass
Al member
private
Id Access all
Name members of
Age
customer class
Phone no
getter/setter
• Polymorphism in java is one of the core concepts of object-oriented
programming language. The word polymorphism is derived from two
Greek words: poly and morphs.
Aggregation
• Aggregation represents HAS-A relationship.
• which means when a class contains reference of another class
known to have aggregation.
Student
Name
Address
Address
City
State
country
• Solve this one
Book
Name
Price
Author
author
Author name
Age
place
Java String
Java String is basically an array of characters.
The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
By string literal
String s="welcome";
By new keyword
String s=new String("Welcome")
Immutable String in Java
• When a string is created using string literals, jvm checks if the string
object is already present in the string constant pool or not.
• If the object is not present, then jvm creates a new object, else if the
object is already present, jvm creates a new reference to the previous
object.
Java String compare
There are three ways to compare string in java:
1) By equals() method
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
2) By = = operator
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3)
/false(because s3 refers to instance created in nonpool)
compareTo() method
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}
Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable)
string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
3. Error in Java
Error is not an exception but it is an issue that emerges out of the control of
the user or the developer. VirtualMachineError,
Keyword Description
void m(){
throw new ArithmeticException("sorry");
}
//method code
}
Java throw and throws example
void m()throws ArithmeticException{
}
Nested Classes
• A class created inside another class in known as nested or inner
class.
• It is a way of grouping classes that are used only at one place.
• Using nested classes increases encapsulation and creates more
readable and maintainable code.
Types of nested class
A static inner class is like any other static member of class (Common
for all instances).
• Static inner class can access only the static members of class (can
be private).
• Static methods can be declared inside a static inner class.
Member inner class :
CPU It is not guaranteed that Daemon User thread always gets preference in
availability thread always gets CPU usage getting CPU usage because of its
2 whenever it requires due to its low higher priority.
priority.
Creation Daemon threads are executed in the While user thread is usually created by
background state so generally named the application for executing some
3
as background threads. tasks concurrently.
Execution Daemon threads are executed in the User threads are called foreground
Ground background state so generally named threads on another hand.
4
as background threads.
What is File Handling in Java?