You are on page 1of 8

Singleton,factory,abstract,commandline,,,flyweight,

Java | How to start learning Java


Java is one of the most popular and widely used programming language and platform. A platform is an
environment that helps to develop and run programs written in any programming language.
Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming
consoles, cell phones to the Internet, Java is used in every nook and corner.

About Java
 Java is a simple language: Java is easy to learn and its syntax is simple and easy to
understand. It is based on C++ (so easier for programmers who know C++). Java has removed
many confusing and rarely-used features e.g. explicit pointers, operator overloading etc. Java
also takes care about memory management and for that, it provides an automatic garbage
collector. This collects the unused objects automatically.
 Java is a platform-independent language: The programs written in Java language, after
compilation, are converted into an intermediate level language called the bytecode which is
irrespective of the machine on which the programs runs. This makes java highly portable as its
bytecodes can be run on any machine by an interpreter called the Java Virtual Machine(JVM)
and thus java provides ‘reusability of code’.
 Java is an object-oriented programming language: OOP makes the complete
program simpler by dividing it into a number of objects. The objects can be used as a bridge to
have data flow from one function to another. We can easily modify data and function as per the
requirement.
 Java is a robust language: Java programs must be reliable because they are used in both
consumer and mission-critical applications, ranging from Blu-ray players to navigation systems.
 Java is a multithreaded language: Java can perform many tasks at once by defining
multiple threads. For example, a program that manages a Graphical User Interface (GUI) while
waiting for input from a network connection uses another thread to perform the wait instead of
using the default GUI thread for both tasks. This keeps the GUI responsive.
 Java programs can create applets: Applets are the programs which run on web browsers.
 Java does not require any preprocessor: It does not require inclusion of header files for
creating a Java application.
Therefore, Java is a very successful language and its need is certainly going to increase day by day.

Important tips and links to get you started


1. Firstly understand the basics:
Learning the basics of any programming language is very important. It is the best head start.
Marking the doubts and clearing them regularly will lead to success. Try to get the concept behind
any logic and don’t try and mug it up, that’s very important. Start, get familiar with the environment,
and slowly you’ll get used to it no time. Here are a few links to get you started:
 Java – Overview
 Java – Basics(Articles)
 Java – Basics (Videos)
 OOP – Concept
2. Patience is the key:
Many a time it will be overwhelming but be patient, learn at your own pace, don’t rush. Mastering
Java is not a one day process. And remember even the best coders would have had started at
some point. So it’s not a big deal you can also do it. Give it time. Patience is the key to success.
3. Practice Coding
Once you’ve understood the basics, the best thing to brush up your skills is a regular practice.
True knowledge only comes when you implement what you’ve learned, as is said ‘Practice Makes
a Man Perfect’. So, code more than you read. This will build your confidence. Remember
Perfect Practice makes you Perfect.
Practice Coding: You can increase your coding skills here. Happy Coding!
4. Read about Java regularly
Continuously read about the various topics in Java and try to explore more. This will help to
maintain your interest in Java.
Go through this link to explore the vast world of Java:
Explore Java >>
Recent articles on Java >>
5. Study in a group
Group study is a better way to learn something. This way you get to know about new things about
the topic as everyone presents their ideas and you can discuss and solve your doubts on the
spot. So try and make a common group of people who are willing to learn java.
You can take help of a tutor and can also refer to any of the books if you want. There are many
good books in the market that’ll help you in learning java.

Setting up Java

You can download java from here. Here you will find different versions of java. Choose and download
the one compatible with your operating system.
For detailed instructions for setting up of Java, refer this article.
After you have set up the Java environment correctly, try running this simple program:
// A Java program to print GeeksforGeeks
public class GFG {
public static void main(String args[])
{
System.out.println("GeeksforGeeks");
}
}
Run on IDE
Output:
GeeksforGeeks

If the environment is setup correctly and the code is correctly written, you shall see this output on your
console. That is your first Java program!

Java Naming Conventions


Below are some naming conventions of for java programming language. They must be followed while
developing software in java for good maintenance and readability of code. Java uses CamelCase as a
practice for writing names of methods, variables, classes, packages and constants.

Camel case in Java Programming : It consists of compound words or phrases such that each
word or abbreviation begins with a capital letter or first word with a lowercase letter, rest all with capital.
1. Classes and Interfaces :
 Class names should be nouns, in mixed case with the first letter of each
internal word capitalized. Interfaces name should also be capitalized just like
class names.
 Use whole words and must avoid acronyms and abbreviations.
Examples:

Interface Bicycle

Class MountainBike implements Bicyle


Interface Sport

Class Football implements Sport

2. Methods :
 Methods should be verbs, in mixed case with the first letter lowercase and
with the first letter of each internal word capitalized.
Examples:

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);

3. Variables : Variable names should be short yet meaningful.


 Should not start with underscore(‘_’) or dollar sign ‘$’ characters.
 Should be mnemonic i.e, designed to indicate to the casual observer the intent
of its use.
 One-character variable names should be avoided except for temporary
variables.
 Common names for temporary variables are i, j, k, m, and n for integers; c, d,
and e for characters.
Examples:

// variables for MountainBike class

int speed = 0;

int gear = 1;

4. Constant variables:
 Should be all uppercase with words separated by underscores (“_”).
 There are various constants used in predefined classes like Float, Long, String
etc.
Examples:

static final int MIN_WIDTH = 4;

// Some Constant variables used in predefined Float class

public static final float POSITIVE_INFINITY = 1.0f / 0.0f;

public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;

public static final float NaN = 0.0f / 0.0f;

5. Packages:
 The prefix of a unique package name is always written in all-lowercase ASCII
letters and should be one of the top-level domain names, like com, edu, gov,
mil, net, org.
 Subsequent components of the package name vary according to an
organization’s own internal naming conventions.
Examples:

com.sun.eng

com.apple.quicktime.v2

// java.lang packet in JDK

java.lang

How JVM Works – JVM Architecture?


JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that
actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime
Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java enabled system without
any adjustment. This is all possible because of JVM.

When we compile a .java file, a .class file(contains byte-code) with the same filename is generated by
the Java compiler. This .class file goes into various steps when we run it. These steps together
describe the whole JVM.

Class Loader Subsystem

It is mainly responsible for three activities.


 Loading
 Linking
 Initialization
Loading : The Class loader reads the .class file, generate the corresponding binary data and save it
in method area. For each .class file, JVM stores following information in method area.
 Fully qualified name of the loaded class and its immediate parent class.
 Whether .class file is related to Class or Interface or Enum
 Modifier, Variables and Method information etc.
After loading .class file, JVM creates an object of type Class to represent this file in the heap memory.
Please note that this object is of type Class predefined in java.lang package. This Class object can be
used by the programmer for getting class level information like name of class, parent name, methods
and variable information etc. To get this object reference we can use getClass()method
of Object class.
// A Java program to demonstrate working of a Class type
// object created by JVM to represent .class file in
// memory.
import java.lang.reflect.Field;
import java.lang.reflect.Method;

// Java code to demonstrate use of Class object


// created by JVM
public class Test
{
public static void main(String[] args)
{
Student s1 = new Student();

// Getting hold of Class object created


// by JVM.
Class c1 = s1.getClass();

// Printing type of object using c1.


System.out.println(c1.getName());

// getting all methods in an array


Method m[] = c1.getDeclaredMethods();
for (Method method : m)
System.out.println(method.getName());

// getting all fields in an array


Field f[] = c1.getDeclaredFields();
for (Field field : f)
System.out.println(field.getName());
}
}

// A sample class whose information is fetched above using


// its Class object.
class Student
{
private String name;
private int roll_No;

public String getName() { return name; }


public void setName(String name) { this.name = name; }
public int getRoll_no() { return roll_No; }
public void setRoll_no(int roll_no) {
this.roll_No = roll_no;
}
}
Run on IDE
Output:

Student

getName

setName

getRoll_no

setRoll_no

name

roll_No

Note : For every loaded .class file, only one object of Class is created.
Student s2 = new Student();

// c2 will point to same object where

// c1 is pointing

Class c2 = s2.getClass();

System.out.println(c1==c2); // true

Linking : Performs verification, preparation, and (optionally) resolution.


 Verification : It ensures the correctness of .class file i.e. it check whether this file is properly
formatted and generated by valid compiler or not. If verification fails, we get run-time
exception java.lang.VerifyError.
 Preparation : JVM allocates memory for class variables and initializing the memory to default
values.
 Resolution : It is the process of replacing symbolic references from the type with direct
references. It is done by searching into method area to locate the referenced entity.
Initialization : In this phase, all static variables are assigned with their values defined in the code
and static block(if any). This is executed from top to bottom in a class and from parent to child in class
hierarchy.
In general, there are three class loaders :
 Bootstrap class loader : Every JVM implementation must have a bootstrap class loader,
capable of loading trusted classes. It loads core java API classes present
in JAVA_HOME/jre/libdirectory. This path is popularly known as bootstrap path. It is
implemented in native languages like C, C++.
 Extension class loader : It is child of bootstrap class loader. It loads the classes present in the
extensions directories JAVA_HOME/jre/lib/ext(Extension path) or any other directory
specified by the java.ext.dirs system property. It is implemented in java by
the sun.misc.Launcher$ExtClassLoader class.
 System/Application class loader : It is child of extension class loader. It is responsible to load
classes from application class path. It internally uses Environment Variable which mapped to
java.class.path. It is also implemented in Java by
the sun.misc.Launcher$AppClassLoaderclass.
// Java code to demonstrate Class Loader subsystem
public class Test
{
public static void main(String[] args)
{
// String class is loaded by bootstrap loader, and
// bootstrap loader is not Java object, hence null
System.out.println(String.class.getClassLoader());
// Test class is loaded by Application loader
System.out.println(Test.class.getClassLoader());
}
}
Run on IDE
Output:

null

sun.misc.Launcher$AppClassLoader@73d16e93

Note : JVM follow Delegation-Hierarchy principle to load classes. System class loader delegate load
request to extension class loader and extension class loader delegate request to boot-strap class
loader. If class found in boot-strap path, class is loaded otherwise request again transfers to extension
class loader and then to system class loader. At last if system class loader fails to load class, then we
get run-time exception java.lang.ClassNotFoundException.

JVM Memory

Method area :In method area, all class level information like class name, immediate parent class name,
methods and variables information etc. are stored, including static variables. There is only one method
area per JVM, and it is a shared resource.
Heap area :Information of all objects is stored in heap area. There is also one Heap Area per JVM. It
is also a shared resource.
Stack area :For every thread, JVM create one run-time stack which is stored here. Every block of this
stack is called activation record/stack frame which store methods calls. All local variables of that method
are stored in their corresponding frame. After a thread terminate, it’s run-time stack will be destroyed
by JVM. It is not a shared resource.
PC Registers :Store address of current execution instruction of a thread. Obviously each thread has
separate PC Registers.
Native method stacks :For every thread, separate native stack is created. It stores native method
information.
Execution Engine

Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and
information present in various memory area and execute instructions. It can be classified in three parts
:-
 Interpreter : It interprets the bytecode line by line and then executes. The disadvantage here is
that when one method is called multiple times, every time interpretation is required.
 Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It compiles the
entire bytecode and changes it to native code so whenever interpreter see repeated method
calls,JIT provide direct native code for that part so re-interpretation is not required,thus efficiency
is improved.
 Garbage Collector : It destroy un-referenced objects.For more on Garbage
Collector,refer Garbage Collector.
Java Native Interface (JNI) :

It is a interface which interacts with the Native Method Libraries and provides the native libraries(C,
C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++
libraries which may be specific to hardware.
Native Method Libraries :

It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.

You might also like