Java Basics

Java Basics



Java is a high level, robust, secured and object-oriented programming (OOP) language. It was developed by James Gosling, Mike Sheridan, Patrick Naughton in 1995 for Sun Microsystems, later acquired by Oracle Corporation. Java technology is used to develop applications such as Standalone Application, Web Application, Enterprise Application and Mobile Application. Games, Smart Card, Embedded System, Robotics for a wide range of environments, from consumer devices to heterogeneous enterprise systems. Java language, a C-language derivative has its own structure, syntax rules, and programming paradigm. The Java language helps to create modular programs and reusable code which can run on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

With the advancement of Java multiple configurations were built to suit various types of platforms such as J2EE for Enterprise Applications, J2ME for Mobile Applications, Java SE, Java EE, and Java ME.

JAVA Components

The Java language’s programming paradigm is based on the concept of OOP, which the language’s features support. Structurally, the Java language starts with packages. A package is the Java language’s namespace mechanism. Within packages are classes, and within classes are methods, variables, constants. The Java Runtime Environment (JRE) includes the Java Virtual Machine (JVM), code libraries, and components that are necessary for running programs that are written in the Java language. The JRE is available for multiple platforms. The JRE can be freely redistributed with applications, according to the terms of the JRE license, to give the application’s users a platform on which to run your software. The JRE is included in the Java development Kit (JDK).

Java Virtual Machine

A JVM is an abstract computing machine, or virtual machine because it doesn’t physically exist. It is a platform-independent execution environment that converts Java bytecode into machine language and executes it.

How JVM works?

A Java program is written and saved as .java extension. The complier checks the code against the language’s syntax rules and then writes out bytecode in .class files. Bytecode is a set of instructions targeted to run on a JVM. The byte code can run on any platform such as Windows, Linux, Mac OS. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. The pictorial representation of compilation and execution of a Java program is:

The Compiler (javac) converts source code (.java file) to the byte code (.class file). The JVM executes the bytecode produced by compiler. At runtime, the JVM reads and interprets .class files and executes the program’s instructions on the native hardware platform for which the JVM was written. The JVM interprets the bytecode just as a CPU would interpret assembly-language instructions.

JVM Architecture

The component of JVM are explained below:

  • ClassLoader:?The class loader is a subsystem used for loading class files. It performs three major functions as Loading, Linking, and Initialization.
  • Method Area:?JVM Method Area stores class structures like metadata, the constant runtime pool, and the code for methods.
  • Heap:?All the Objects, their related instance variables, and arrays are stored in the heap. This memory is common and shared across multiple threads.
  • JVM language Stacks:?Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM stack, created simultaneously as the thread is created. A new frame is created whenever a method is invoked, and it is deleted when method invocation process is complete.
  • PC Registers:?PC register store the address of the Java virtual machine instruction which is currently executing. In Java, each thread has its separate PC register.
  • Native Method Stacks:?Native method stacks hold the instruction of native code depends on the native library. It is written in another language instead of Java.
  • Execution Engine:?It is a type of software used to test hardware, software, or complete systems. The test execution engine never carries any information about the tested product.
  • Native Method interface:?The Native Method Interface is a programming framework. It allows Java code which is running in a JVM to call by libraries and native applications.
  • Native Method Libraries:?Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution Engine.

JVM Operations

The JVM performs following operation:

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

Java Development Kit

The Java Development Kit (JDK) is a software development environment which is used to develop Java applications, Java applets. The JDK contains JVM, interpreter/loader, compiler, an archiver, a documentation generator required to complete the development of a Java Application. The pictorial representation of JDK is:

JRE Components

JRE consists of the following components:

  • Deployment technologies, including deployment, Java Web Start and Java Plug-in.
  • User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility, Image I/O, Print Service, Sound, drag and drop (DnD) and input methods.
  • Integration libraries, including Interface Definition Language (IDL), Java Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP) and scripting.
  • Other base libraries, including international support, input/output (I/O), extension mechanism, Beans, Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, Override Mechanism, Security, Serialization and Java for XML Processing (XML JAXP).
  • Lang and util base libraries, including lang and util, management, versioning, zip, instrument, reflection, Collections, Concurrency Utilities, Java Archive (JAR), Logging, Preferences API, Ref Objects and Regular Expressions.
  • Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.

Eclipse is a popular open source Integrated Development Environment (IDE) for Java development. Eclipse handles basic tasks, such as code compilation and debugging apart from providing an interface for writing and testing code. In addition, Eclipse can be used to organize source code files into projects, compile and test those projects, and store project files in any number of source repositories.

Difference between JVM, JRE and JDK

  • JRE:?JRE is the environment within which the java virtual machine runs. JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger. That means you can run the code in JRE but you can’t develop and compile the code in JRE.
  • JVM:?JVM runs the program by using class, libraries and files provided by JRE.
  • JDK:?JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger.

Class Concepts

A class is a user defined entity from which objects are created. An object can be defined as an instance of a class. An object contains an address and takes up some space in memory whereas class doesn’t store any space. In other words, class is a blueprint or a set of instruction to build a group of object which has common properties.

For Example, we can think of class as a sketch of a building. It contains all the details about the floors, doors and windows. Based on these descriptions we build the building. Building is the object. Since, many buildings can be made from the same description, we can create many objects from a class.

Object

It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of:

State:?It is represented by attributes of an object. It also reflects the properties of an object.

Behavior:?It is represented by methods of an object. It also reflects the response of an object with other objects.

Identity:?It gives a unique name to an object and enables one object to interact with other objects.

If we consider the real-world, we can find many objects around us, cars, dogs, humans. All these objects have a state and a behavior. If we consider a dog, then its state is – name, breed, color, and the behavior is – barking, wagging the tail, running. If you compare the software object with a real- world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object’s state is stored in fields and behavior is shown via methods. So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods

Class Declaration

A Java class declarations can include these components, in order:

  • Modifiers:?A class can be public or has default access.
  • Class name:?The name should begin with a initial letter (capitalized by convention).
  • Superclass:?The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  • Interfaces:?A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  • Body:?The class body surrounded by braces, { }.

Syntax of a class is:

class ?class_name>{

field; method;
}        

Constructors

Constructors are used for initializing new objects. Fields are variables that provides the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. There are various types of classes that are used in real time applications such as nested classes, anonymous classes, lambda expressions. Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

Example

public class Puppy { public Puppy() {
}
 

public Puppy(String name) {
// This constructor has one parameter, name.
}
}        

Class Variables

A class can contain any of the following variable types.

  • Local variables:?Variables 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.
  • 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 variables:?Class variables are variables declared within a class, outside any method, with the static keyword.

Creating an Object

An object is created from a class. In Java, the new keyword is used to create new objects. There are three steps when creating an object from a class.

  • Declaration: A variable declaration with a variable name with an object type
  • Instantiation: The ‘new’ keyword is used to create the object
  • Initialization: The ‘new’ keyword is followed by a call to a constructor. This call initializes the new object.

Following is an example of creating an object

public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name. System.out.println("Passed Name is :" + name );
}

public static void main(String []args) {
// Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" );
}
}        

Output

Passed Name is :tommy        

Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.Example:

// Class Declaration


public class Dog
{
// Instance Variables String name;
String breed; int age; String color;

// Constructor Declaration of Class
public Dog(String name, String breed,int age, String color)
{
this.name = name; this.breed = breed; this.age = age; this.color = color;
}


// method 1
public String getName()
{
return name;
}


// method 2
public String getBreed()
{
return breed;
}


// method 3
 

public int getAge()
{
return age;
}


// method 4
public String getColor()
{
return color;
}


@Override
public String toString()
{
return("Hi my name is "+ this.getName()+ ".\nMy breed,age and color are " + this.getBreed()+"," + this.getAge()+ ","+ this.getColor());
}


public static void main(String[] args)
{
Dog tuffy = new Dog("tuffy","papillon", 5, "white"); System.out.println(tuffy.toString());
}
}        

Output:

Hi my name is tuffy.
My breed,age and color are papillon,5,white        

Code Explanation:

This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”,”papillon”,5,”white” as values for those arguments:

Dog tuffy = new Dog("tuffy","papillon",5, "white");        

Note: All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-argument constructor (as it contain only one statement i.e super();), or the Object class constructor if the class has no other parent.

Ways to create object of a class

There are four ways to create objects in java.

Using new keyword: It is the most common and general way to create object in java.

Example:

// creating object of class Test Test t = new Test();        

Using Class. For Name (String class Name) method : There is a pre-defined class in java. lang package with name Class. The for Name (String class Name) method returns the Class object associated with the class with the given string name. We have to give the fully qualified name for a class. On calling new Instance () method on this Class object returns new instance of the class with the given string name.

// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();        

Using clone() method: clone() method is present in Object class. It creates and returns a copy of the object.

// creating object of class Test 
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();        

  • Deserialization: De-serialization is technique of reading an object from the saved state in a file. Refer Serialization/De-Serialization in java

FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); Object obj = in.readObject();        

Object Oriented Programming System Concepts

Object Oriented Programming is a methodology or paradigm to design a program using classes and objects. It is a programming style which is associated with the concepts like class, object, Inheritance, Encapsulation, Abstraction, Polymorphism. Object-oriented languages follow a different programming pattern from structured programming languages like C and COBOL. The Object-oriented languages combine data and program instructions into objects.

Object

An object is a self-contained entity that contains attributes and behavior. Instead of having a data structure with fields (attributes) and passing that structure around to all of the program logic that acts on it (behavior), in an object-oriented language, data and program logic are combined. This combination can occur at vastly different levels of granularity, from fine-grained objects such as a Number, to coarse-grained objects, such as a FundsTransfer service in a large banking application. An object-based application in Java is based on declaring classes, creating objects from them and interacting between these objects.

Principles of OOPs

The object-oriented paradigm supports four major principles

Inheritance

In OOP, computer programs are designed in such a way where everything is an object that interacts with one another. Inheritance is one such concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes. In Java, there are two classes:

  • Parent class (Super or Base class)
  • Child class (Subclass or Derived class)

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class. The biggest advantage of Inheritance is that the code in base class need not be rewritten in the child class. That is the variables and methods of the base class can be used in the child class as well.

Syntax:

class A extends B
{

}        

Here class A is child class and class B is parent class.

Example:

class Faculty	{
String designation = "Faculty"; String college = "BookWorld"; void does(){
System.out.println("Teaching");
}
}
public class ScienceFaculty	extends Faculty String mainSubject = "Science";
public static void main(String args[]){ ScienceFaculty obj = new ScienceFaculty(); System.out.println(obj.college); System.out.println(obj.designation); System.out.println(obj.mainSubject); obj.does();
}
}        

Output:

BookWorld 
Faculty 
Science 
Teaching        

Code Explanation:

  • There is a parent class Faculty and a child class Science Faculty.
  • In the Science Faculty class there is no need to write the same code which is already present in the present class.
  • The college name, designation and does() method is common for all the faculties, thus Science Faculty class does not need to write this code
  • The common data members and methods can in-herited from the Faculty class.

Polymorphism

Polymorphism in java is a concept by which we can perform a single action by different ways. In other words, Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child

class object. Polymorphism in java can be performed by method overloading and method overriding.

There are two types of polymorphism in java

  • compile time polymorphism is achieved by method overloading
  • runtime polymorphism is achieved by method overriding

For example, let’s say we have a class Animal that has a method sound(). Since this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink.

public class Animal{
...
public void sound(){
System.out.println("Animal is making a sound");
}
}        

Now lets say we two subclasses of Animal class: Horse and Cat that extends Animal class. We can provide the implementation to the same method

public class Horse extends Animal{
...
@Override
public void sound(){ System.out.println("Neigh");
}
}        

And

public class Cat extends Animal{
...
@Override
public void sound(){ System.out.println("Meow");
}
}        

As you can see that although we had the common action for all subclasses sound() but there were different ways to do the same action. It would not make any sense to just call the generic sound() method as each Animal has a different sound. Thus we can say that the action this method performs is based on the type of object.

Example 1: Runtime Polymorphism

Example: Code of Animal.java

public class Animal{ public void sound(){
System.out.println("Animal is making a sound");
}
}        

Code of Horse.java

class Horse extends Animal{ @Override
public void sound(){ System.out.println("Neigh");
}
public static void main(String args[]){ Animal obj = new Horse(); obj.sound();
}
}        

Output:

Neigh 
Cat.java
public class Cat extends Animal{ 
	@Override
public void sound(){ 
System.out.println("Meow");
}
public static void main(String args[]){ 
Animal obj = new Cat();
obj.sound();
}
}        

Output:

Meow        

Example 2: Compile time Polymorphism

class Overload
{
void demo (int a)
 

{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) { System.out.println("double a: " + a); return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload(); double result;
Obj .demo(10);
Obj .demo(10, 20); result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}        

Output:

a: 10
a and b: 10,20 
double a: 5.5
O/P : 30.25        

Code Explanation:

Here the method demo() is overloaded 3 times: first method has 1 int parameter, second method has 2 int parameters and third one is having double parameter. Which method is to be called is determined by the arguments we pass while calling methods. This happens at runtime so this type of polymorphism is known as compile time polymorphism.

Abstraction

Abstraction is a process where only relevant data is shown to the user and unnecessary details of an object are hidden. For example, when the user login to his bank account online, he enter his user_id and password and press login, The after process of to and fro information transfer and verification is all abstracted away from the user.

The abstraction in object oriented programming can be achieved by various ways such as encapsulation and inheritance.

A Java program is also a great example of abstraction. Here java takes care of converting simple statements to machine language and hides the inner implementation details from outer world.

Abstract Keyword (Abstract Classes and Methods)

An abstract class is never instantiated. When a class contains an abstract method, then it is declared as abstract class. It is used to provide abstraction. Note that an abstract class does not provide 100% abstraction because it may contain a concrete method as well

Syntax:

abstract class class_name { }        

Example of Abstract class

abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
 }
public static void main(String[] args)
{
B b = new B(); b.callme();
}
}        

Output:

this is callme.        

Note the key points about abstract classes:

  • Abstract classes are not Interfaces. They are different, we will study this when we will study Interfaces.
  • An abstract class may or may not have an abstract method. But, if any class has even a single abstract method, then it must be declared abstract.
  • Abstract classes can have constructors, member variables and normal methods.
  • Abstract classes are never instantiated.
  • When you extend an abstract class with abstract method, you must define the abstract method in the child class or make the child class abstract.

Abstract class cannot be instantiated. Below is an example to demonstrate same.

abstract class Student
{
public void name()	// concrete (non-abstract) method
{
System.out.println("Name is Adam");
}
public void marks()	// concrete (non-abstract) method
{
System.out.println("Marks scored are 80");
}
public static void main(String args[])
{
Student s1 = new Student();	// Error raised, see the errror in screenshot
}
}        

Output:

Student.java:13: error: Student is abstract; cannot be instantiated Student s1 = new Student();	// Error raised, see the errror in
screenshot
1 error        

Abstract Method

The methods that are declared without any body within an abstract class are called abstract methods. The method’s body, in this case, is defined by its subclass. An abstract method can never be final and static. Any class that extends an abstract class must implement all the abstract methods declared by the super class.

Syntax:

abstract return_type function_name (); //No definition        

Abstract method in an abstract class

//abstract class abstract class Sum{
/* These two are abstract methods, the child class
* must implement these methods
*/
public abstract int sumOfTwo(int n1, int n2);
public abstract int sumOfThree(int n1, int n2, int n3);
 //Regular method public void disp(){
System.out.println("Method of class Sum");
}
}
//Regular class extends abstract class class Demo extends Sum{
/* If I don't provide the implementation of these two methods,
the
* program will throw compilation error.
*/
public int sumOfTwo(int num1, int num2){ return num1+num2;
}
public int sumOfThree(int num1, int num2, int num3){ return num1+num2+num3;
}
public static void main(String args[]){
 

Sum obj = new Demo(); System.out.println(obj.sumOfTwo(3, 7));
System.out.println(obj.sumOfThree(4, 3, 19)); obj.disp();
}
}        

Output:

10
26
Method of class Sum
        

Note the key points about abstract method:

  • Abstract methods don’t have body, they just have method signature.
  • If a class has an abstract method it should be declared abstract, the vice versa is not true, which means an abstract class doesn’t need to have an abstract method compulsory.
  • If a regular class extends an abstract class, then the class must have to implement all the abstract methods of abstract parent class or it has to be declared abstract as well.

Encapsulation

Encapsulation means putting together all the variables and the methods into a single unit called Class. The idea behind is to hide how things work and just exposing the requests a user can do. Encapsulation provides the security that keeps data and methods safe from inadvertent changes. Encapsulation can be achieved in Java by:

  • Declaring the variables of a class as private.
  • Providing public setter and getter methods to modify and view the variables values.

Example:

public class Student { private String name; public String getName() {
return name; }
public void setName(String name) { this.name = name; }
public static void main(String[] args) {
}
}        

Code Explanation:

  • There is a class Student which has a private variable name and a getter and setter methods through which the name of a student can get and set.
  • Through these methods, any class which wishes to access the name variable has to do it using these getter and setter methods.

String Class

String is a sequence of characters, for e.g. “World” is a string of 5 characters. In Java, string is a constant and cannot be changed once it has been created. The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings. String concatenation is implemented through the String Builder (or String Buffer) class and it’s append method. String conversions are implemented through the method to String, defined by Object and inherited by all classes in Java.

There are two ways to create a String object:

  • By string literal: Java String literal is created by using double quotes. For Example: String str=“Hello”;
  • By new keyword: Java String is created by using a keyword “new”. For Example: String str=new String(“Hello”);

Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned.

Example:

public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'w', 'o', 'r', 'l', 'd', '.' };
String helloString = new String(helloArray); 
System.out.println( helloString );
}
}        

Output:

World.        

Summary

  • Java is a high level, robust, secured and object-oriented programming (OOP) language
  • The Java Runtime Environment (JRE) includes the Java Virtual Machine (JVM), code libraries, and components that are necessary for running programs that are written in the Java language
  • The Java Development Kit (JDK) is a software development environment which is used to develop Java applications, Java applets
  • Abstraction is a process where only relevant data is shown to the user and unnecessary details of an object are hidden

要查看或添加评论,请登录

社区洞察

其他会员也浏览了