Core Java Tutorial Latest

Core Java Tutorial Latest

1. Java JVM, JDK and JRE

Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to execute java byte code. The JVM doesn't understand Java typo, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM.

JVM control execution of every Java program. It enables features such as automated exception handling, Garbage-collected heap.

No alt text provided for this image

Class Loader : Class loader loads the Class for execution.

Method area : Stores pre-class structure as constant pool.

  • Heap : Heap is a memory area in which objects are allocated.
  • Stack : Local variables and partial results are store here. Each thread has a private JVM stack created when the thread is created.
  • Program register : Program register holds the address of JVM instruction currently being executed.
  • Native method stack : It contains all native used in application.
  • Executive Engine : Execution engine controls the execute of instructions contained in the methods of the classes.
  • Native Method Interface : Native method interface gives an interface between java code and native code during execution.
  • Native Method Libraries : Native Libraries consist of files required for the execution of native code.

Difference between JDK and JRE

JRE : The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

JDK : The JDK also called Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.

2. First Java Program

Creating a Hello World Program in Java is not a single line program. It consists of various other lines of code. Since Java is a Object-oriented language so it require to write a code inside a class. Let us look at a simple java program.

class Hello
{
  	public static void main(String[] args)
  	{
     	System.out.println ("Hello World program");
  	}
}        

Lets understand what above program consists of and its keypoints.

class : class keyword is used to declare classes in Java

public : It is an access specifier. Public means this function is visible to all.

static : static is again a keyword 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 : It is the 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 the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error.

String[] args : This represents an array whose type is String and name is args. We will discuss more about array in Java Array section.

System.out.println : This is used to print anything on the console like printf in C language.

3. Variable in Java

In this tutorial we will learn about Java variables, various types of variables along with code examples to understand Java variables.

What is a Variable?

When we want to store any information, we store it in an address of the computer. Instead of remembering the complex address where we have stored our information, we name that address. The naming of an address is known as variable. Variable is the name of memory location.

In other words, variable is a name which is used to store a value of any type during program execution.

To declare the variable in Java, we can use following syntax


datatype variableName;        

Here, datatype refers to type of variable which can any like: int, float etc. and variable Name can be any like: empId, amount, price etc.

Java Programming language defines mainly three kind of variables.

  1. Instance Variables
  2. Static Variables (Class Variables)
  3. Local Variables

4. Data Types in Java

Java language has a rich implementation of data types. Data types specify size and the type of values that can be stored in an identifier.

In java, data types are classified into two categories :

  1. Primitive Data type
  2. Non-Primitive Data type

4. 1) Primitive Data type

A primitive data type can be of eight types :

Primitive Data types char boolean byte short int long float double Once a primitive data type has been declared its type can never change, although in most cases its value can change. These eight primitive type can be put into four groups

4.2) Non-Primitive(Reference) Data type

A reference data type is used to refer to an object. A reference variable is declare to be of specific and that type can never be change.

For example: String str, here str is a reference variable of type String. String is a class in Java. We will talk a lot more about reference data type later in Classes and Object lesson.

Reference type are used to hold reference of an object. Object can be instance of any class or entity.

In object oriented system, we deal with object that stores properties. To refer those objects we use reference types.

We will talk a lot more about reference data type later in Classes and Object lesson.

Identifiers in Java

All Java components require names. Name used for classes, methods, interfaces and variables are called Identifier. Identifier must follow some rules. Here are the rules:

  • All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an underscore.
  • After the first character, an identifier can have any combination of characters.
  • Java keywords cannot be used as an identifier.
  • Identifiers in Java are case sensitive, foo and Foo are two different identifiers.

Some valid identifiers are: int a, class Car, float amount etc.

5. Static Block in Java

In Java, the static keyword is used for the management of memory mainly. the static keyword can be used with Variables, Methods, Block and nested class. A static block in a program is a set of statements which are executed by the JVM (Java Virtual Machine) before the main method. At the time of class loading, if we want to perform any task we can define that task inside the static block, this task will be executed at the time of class loading. In a class, any number of a static block can be defined, and this static blocks will be executed from top to bottom.

No alt text provided for this image
class StaticDemo1
{
	static
	{
		System.out.println("Welcome to studytonight.com");
		System.out.println("This is static block");

	}

	public static void main(String as[])
	{
		System.out.println("This is main() method");
	}
}        

6. Different ways to create objects in Java

Java is an object-oriented language, everything revolve around the object. An object represents runtime entity of a class and is essential to call variables and methods of the class.

To create an object Java provides various ways that we are going to discuss in this topic.

  1. New keyword
  2. New instance
  3. Clone method
  4. Deserialization
  5. NewInstance() method

7. What is OOPS

OOPS is a programming approach which provides solution to real life problems with the help of algorithms based on real world. It uses real world approach to solve a problem. So object oriented technique offers better and easy way to write program then procedural programming languages such as C, ALGOL, PASCAL etc. Click here to watch video on OOPS concept in Java

Java is an object oriented language which supports object oriented concepts like: class and object. In OOPS data is treated important and encapsulated within the class, object then use to access that data during runtime.

OPS provides advantages over the other programming paradigm and include following features.

Main Features of OOPS

  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction

8. Constructors in Java

A constructor is a special method that is used to initialize an object. Every class has a constructor either implicitly or explicitly.

If we don't declare a constructor in the class then JVM builds a default constructor for that class. This is known as default constructor.

A constructor has same name as the class name in which it is declared. Constructor must have no explicit return type. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

Default Constructor

In Java, a constructor is said to be default constructor if it does not have any parameter. Default constructor can be either user defined or provided by JVM.

If a class does not contain any constructor then during runtime JVM generates a default constructor which is known as system define default constructor.

If a class contain a constructor with no parameter then it is known as default constructor defined by user. In this case JVM does not create default constructor.

The purpose of creating constructor is to initialize states of an object.

Constructor Overloading

Like methods, a constructor can also be overloaded.

Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters.

Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you have multiple constructor with different signature but only difference is that constructor doesn't have return type.

Constructor Chaining

Constructor chaining is a process of calling one constructor from another constructor in the same class. Since constructor can only be called from another constructor, constructor chaining is used for this purpose.

To call constructor from another constructor this keyword is used. This keyword is used to refer current object.

Lets see an example to understand constructor chaining.

  
class Test
{

 Test()
 {
  this(10);
 }

 Test(int x)
 {
  System.out.println("x="+x);
 }

public static void main(String arg[])
{

Test object = new Test();
}

}
          

Private Constructors

In Java, we can create private constructor to prevent class being instantiate. It means by declaring a private constructor, it restricts to create object of that class.

Private constructors are used to create singleton class. A class which can have only single object known as singleton class.

In private constructor, only one object can be created and the object is created within the class and also all the methods are static. An object can not be created if a private constructor is present inside a class. A class which have a private constructor and all the methods are static then it is called Utility class.

9. Access Modifiers in Java

Access modifiers are keywords in Java that are used to set accessibility. An access modifier restricts the access of a class, constructor, data member and method in another class.

Java language has four access modifier to control access level for classes and its members.

  • Default: Default has scope only inside the same package
  • Public: Public has scope that is visible everywhere
  • Protected: Protected has scope within the package and all sub classes
  • Private: Private has scope only within the classes

Java also supports many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient etc.

10. Java this keyword

In Java, this is a keyword which is used to refer current object of a class. we can it to refer any member of the class. It means we can access any instance variable and method by using this keyword.

The main purpose of using this keyword is to solve the confusion when we have same variable name for instance and local variables.

We can use this keyword for the following purpose.

  • this keyword is used to refer to current object.
  • this is always a reference to the object on which method was invoked.
  • this can be used to invoke current class constructor.
  • this can be passed as an argument to another method.

11.Garbage Collection in Java

ava garbage collection is the process of releasing unused memory occupied by unused objects. This process is done by the JVM automatically because it is essential for memory management.

When a Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed.

When there is no reference to an object, then that object is assumed to be no longer needed and the memory occupied by the object are released. This technique is called Garbage Collection.

How Garbage Collection Works?

The garbage collection is a part of the JVM and is an automatic process done by JVM. We do not need to explicitly mark objects to be deleted. However, we can request to the JVM for garbage collection of an object but ultimately it depends on the JVM to call garbage collector.

Can the Garbage Collection be forced explicitly ?

No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection.

Advantages of Garbage Collection

  1. Programmer doesn't need to worry about dereferencing an object.
  2. It is done automatically by JVM.
  3. Increases memory efficiency and decreases the chances for memory leak.

An object is able to get garbage collect if it is non-reference. We can make an object non-reference by using three ways.

1. set null to object reference which makes it able for garbage collection. For example:


Demo demo = new Demo();
demo = null; // ready for garbage collection        

2. We can non-reference an object by setting new reference to it which makes it able for garbage collection. For example

    
Demo demo = new Demo();
Demo demo2 = new Demo();
demo2 = demo // referring object
            

3. Anonymous object does not have any reference so if it is not in use, it is ready for the garbage collection.

finalize() method

Sometime an object will need to perform some specific task before it is destroyed such as closing an open connection or releasing any resources held. To handle such situation finalize() method is used.

The finalize() method is called by garbage collection thread before collecting object. Its the last chance for any object to perform cleanup utility.

Signature of finalize() method

protected void finalize()
{
 //finalize-code
}        

Request for Garbage Collection

We can request to JVM for garbage collection however, it is upto the JVM when to start the garbage collector.

Java gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that JVM will perform the garbage collection. It only request the JVM for garbage collection. This method is present in System and Runtime class.

Example of gc() Method

Let's take an example and understand the functioning of the gc() method.

public class Test
{

    public static void main(String[] args)
    {
        Test t = new Test();
        t=null;
        System.gc();
    }
    public void finalize()
    {
        System.out.println("Garbage Collected");
    }
}        

12. Java Final Modifier

Final modifier is used to declare a field as final. It can be used with variable, method or a class.

If we declare a variable as final then it prevents its content from being modified. The variable acts like a constant. Final field must be initialized when it is declared.

If we declare a method as final then it prevents it from being overridden.

If we declare a class as final the it prevents from being inherited. We can not inherit final class in Java.

Example: Final variable

In this example, we declared a final variable and later on trying to modify its value. But final variable can not be reassigned so we get compile time error.

	
public class Test {
	
	final int a = 10;
	public static void main(String[] args) {
		Test test = new Test();
		test.a = 15; // compile error
		System.out.println("a = "+test.a);
	}
}
	        

error: The final field Test.a cannot be assigned

Final Method

A method which is declared using final keyword known as final method. It is useful when we want to prevent a method from overridden.

Example: Final Method

In this example, we are creating a final method learn() and trying to override it but due to final keyword compiler reports an error.

	
class StudyTonight
{
  final void learn()
  {
    System.out.println("learning something new");
  }
}

// concept of Inheritance
class Student extends StudyTonight
{
  void learn()
  {
    System.out.println("learning something interesting");
  }

  public static void main(String args[]) {
    Student object= new Student();
    object.learn();
  }
}
	        

Cannot override the final method from StudyTonight

This will give a compile time error because the method is declared as final and thus, it cannot be overridden. Don't get confused by the extends keyword, we will learn about this in the Inheritance tutorial which is next.

Let's take an another example, where we will have a final variable and method as well.

	
class Cloth
{
  final int MAX_PRICE = 999;    //final variable
  final int MIN_PRICE = 699;
  final void display()      //final method
  {
    System.out.println("Maxprice is" + MAX_PRICE );
    System.out.println("Minprice is" + MIN_PRICE);
  }
}
	        

In the class above, the MAX_PRICE and MIN_PRICE variables are final hence there values cannot be changed once declared. Similarly the method display() is final which means even if some other class inherits the Cloth class, the definition of this method cannot be changed.

Final Class

A class can also be declared as final. A class declared as final cannot be inherited. The String class in java.lang package is an example of a final class.

We can create our own final class so that no other class can inherit it.

Example: Final Class

In this example, we created a final class ABC and trying to extend it from Demo class. but due to restrictions compiler reports an error. See the below example.

	
final class ABC{
	
	int a = 10;
	void show() {
		System.out.println("a = "+a);
	}
	
}

public class Demo extends ABC{
	
	public static void main(String[] args) {
		
		Demo demo = new Demo();
		
	}
}

        

Output: The type Demo cannot subclass the final class ABC

12. Introduction to Java String Handling

String is an object that represents sequence of characters. In Java, String is represented by String class which is located into java.lang package

It is probably the most commonly used class in java library. In java, every string that we create is actually an object of type String. One important thing to notice about string object is that string objects are immutable that means once a string object is created it cannot be changed.

What is an Immutable object?

An object whose state cannot be changed after it is created is known as an Immutable object. String, Integer, Byte, Short, Float, Double and all other wrapper classes objects are immutable.

Creating a String object

String can be created in number of ways, here are a few ways of creating string object.

1) Using a String literal

String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String object.

public class Demo{    
    public static void main(String[] args) {  
    	String s1 = "Hello Java";
    	System.out.println(s1);
    }  
}          

2) Using new Keyword

We can create a new string object by using new operator that allocates memory for the object.

public class Demo{    
    public static void main(String[] args) {  
    	String s1 = new String("Hello Java");
    	System.out.println(s1);
    }  
}          

String Comparison

To compare string objects, Java provides methods and operators both. So we can compare string in following three ways.

  1. Using equals() method
  2. Using == operator
  3. By CompareTo() method

StringBuffer class in Java

StringBuffer class is used to create a mutable string object. It means, it can be changed after it is created. It represents growable and writable character sequence.

It is similar to String class in Java both are used to create string, but stringbuffer object can be changed.

So StringBuffer class is used when we have to make lot of modifications to our string. It is also thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors.

  1. StringBuffer(): It creates an empty string buffer and reserves space for 16 characters.
  2. StringBuffer(int size): It creates an empty string and takes an integer argument to set capacity of the buffer.
  3. StringBuffer(String str): It creates a stringbuffer object from the specified string.
  4. StringBuffer(charSequence []ch): It creates a stringbuffer object from the charsequence array.

Example: Creating a StringBuffer Object

In this example, we are creating string buffer object using StringBuffer class and also testing its mutability.

public class Demo {

	public static void main(String[] args) {

		StringBuffer sb = new StringBuffer("study");
		System.out.println(sb);
		// modifying object
		sb.append("tonight");
		System.out.println(sb);    // Output: studytonight

	}
}        

Java StringBuilder class

StringBuilder is identical to StringBuffer except for one important difference that it is not synchronized, which means it is not thread safe.

StringBuilder also used for creating string object that is mutable and non synchronized. The StringBuilder class provides no guarantee of synchronization. StringBuffer and StringBuilder both are mutable but if synchronization is not required then it is recommend to use StringBuilder class.

This class is located into java.lang package and signature of the class is as:

public final class StringBuilder
extends Object
implements Serializable, CharSequence        

StringBuilder Constructors

  1. StringBuilder (): creates an empty StringBuilder and reserves room for 16 characters.
  2. StringBuilder (int size): create an empty string and takes an integer argument to set capacity of the buffer.
  3. StringBuilder (String str): create a StringBuilder object and initialize it with string str.
  4. StringBuilder (CharSequence seq): It creates stringbuilder object by using CharSequence object.

13. Introduction to Multithreading in Java

Multithreading is a concept of running multiple threads simultaneously. Thread is a lightweight unit of a process that executes in multithreading environment.

Joining threads in Java

Sometimes one thread needs to know when other thread is terminating. In java, isAlive() and join() are two different methods that are used to check whether a thread has finished its execution or not.

The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false.

final boolean isAlive()        

But, join() method is used more commonly than isAlive(). This method waits until the thread on which it is called terminates.

final void join() throws InterruptedException        

Using join() method, we tell our thread to wait until the specified thread completes its execution. There are overloaded versions of join() method, which allows us to specify time for which you want to wait for the specified thread to terminate.

final void join(long milliseconds) throws InterruptedException
        

Java Thread join method can be used to pause the current thread execution until unless the specified thread is dead. There are three overloaded join functions.

Java Thread join example


package com.threads;

public class ThreadJoinExample {

    public static void main(String[] args) {

        Thread t1 = new Thread(new MyRunnable(), "t1");
        Thread t2 = new Thread(new MyRunnable(), "t2");
        Thread t3 = new Thread(new MyRunnable(), "t3");
        
        t1.start();
        
        //start second thread after waiting for 2 seconds or if it's dead
        try {
            t1.join(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t2.start();
        
        //start third thread only when first thread is dead
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t3.start();
        
        //let all threads finish execution before finishing main thread
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        System.out.println("All threads are dead, exiting main thread");
    }

}

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("Thread started:::"+Thread.currentThread().getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread ended:::"+Thread.currentThread().getName());
    }
    
        

14. Java Collection Framework

Java collection framework represents a hierarchy of set of interfaces and classes that are used to manipulate group of objects.

Collections framework was added to Java 1.2 version. Prior to Java 2, Java provided adhoc classes such as Dictionary, Vector, Stack and Properties to store and manipulate groups of objects.

Java collections framework is contained in java.util package. It provides many important classes and interfaces to collect and organize group of objects.

No alt text provided for this image

14.1 List of Collection Interfaces

The list of core collection interfaces are : just mention the important ones

Important : Collection , Set , Queue , List , Map

Other interfaces also on the list : SortedSet, SortedMap, Deque, ListIterator, etc.

14.2 What is the difference between List and Set?

Set contains only unique elements while List can contain duplicate elements.

Set is unordered while the List is ordered. List maintains the order in which the objects are added.

14.3 What are the classes implementing List and Set interface?

Class implementing List interface :  ArrayList, Vector, LinkedList

Class implementing Set interface : HashSet, TreeSet

14.4 What is the difference between HashSet and TreeSet?

Main differences between HashSet and TreeSet are :

a. HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order

b. HashSet can store the null object while TreeSet can not store the null object.

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics