Sunteți pe pagina 1din 46

CORE JAVA

Fundamental of Language
Machine Language:
Machine language is a lowest-level
programming language.
Machine
languages
are
only
language understood by computer
because they consist entirely of
numbers(Binary 0 and 1),Therefore
programmers use either a High-level
programming
language
or
an
assembly language.
Assembly Language:
An assembly language is a low-level
programming language,in which there
is a very strong correspondence
between the language and the
architectures
machine
code
instructions.
Program
written
in
high-level
language
are
translated
into
assembly language or machine
language by a compiler .
Every CPU has its own unique
machine language. Programs must
be rewritten or recompiled,therefore

Introduction of Java
Java is a programming language and
a platform.
Platform Any hardware or software environment
in which a program runs, known as a platform.
Since Java has its own Runtime Environment
(JRE) and API, it is called platform.
Java is a high-level programming language
originally developed by Sun Microsystems
and released in 1991. Java runs on a variety of
plateforms,such as Windows,Mac OS, and the
various version of Unix.
Java is an Object-Oriented language.It enables
us not only to organize our program code into
logical units called object but also to take
advantage of Encapsulation,inheritance, and
polymorphism.

Java Version History


There are many java versions that has been
released.
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)

Features of Java
There is given many features of java. They are also
known as java buzzwords.
Simple
Object-Oriented
Platform independent
Secured
Robust
Architecture neutral
Portable
Dynamic
Interpreted
High Performance
Multithreaded
Distributed

Simple
According to Sun, Java language is simple
because:
syntax is based on C++ (so easier for
programmers to learn it after C++).
removed many
confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
No need to remove unreferenced
objects because there is Automatic Garbage Collection in
java.Object-oriented
Object-oriented
Object-oriented means we organize our software as a
combination of different types of objects that incorporates
both data and behaviour.Object-oriented
programming(OOPs) is a methodology that simplify software
development and maintenance by providing some rules.Basic
concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Objects are the basic run time entities is an object oriented system.
Class: A class is a collection of objects of similar type.
Encapsulation:
The wrapping up of data and functions into a single unit is knows as
encapsulation.
Data encapsulation is the most striking feature of a class(The data is not
accessible to the outside world and only those functions which are wrapper in
the class can access.)
Abstraction
Abstraction refers to the act of representing essential features without
including the background details or explanations.
D/f between Encapsulation or Abstraction
Take a example of laptop.
Inheritance:
Inheritance is one of the key feature of OOP language, In java a class can be
derived from another class. The derived class acquire all features of the base
class .
Provide the idea of reusability.
Java does not support multiple inheritance.
Polymorphism:
Polymorphism means the ability to take more than one form.
Benefits::
Data security is enforced.
Inheritance save time.
User defined data types can be easily constructed.
Large complexity in the software developed can be easily managed.

Platform Independent

Secured
Java is secured because:
No explicit pointer
Programs run inside virtual
machine sandbox.
Classloader- adds security
by separating the package for
the classes of the local file
system from those that are
imported
from
network
sources.
Bytecode Verifier- checks
the code fragments for illegal
code that can violate access
right to objects.
Security
Managerdetermines what resources a
class can access such as
reading and writing to the
local disk.

Robust
Robust simply means strong.
Java uses strong memory management.
There are lack of pointers that avoids security
problem.
There is automatic garbage collection in java.
There is exception handling and type checking
mechanism in java. All these points makes java
robust.
Architecture-neutral
There is no implementation dependent features
e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since
byte code is "close" to native code still
somewhat slower than a compiled language

Distributed
We can create distributed applications in
java. RMI and EJB are used for creating
distributed applications. We may access
files by calling the methods from any
machine on the internet.
Multi-threaded
A thread is like a separate program,
executing concurrently. We can write Java
programs that deal with many tasks at
once by defining multiple threads. The
main advantage of multi-threading is that
it shares the same memory. Threads are
important
for
multi-media,
Web

Hello Java-program
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
save this file as Simple.java
To compile:javac Simple.java
To execute:java Simple
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is
visible to all.
static is a keyword, if we declare any method as static, it is known as static
method. The core advantage of static method is that there is no need to create
object to invoke the static method. The main method is executed by the JVM,
so it doesn't require to create object to invoke the main method. So it saves
memory.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement. The println method is a member
or method of the out object, which is a static data member of System class.
System is a final class ,so we cannot make its object.

Classloader is the subsystem of JVM that is used


to load class files.

Bytecode verifier checks the code fragments for ille


Code that can violate access right to objects.
Interpreter read bytecode stream then
execute the instructions.

How to set path in Java

temporary

set Permanent Path of JDK in Windows


Go to MyComputer properties -> advanced tab
-> environment variables -> new tab of user
variable -> write path in variable name ->
write path of bin folder in variable value -> ok
-> ok -> ok

Java Path in Linux OS


export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home
directory under Root (/home).

JDK,JRE & JVM


JVM
JVM (Java Virtual Machine) is an abstract machine. It is
a specification that provides runtime environment in
which java bytecode can be executed.
JVMs are available for many hardware and
software platforms.
JVM, JRE and JDK are platform dependent because
configuration of each OS differs. But, Java is platform
independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment

JRE(Java Runtime Enviroment)


It is used to provide runtime
environment.
It is the implementation of JVM.
It physically exists.
It contains set of libraries + other files
that JVM uses at runtime.

JDK(Java Development Kit)


It physically exists.
It contains JRE + development tools.

Application Programming Interface


The Java Standard Library(or API) includes hundreds of classes
and methods grouped into several functional packages. Most
commonly used packages are:
Language Support Packages: A collection of classes and
methods required for implementing basic features of java.
Utilities Packages: A collection of classes to provide utility
functions such as date and time functions.
Input/Output Packages: A collection of classes required for
Input/Output manipulation.
Networking Packages: A collection of classes for
communicating with other computers via internet.
AWT Packages: The Abstract Window Tool Kit package
contains classes that implements platform-independent
graphical user interface.
Applet Packages: This includes a set of classes that allow
us to create java applets.

Variable

Variable is name of reserved area


allocated in memory.

Types of Variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is
called instance variable . It is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be
local.

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable }
}//end of class
Data Types in Java

Operators in java

Command Line Arguments:


Command Line Arguments are parameters that are
supplied to the application program at the time of
invoking it for execution.
Any input we enter is in form of string, So we have to
convert string into derived data type.
class ComLineTest{
public static void main(String args[])
{
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
a=a+b;
System.out.println("The sum of two nos is="+a);
}
}

Scanner class
Command Line Argument is not user friendly, then we use Sanner class.
The java.util.Scanner class is a simple text scanner which can parse primitive types
and strings using regular expressions.Following are the important points about
Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default
matches whitespace.
A scanning operation may block waiting for input.
A Scanner is not safe for multithreaded use without external synchronization.
import java.util.*;
class sum
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.println("Enter value of a and b=:");
a=sc.nextInt();
b=sc.nextInt();
a=a+b;
System.out.println("Sum of two nos:="+a);
}
}

Type Casting and Conversion:


For Example,
public class TypeCasting {
public static void main(String[] args) {
byte Byte;
Byte=40;
System.out.println(Byte);
}
}
Output:
40
we know that a "byte" type can hold an
integer "-128 to 127".

public class TypeCasting {


public static void main(String[] args) {
byte Byte;
Byte=40;
Byte=Byte+2;
System.out.println(Byte);
}
}
Output:
TypeCasting.java:5: possible loss of precision
found : int
required: byte
Byte=Byte+2;
^
1 error
Two types of conversions exist in Java:
1. Implicit(Auto) Type Conversion
2. Explicit (External) Type Conversion

Java Array
Java provides a data structure,
the array, which stores a fixed-size
sequential collection of elements of
the same type.
Declaring Array Variables:
dataType[] arrayRefVar;
Creating Arrays:
arrayRefVar = new dataType[arraySize];
//One-dimensional Array

dataType[] arrayRefVar = {value0, value1, ...,


valuek};
or
double[] myList = new double[10];

public class TestArray {


public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This would produce following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Multidimensional array
Declaration:
int myArray[][]=new int[3][4];

A quick way to initialize a two dimensional array is to use nested for


loops as shown below:
Example:
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
table[i][j]=1;
else
table[i][j]=0;
}
}
o/p: 1

foreach Loops:

JDK 1.5 introduced a new for loop, known as foreach loop or enhanced
for loop, which enables you to traverse the complete array
sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This would produce following result:
1.9
2.9
3.4
3.5

String
Strings are a sequence of characters.
In the Java programming language,
strings are objects.
The Java platform provides the String
class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to
write:
String greeting = "Hello world!";
By new keyword
String s=new String("Welcome");//creates t
wo objects and one reference variable

Immutable String in Java


In java, string objects are immutable. Immutable simply
means unmodifiable or unchangeable.
Once string object is created its data or state can't be
changed but a new string object is created.

class Simple{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the strin
g at the end
System.out.println(s);//will print Sachin because strings are
immutable objects
}
}
Output:Sachin

String comparison in Java


There are three ways to compare String objects:
By equals() method (authentication )
By = = operator (sorting)
By compareTo() method (reference matching)
1) By equals() method
equals() method compares the original content of
the string.It compares values of string for
equality.String class provides two methods:
public boolean equals(Object
another){} compares this string to the
specified object.
public boolean equalsIgnoreCase(String
another){} compares this String to another
String, ignoring case.

class Simple{
public static void main(String args[]){

String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:true true false
//Example of equalsIgnoreCase(String) method
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
Output:false true

2) By == operator
The = = operator compares references not values.
//<b><i>Example of == operator</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to sam
e instance)
System.out.println(s1==s3);//false(because s3 refers to insta
nce created in nonpool)
}
}
Output:true false

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the
values compare less than, equal, or greater than.Suppose s1 and s2 are
two string variables.If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
//<b><i>Example of compareTo() method:</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:0 1 -1

String Concatenation in Java


Concating strings form a new string i.e. the combination of
multiple strings.
There are two ways to concat string objects:
By + (string concatenation) operator
By concat() method
1) By + (string concatenation) operator
String concatenation operator is used to add strings.For
Example:
//Example of string concatenation operator
class Simple{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output:Sachin Tendulkar

2) By concat() method
concat() method concatenates the specified string to the end of
current string.
Syntax:
public String concat(String another){}

//<b><i>Example of concat(String) method</i></b>


class Simple{
public static void main(String args[]){

String s1="Sachin ";


String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Output:Sachin Tendulkar

Example of java substring


//Example of substring() method
class Simple{
public static void main(String args[]){
String s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}

charAt() method
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}
Output:S h

length() method
class Simple{
public static void main(String args[]){

String s="Sachin";
System.out.println(s.length());//6
}

}
Output:6
toUpperCase() and toLowerCase() method
class Simple{
public static void main(String args[]){

String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}
Output:SACHIN sachin Sachin

StringBuffer class:
The StringBuffer class is used to created
mutable (modifiable) string. The StringBuffer
class is same as String except it is mutable i.e.
it can be changed.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is chan
ged
System.out.println(sb);//prints Hello Java
}
}

Example of insert() method of StringBuffer class


The insert() method inserts the given string with this string at the given position.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Example of replace() method of StringBuffer class
The replace() method replaces the given string from the specified beginIndex
and endIndex.
class A{
public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello");


sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

Example of delete() method of StringBuffer class


The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Example of reverse() method of StringBuffer class
The reverse() method of StringBuilder class reverses the current string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a string into


tokens. It is simple way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like StreamTokenizer class.
Simple example of StringTokenizer class

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
Name
is
khan

S-ar putea să vă placă și