Corejava Slides
Corejava Slides
Corejava Slides
}
Java Constructors Explained
A constructor is a special method in Java. It is called when an instance of object is created and
memory is allocated for the object. It is called constructor because it constructs the values at the time
of object creation.
Default Constructor
A constructor that has no parameter is known as default constructor. If we don’t define a constructor
in a class, then compiler creates default constructor(with no arguments) for the class.
Default constructor example
public class MyClass {
int number;
public MyClass() {
System.out.println("Constructor Called");
number=5;
}
public static void main(String[] args) {
}
}
}
CODE: static Class in Java
class JavaExample
{
private static String str = "TNS Java Sessions";
static class MyNestedClass
{
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
Arrays in Java with Program Examples
Arrays in Java are a group of like-typed variables that are referred to by a common name.
Array is a collection of similar type of elements that have contiguous memory location.
• Arrays in Java are Objects.
• In Java all arrays are dynamically allocated.(discussed below)
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• In case of primitives data types, the actual values are stored in contiguous memory locations.
• In case of objects of a class, the actual objects are stored in heap segment.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Single Dimensional Arrays
Creating, Initializing, and Accessing an Array
The general form of a one-dimensional array declaration is
type var-name[];
OR
type[] var-name;
Instantiating an Array in Java
int intArray[]; //declaring array int[] intArray = new int[20]; // combining both statements in one
intArray = new int[20]; // allocating memory to array
class Testarray {
public static void main(String args[]) {
//printing array
for (int i = 0; i < a.length; i++) //length is the property of array
System.out.println(a[i]);
}
}
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
class Student // Elements of array are objects of a class // so on...
{ Student. arr[2] = new
public class GFG Student(3,"shikar");
public int roll_no;
{ arr[3] = new
public String name; public static void main (String[] args) Student(4,"dharmesh");
Student(int roll_no, String name) { arr[4] = new
{
// declares an Array of integers. Student(5,"mohit");
Student[] arr;
this.roll_no = roll_no; // accessing the elements of
this.name = name; // allocating memory for 5 objects of type the specified array
} Student. for (int i = 0; i < arr.length; i++)
arr = new Student[5]; System.out.println("Element
}
at " + i + " : " +
// initialize the first elements of the array arr[i].roll_no +" "+
arr[0] = new Student(1,"aman"); arr[i].name);
}
// initialize the second elements of the }
array
arr[1] = new Student(2,"vaibhav");
Java Multi Dimensional Arrays
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
2-D Array in Java Example Program
class multiDimensional
{
public static void main(String args[])
{
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Jagged array in java is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D
arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays.
// Program to demonstrate 2-D jagged array in Java
class Main
// Displaying the values of 2D Jagged array
{ System.out.println("Contents of 2D
public static void main(String[] args) Jagged Array");
{ for (int i=0; i<arr.length; i++)
// Declaring 2-D array with 2 rows {
int arr[][] = new int[2][];
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
// Making the above array Jagged
System.out.println();
// First row has 3 columns }
arr[0] = new int[3]; }
// Second row has 2 columns }
arr[1] = new int[2];
// Initializing array Contents of 2D Jagged Array
int count = 0; 012
for (int i=0; i<arr.length; i++) 34
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
Java Single Inheritance Program Example –
class Animal class TestInheritance
{ {
void eat() public static void main(String args[])
{
{
Dog d=new Dog();
System.out.println("eating...");
d.bark();
}
d.eat();
} }
class Dog extends Animal }
{
void bark()
{
System.out.println("barking...");
}
}
Single Level Inheritence – Program 2
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Java Multilevel Inheritance Program Example –
class Animal {
class TestInheritance2 {
void eat() { public static void main(String args[]) {
System.out.println("eating..."); BabyDog d = new BabyDog();
} d.weep();
} d.bark();
d.eat();
class Dog extends Animal {
}
void bark() {
}
System.out.println("barking...");
}
}
class BabyDog extends Dog {
void weep() {
System.out.println("weeping...");
}
}
Multilevel Inheritence – Example2 Class SubClass2 extends SubClass1
{
Class SuperClass public void methodC()
{ {
public void methodA()
System.out.println("SubClass2");
}
{
public static void main(String args[])
System.out.println("SuperClass"); {
} SubClass2 obj = new SubClass2();
} SubClass2.methodA(); //calling super class
Class SubClass1 extends SuperClass method
{
SubClass2.methodB(); //calling subclass 1
method
public void methodB()
SubClass2.methodC(); //calling own method
{
}
System.out.println("SubClass1 "); }
}
}
Java Hierarchial Inheritance Program Example –
class Animal { class TestInheritance3 {
void eat() { public static void main(String args[]) {
System.out.println("eating..."); Cat c = new Cat();
}
c.meow();
c.eat();
}
//c.bark();//C.T.Error
class Dog extends Animal { }
void bark() { }
System.out.println("barking...");
}
}
class Cat extends Animal {
void meow() {
System.out.println("meowing...");
}
}
Java Hierarchial Inheritance Program Example –2
Class A Class C extends A
{
{
public void methodC()
public void methodA() {
{ System.out.println("Sub class Method C");
System.out.println("Super class method"); }
}
public static void main(String args[])
{
}
A obj1 = new A();
Class B extends A B obj2 = new B();
{ C obj3 = new C();
public void methodB() obj1.methodA(); //calling super class method
obj2.methodA(); //calling A method from subclass
{
object
System.out.println("Sub class Method B"); obj3.methodA(); //calling A method from subclass
} object
} }
}
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A
and B classes have same method and you call it from child class object, there will be ambiguity to
call method of A or B class.
In C++ we have virtual keyword to tackle this ambiguity however, in Java Multiple Inheritance is
possible only via Interfaces.
Java Even Odd Program Code Example –
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");
class LargestOfThreeNumbers
int x, y, z;
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
else
}
Swapping of 2 Variables using 3rd Variable in C++
#include <iostream>
using namespace std;
int main() {
int a,b,c;
cout<<"Enter value of a: ";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
cout<<"Before Swapping: a: "<<a<<" b: "<<b<<endl;
// start: swapping logic
c=a;
a=b;
b=c;
// end: swapping logic
cout<<"After Swapping: a: "<<a<<" b: "<<b<<endl;
return 0;
}
Swapping of 2 Variables Without using 3rd Variable in C++
#include <iostream>
using namespace std;
int main() {
int a,b;
int num = 4;
int factorial =1;
for(int i = num; i>0; i--)
{
factorial = factorial *i;
}
System.out.println("Factorial is: "+factorial);
}
}
Java program to Find if a Number is PALINDROME or not –
package javaapplication4;
int num=121;
int temp=num;
int rev = 0;
while(num>0)
rev = rev*10;
num = num/10;
if(temp == rev)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
Java Program to Print FIBONACCI Series using FOR LOOP
// 0 + 1 + 1 + 2 + 3 + 5 + 8 +
package javaapplication4;
public class JavaApplication4 {
public static void main(String[] args) {
int a = 0;
int b = 1;
int c;
for(int i = 0; i<5 ; i++)
{
System.out.print(a+" ");
c = a+b;
a=b;
b=c;
}
}
}
Polymorphism in Java – Method Overloading | Method Overriding
• Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many and “morphs” means forms.
So Polymorphism means the ability to take many forms.
• Polymorphism is a concept by which we can perform a single task in different ways.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Packages Example Step 2: import pack.*;
Step1 : package pack; import Subpackage.*;
public class A{ class B{
public void msg(){System.out.println("Hello");} public static void main(String args[]){
A obj = new A();
}
C obj1 = new C();
Step 1.1 package pack; D obj2 = new D();
public class C { obj.msg();
public void msg() obj1.msg();
{ obj2.msg();
System.out.println("Hello C"); }
}
}
}
Step 1.3 package Subpackage;
public class D {
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Abstract Methods
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract void disp();
1. In Java, an instance of an abstract class cannot be created, we can have references of abstract class type though.
Example
import java.io.File; // Import the File class
Categories of Exceptions
• Checked exceptions
• Unchecked exceptions
• Errors
Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at
compilation-time, these are also called as compile time exceptions.
For example: if you use FileReader class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to
handle the exception.
import java.io.File; C:\>javac FilenotFound_Demo.java
import java.io.FileReader; FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be
thrown
public class FilenotFound_Demo { FileReader fr = new FileReader(file);
^
1 error
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of
an API.
public class Unchecked_Demo {
}
Java catch multiple exceptions
public class MultipleCatchBlock2 {
public class MultipleCatchBlock1 {
public static void main(String[] args) {
public static void main(String[] args) {
try{
try{ int a[]=new int[5];
int a[]=new int[5];
a[5]=30/0; System.out.println(a[10]);
} }
catch(ArithmeticException e) catch(ArithmeticException e)
{ {
System.out.println("Arithmetic Exception occurs"); System.out.println("Arithmetic Exception occurs");
} }
catch(ArrayIndexOutOfBoundsException e) catch(ArrayIndexOutOfBoundsException e)
{ {
System.out.println("ArrayIndexOutOfBounds System.out.println("ArrayIndexOutOfBounds
Exception occurs"); Exception occurs");
} }
catch(Exception e) catch(Exception e)
{ {
System.out.println("Parent Exception occurs"); System.out.println("Parent Exception occurs");
} }
System.out.println("rest of the code"); System.out.println("rest of the code");
} }
} }
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java Nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
class Excep6{
public static void main(String args[]){
going to divide
try{
java.lang.ArithmeticException: / by zero
try{
java.lang.ArrayIndexOutOfBoundsException: Index
System.out.println("going to divide");
5 out of bounds for length 5
int b =39/0;
other statement
normal flow..
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Case 1: exception doesn't occur. Case 2: exception occurs and not handled.
class TestFinallyBlock{ class TestFinallyBlock1{
public static void main(String args[]){ public static void main(String args[]){
try{ try{
int data=25/5; int data=25/0;
System.out.println(data); System.out.println(data);
} }
catch(NullPointerException e){System.out.println(e);} catch(NullPointerException e)
finally{System.out.println("finally block is always {System.out.println(e);}
executed");} finally{System.out.println("finally block is always
System.out.println("rest of the code..."); executed");}
} System.out.println("rest of the code...");
} }
}
Output: Output:
5
finally block is always executed
finally block is always executed
rest of the code... Exception in thread main
java.lang.ArithmeticException:/ by zero
Case 3: exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
int a = 5;
// converts into object
Integer aObj = a;
double b = 5.6;
// converts into object
Double bObj = b;
This process is known as auto-boxing
Unboxing
It is just the reverse process of autoboxing. Converting an object of a wrapper class to its corresponding primitive type is
known as unboxing.
The Java compiler applies unboxing when an object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the corresponding primitive type.
• Wrapper Objects into Primitive Types
class Main {
public static void main(String[] args) { Output
// runs perfectly
ArrayList<Integer> list = new ArrayList<>();
Typecasting in Java
• Typecasting in Java is assigning a value of one type to a variable of another type. When you assign value of one data type to
another, the two types might not be compatible with each other.
• If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion
(Widening ) and if not then they need to be casted or converted explicitly(narrowing).
2 types of Type Casting in java
• Automatic Type Conversion (Widening – implicit)
• Narrowing (Explicit)
• Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens when:
• The two data types are compatible.
• When we assign value of a smaller data type to a bigger data type.
class Test
{
public static void main(String[] args) Output
{ Int value 100
int i = 100; Long value 100
//automatic type conversion Float value 100.0
long l = i;
• if statement
if(condition){
• if-else statement
//code to be executed
• if-else-if ladder }
• nested if statement
Java if Statement
• The Java if statement tests the condition. It executes the if block if condition is true.