R4R
Right Place For Right Person TM
 
R4R java Core java

R4R
provide basic CoreJava Tutorials concept with
CoreJava Examples . Through R4R you can develop CoreJava programming concept. R4R provide CoreJava Interview Questions with answers.R4R provide CoreJava Languages study materials in easy way.

Core Java Examples

2.1    Core Java Basic Example
2.2    Core Java Basic Example
2.3    Awt Basic example (new)
2.4    Core Java Basic example (new)
2.5    Java Utility Examples
2.6    Lang Basic Examples
2.7    Collections Examples

Core Java Articles

4.1    Core Java Topics

Hot Java Topics

5.1    Core Java basics
5.2    Java Multithreading
5.3    Exception Handling
5.4    300 Core Java Interview Questions
 

CORE JAVA

Java is a programming language developed by James Gosling from Sun Microsystems in 1991. The first public available version of Java (Java 1.0) was  released 1995. Over time several version of Java were released which enhanced the language and its libraries. The current version of Java is 1.6also known as Java 6.0. The main components of java language are compiler java virtual machine and Java class libraries. The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine. The Java compiler translates Java coding into  byte-code. The Java virtual machine interprets this byte-code and runs the program. The Java virtual machine is written specifically for a specific operating system. The Java runtime environment (JRE) consists of the JVM and the Java class libraries.

FEATURES OF JAVA
The main objective of java development is to write the program once and run it on multiple plateforms. other features of java are:
1.Simple :-
Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages.
2.Object-orientated programming language:- Except the primitive data types, all elements in Java are objects.
3.Automatic Memory Management :-
Automatic garbage collection - memory management handled by JVM
4.Dynamic:-User can access the files from the any location ,from local system or from anywhere location
5.Distributed:-Using protocols like HTTP and FTP  java developers . can call functions on these protocols and can get access the files from any remote machine on the internet .
6.Portable:-
The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM.
7.Security :-
Java is secure because java do not used memory pointers explicitly. programs are run inside the JVM sand box
8.Plateform independent: -Write once run anywhere makes java platform independent.

BASICS OF JAVA TECHNOLOGY
Java technology as programming language and a platform. Java technology is a simple, secure, robust, complete object oriented and platform independent high level programming language. Java is  portable, high performance, multithreaded and network security provider that enable it in constructing software that can run along in small machines. The whole technology is based on the concept of JavaVirtual Machine (JVM) that acts as  translators of byte code into machine language.

IMPORTANCE OF JAVA TECHNOLOGY
Java is high level programming language .As java provide Java technology as programming language and a platform. Java technology is a simple, secure, robust, complete object oriented and platform independent high level programming language.  The whole technology is based on the concept of Java Virtual Machine (JVM) that acts as a translators of byte code into machine language.

EDITIONS OF JAVA TECHNOLOGY
There are three editions of java technology
1.JAVA SE:-
Java standard edition provide Tolls and APIs that you can use to create server applications ,desktop application, and applets Programs developed using SE edition can run on any operating system. like Linux, Macintosh, Solaris and Windows
2.JEE:-
Java Enterprise Edition helps in web application service, component model and enterprise class service oriented architecture (SOA)
3.JME:- Java Micro edition is basically used for development of software for small devices like mobile phones ,game programming ,PDAsetc.

DEVELOPMENT OF JAVA PROGRAM
The programmer writes Java source code in an text editor which supports plain text. IDE (integrated development environment )is required for programming .An IDE support the programmer in the task of writing code, e.g. it provides auto-formatting of the source code, highlighting of the important keywords, etc. . The Java compiler creates platform independent code which is called byte code. This byte-code is stored in ".class" files. Byte code can be executed by the Java runtime environment. The Java runtime environment (JRE) is a program which knows how to run the byte code on the operating system. The JRE translates the byte code into native code and executes.

CLASS PATH
The Classpath is the connection between the Java compiler and Java interpreter. It defines where the compiler and interpreter look for .class files to load
What is Java API?
Java API is  a set of classes and interfaces which  comes with the JDK. Java API is basically a huge collection of library routines that performs basic programming tasks .All java classes and interfaces are packaged in packages. These classes are written in Java and runs on the JVM. Java classes are platform independent but JVM is not platform independent. You will find different downloads for each OS.

FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA A SIMPLE JAVA PROGRAM
Write the program using note pad for window system or either used net bean or eclipse these are the IDE for program writing.following program is written in note pad

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

Compilation of program
Open the command prompt and write cd javadir, for example in my case cd c:\r4r\java. Use the command dir to see that the source file is in the directory then on command prompt write javac Hello.java (File saved with the name of class here file is saved with Hello.java ,. java is the extension of jav files)

Run The Java Program write java hello world on command prompt to run the program.

JAVA COMMENTS
Java has uses three ways of showing comments. The most common method is a //. You use this for a comment that will run from the // to the end of the line. for longer comments (number of lines of comments)  you can write the the comments within the /* and */.
there is a third kind of comment that can be used to generate documentation automatically. This comment uses a /** to start and a */ to end.

JAVA DATA TYPES
Java support eight primitive type data types these are
byte, short, int, long, float, double, char, Boolean

JAVA VARIABLES
 
Variables are used to store the value for any data type in memory.In Java, every variable has a type. You declare a variable by placing the type first, followed by the name of the variable. few examples are given below


double salary;
int vacationDays;
long earthPopulation;
char yesChar

JAVA ASSIGNMENT AND INITIALIZATIONS
After you declare a variable, you must explicitly initialize it by means of an assignment statement—you can never use the values of un initialized variables. You assign to a previously declared variable using the variable name on the left, an equal sign (=), and then some Java expression that has an appropriate value on the right.


int vacationDays; // this is a declaration
vacationDays = 12; // this is an assignment

int vacationDays = 12; // this is an initialization


OPERATORS
The usual arithmetic operators + – * / are used in Java for addition, subtraction, multiplication, and division. The / operator denotes integer division if both arguments are integers, and floating-point division otherwise. Integer remainder (that is, the mod function) is denoted by %. For example, 13 / 2 is 6, 13 % 2 is 1, and 19.0 / 2 is 8.5.

Increment and Decrement Operators
 
Increment operator is (++) which is used to increase the value of variable by one. on other hand decrement operator (--) is used to decrease the value of variable by one. x++ adds 1 to the current value of the variable x, and x-- subtracts 1 from it.
int n = 12;
n++;
 

Relational and Boolean Operators
Java has the full complement of relational operators. To test for equality you use a double equal sign, ==. For example, the value of

3 == 7

is false.

Java, following C++, uses && for the logical "and" operator and || for the logical "or" operator. As you can easily remember from the != operator, the exclamation point ! is the logical negation operator. The && and || operators are evaluated in "short circuit" fashion. This means that when you have an expression like:

A && B
once the truth value of the expression A has been determined to be false, the value for the expression B is not calculated. For example, in the expression

x != 0 && 1 / x > x + y // no division by 0

Bitwise Operators
While  working with any of the integer types, the there are  operators that can work directly with the bits that make up the integers. Which means that you can use masking techniques to get at individual bits in a number. The bitwise operators are:

& ("and") , | ("or") ,^ ("xor"), ~ ("not")

Control Flow
 java provide  some control statements to control the flow of program. these statements are if, if else ,while ,do while, goto , switch ,break and continue.

Keywords in java :- keywords are those words with are defined in has special meaning for every keywords they cannot be used as literals.some of the key words are int, char, if, switch, ,while ,volatile, final , synchronized ,Boolean, super, protected , private ,public, transient,new , package ,import etc the list is very large.goto and const are the reserved keywords which are not implemented.

Big Numbers
If the declaration  of the basic integer and floating-point types is not sufficient, than you can turn to a some classes in the java.math package, called BigInteger and BigDecimal. These are classes for manipulating numbers with an arbitrarily long sequence of digits. The BigInteger class implements arbitrary precision integer arithmetic, and BigDecimal does the same for floating-point numbers.

BigInteger a = BigInteger.valueOf(100);

Arrays
An array is a data structure which used to  stores a collection same type of values. You access each individual value through an integer index. For example, if a is an array of integers, then a[i] is the ith integer in the array.

OOPS FUNDAMENTALS THAT JAVA FOLLOW
Java follow the three basic fundamental of oops that is Encapsulation( some times called hiding of data), inheritance (inherit the properties of super class) and polymorphism (method overriding and method overloading).

Objects:- As java is object based programming .object is defined as the instance of class .All objects that are instances of the same class share a family resemblance by supporting the same behavior. The behavior of an object is defined by the methods that you can call.
Classes:  A class can be defined as  the blueprint from which individual objects are created. A class must  consists the methods and data.


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

super class and sub class in java: - parent class is called super class and child class is called sub class in java. sub is extend from super class sometime method is also override in sub class which is declare in super class.

Methods:-A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name.

Here is an example of a typical method declaration:

    public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) {
    //do the calculation here

Constructor:-
Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences. Constructor is always called by new operator. Constructor are declared just like as we declare methods, except that theconstructor don't have any return type. constructor is declare with name of class. constructors are overloaded just like methods.
public class Point {
    int m_x;
    int m_y;

    //============ Constructor
    public Point(int x, int y) {
        m_x = x;
        m_y = y;


ADDITIONAL JAVA FUNDAMENTALS
Super Keyword:-The super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used.The super keyword as a standalone statement is used to call the constructor of the superclass in the base class.

public class Class1{

public Class1(String arg){//constructor

super(arg);//super calling the constructor
}
The syntax super.<method_Name>() is used to give a 
call to a method of the superclass in the base class.

Final classes and methods.:- The Classes those are not extended are called final classes, and  use the final modifier in the definition of the class to indicate this. we can also make a specific method in a class final. If we  do this, then no subclass can override that method. (All methods in a final class are automatically final.)

Interfaces :-In the Java programming language, an interface is not a class but a set of requirements for classes that want to conform to the interface.Interfaces are not classes. In particular, you can never use the new operator to instantiate an interface. However, even though you can't construct interface objects, you can still declare interface variables.
Here is what the Comparable interface looks like:

public interface Comparable
{
   int compareTo(Object other);

methods in an interface are automatically public, fields are always public static final.

 Abstract Classes:-Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.

ACCESS MODIFIERS IN JAVA
The Java has three explicit access modifiers viz. public, private and protected, and also has a default modifier, which is used when you do not explicitly specify a modifier.
public modifier : The public modifier makes an element most visible, it can be applied to various classes and their members (instance variable and methods)
private modifier :
The private modifier is used to make a java element least visible. The private modifier cannot be used for a top-level class, and can be applied only to the members of a top-level class viz. instance variables, methods.
protected modifier :
The protected modifier makes a class member more visible than private modifier but less accessible than public modifier. This modifier may be applied only to class members viz. variables, methods, and inner classes—but not to the class itself
default modifier :
In java we cannot specify any modifier for the variables inside a method, and also we cannot specify the protected modifier for a class. When we do not specify any access modifier for an element, it is implied that the access is default.

JAVA PACKAGES
A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces. some packages are  java . langl , java.util, java.io,java.net ,java.awts

METHOD OVERLOADING AND METHOD OVERRIDING IN JAVA
Method overloading when you have more than one method with the same name but different arguments, the methods are said to be overloaded. Example:

    public class OverLoadingExample{

    public void add(int i, int j)

    {

    int k = i + j;

    }

    public void add(String s, String t)

    {

    int k = Integer.parseInt(s) + Integer.parseInt(t);

    }

    }

Method overriding
when you want to extend a class and the ethod of super  class  write  in the derived class .then, it is termed as overriding.
    public class BaseClass{

    public void methodToOverride()

    {

    //Some code here

    }

    }

    public class DerivedClass extends BaseClass{

    public void methodToOverride()

    {

    //Some new code here

   
}

    }
EXCEPTION HANDLING IN JAVA
Exceptions are used for handling errors which are  occurs during the program execution .During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block. In Java, an exception object is always an instance of a class derived from Throwable Throwable class is divided into two----Errors and Exceptions .Exception is further divide into IO Exceptions and Run Time Exceptions.
 

Example:

  import java.io.*;

public class exceptionHandle{
  public static void main(String[] args) throws Exception{
    try{
      int a,b;
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      a = Integer.parseInt(in.readLine());
      b = Integer.parseInt(in.readLine());
    }
    catch(NumberFormatException ex){
      System.out.println(ex.getMessage() + " is not a numeric value.");
      System.exit(0);
    }

MULTITHREADING IN JAVA
Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system.In the multithreading concept, several multiple lightweight processes are run in a single process/task or program by a single processor.
Thread:-
A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang Thread class.
process:
:-A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.

Life cycle of tread
Life cycle of tread consists five stages
.1.New state:-After the creations of Thread instance the thread will come  in this state but before the start() method invocation. At this point, the thread is considered not alive
.2.Runnable(ready to run):-A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also
3.Running state:-
A thread is in running state means it is  currently executing..
4.Dead state :-
A thread can be considered dead when its run() method completes.
5.Blocked state:-
In this state thread will come if only when the resource is used  by the other thread

CREATION OF THREAD
Thread can be created in two ways :
1.By extending thread class by own.
FirstExtend the java.lang.Thread Class.Override the run( ) method in the subclass from the Thread class to define the code executed by the thread.
Create an instance of this subclass. Invoke the start( ) method on the instance of the class to make the thread eligible for running.
  class MyThread extends Thread{

  String s=null;

  MyThread(String s1){
    s=s1;
    start();
  }
  public void run(){
      System.out.println(s);
    }
}
public class RunThread{
  public static void main(String args[]){
  
    MyThread m1=new MyThread("Thread started....");
   }
}

2.implementing runnable interface:
To create a thread is to first  create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run( ), which is declared like this:


 public void run( )
Thread(Runnable threadOb, String threadName);
void start( );

Thread Priorities:Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads.

Volatile and Synchronized Keywords
Volatile is a Keyword  used to define the variable in java. If no. of  threads have access  the same variable, the JVM may  its own copy of the variable. Changes to the variable by one thread may or may not be seen by other threads; using the volatile key word essentially synchronizes access to a variable. When you declare a variable with the volatile keyword, the JVM must make sure that all threads accessing the variable have their copies updated whenever the variable is modified.The Java programming language provides two basic synchronization idioms:
synchronized methods and synchronized statements

Synchronized methods To make a method synchronized, simply add the synchronized keyword to its declaration:


  public synchronized void increment()
making  methods synchronized has two effects:-
 

Synchronized Statements
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock.


  public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

COLLECTIONS IN JAVA
Collections is defined as a group of objects also  known as its elements. Actually collection is  a package of data structures which includes ArrayLists, LinkedLists, HashSets, etc. A collection is a simple an object which groups multiple elements into a single unit. Collection  is used to store, retrieve, manipulate, and communicate aggregate data. The manipulation and passing of collections is done by this interface .These classes typically implement Collection indirectly through one of its sub interfaces.
1.Void (no arguments) constructor which creates an empty collection.
2.Constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

COLLECTIONS API
Java Collections of API (Application Programming Intreface) Consists several interfaces, and classes which are  implement those interfaces, within the java.util package. It provides tools for maintaining a data container of objects.The value of primitive is must be wrapped in an object of its appropriate wrapper class (Boolean, Character, Integer, Double, etc.) to maintain a collection of primitive data. .

GARBAGE COLLECTION
The Java virtual machine's heap stores all objects created by a running Java application. Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. Every  time when an object is created in java, it will  goes into an area of memory which is called  as the HEAP. All the objects are stored on heap whether they are created somewhere else. the java heap is actually called the Garbage-collectible Heap. When   an object is created, java allocates memory space on the heap according to the requirement by the  that particular object.  java manage that memory for user .When the JVM can find  that an object can never be used again , then that object become will be  eligible for garbage collection. and if you're running low on memory ,the garbage collector will run, throw out the unreachable objects, and free up the space. so that the space can be reused.


Tolal:0 Click:
Show All Comments

Post Your Comments

Your Name:

Your Email ID :
Comments :
URL
  =* Enter SUM

Tutorials,Examples,Questions and Answer

R4R
R4R
R4R
R4R
R4R
R4R
R4R
R4R