SlideShare a Scribd company logo
1 of 57
Prepared By: Sagar Sharma
 James Gosling initiated the Java language project in June 1991 for use in one of his many
set-top box projects. The language, initially called Oak after an oak tree that stood
outside Gosling's office, also went by the name Green and ended up later being
renamed as Java, from a list of random words.
 Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once,
Run Anywhere (WORA), providing no-cost run-times on popular platforms.
 On 13 November 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
 On 8 May 2007, Sun finished the process, making all of Java's core code free and open-
source, aside from a small portion of code to which Sun did not hold the copyright.
Object Oriented: In Java, everything is an Object.
Java can be easily extended since it is based on
the Object model.
Simple: Java is designed to be easy to learn. If you
understand the basic concept of OOP Java would
be easy to master.
Architectural-neutral :Java compiler generates an
architecture-neutral object file format which
makes the compiled code to be executable on
many processors, with the presence of Java
runtime system.
Robust: Java makes an effort to eliminate error
prone situations by emphasizing mainly on compile
time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible
to write programs that can do many tasks simultaneously.
This design feature allows developers to construct smoothly
running interactive applications.
Interpreted: Java byte code is translated on the fly to
native machine instructions and is not stored anywhere.
The development process is more rapid and analytical
since the linking is an incremental and light weight
process.
Dynamic: Java is considered to be more dynamic than C or
C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of
run-time information that can be used to verify and resolve
accesses to objects on run-time.
JDK: Java Developer Kit contains
tools needed to develop the Java
programs, and JRE to run the
programs. The tools include compiler
(javac.exe), Java application
launcher (java.exe), Appletviewer,
etc… Compiler converts java code
into byte code. Java application
launcher opens a JRE, loads the
class, and invokes its main method.
You need JDK, if at all you want to
write your own programs, and to
compile them. For running java
programs, JRE is sufficient. JRE is
targeted for execution of Java files
i.e. JRE = JVM + Java Packages
Classes(like util, math, lang,
awt,swing etc)+runtime
libraries. JDK is mainly targeted for
java development. I.e. You can
create a Java file (with the help of
Java
 Java Runtime Environment contains JVM, class libraries, and other supporting files. It
does not contain any development tools such as compiler, debugger, etc. Actually
JVM runs the program, and it uses the class libraries, and other supporting files
provided in JRE. If you want to run any java program, you need to have JRE installed
in the system.
 Java Virtual Machine interprets the byte code into the machine code depending
upon the underlying operating system and hardware combination. It is responsible
for all the things like garbage collection, array bounds checking, etc… JVM is
platform dependent.
Class - A class can be defined as a template/ blue print that
describes the behaviours/states that object of its type support.
Object - Objects have states and behaviours. Example: A dog has
states - colour, name, breed as well as behaviours -wagging,
barking, eating. An object is an instance of a class.
Methods - A method is basically a behaviour. A class can contain
many methods. It is in methods where the logics are written, data is
manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance
variables. An object's state is created by the values assigned to
these instance variables.
 Java is available at Download Java
 Right-click on 'My Computer' and select 'Properties'.
 Click on the 'Environment variables' button under the 'Advanced' tab.
 Set following environment variables:
 <JAVA_HOME> : Path to where java is installed.
Example: C:Program FilesJavajdk1.8.0_45
 <PATH> : Path to bin directory of jdk.
Example: C:Program FilesJavajdk1.8.0_45bin
 <CLASSPATH> : Path to lib directory of jdk.
Example: C:Program FilesJavajdk1.8.0_45lib
 Open command prompt.
 Run following command
 javac
 java
Compile-time EnvironmentCompile-time Environment
Java
Bytecodes
move locally
or through
network
Java
Source
(.java)
Java
Compiler
Java
Bytecode
(.class )
Java
Interpreter
Just in
Time
Compiler
Runtime System
Class Loader
Bytecode
Verifier
Java
Class
Libraries
Operating System
Hardware
Java
Virtual
machine
 javap takes a class and dumps
information about its methods to
standard out. It doesn't decompile
the code into Java source code,
but it will disassemble the
bytecode into the bytecode
instructions defined by the Java
Virtual Machine specification.
 Javap is useful when you want to
see what your compiler is doing
for (or to) you, or when you want
to see what effect a code
change will have on the compiled
class file.
public class Test1
{
String s = null;
public Test1()
{
s = new String();
}
}
$ javap -c Test1
Compiled from Test1.java
public class Test1 extends java.lang.Object {
java.lang.String s;
public Test1();
}
Method Test1()
0 aload_0
1 invokespecial #1 4 aload_0 5 aconst_null 6 putfield #2 9
aload_0 10 new #3 13 dup 14 invokespecial #4 17 putfield #2 20
return
 Classloaders describes the behavior of converting a named class into the bits
responsible for implementing that class.
 Classloaders are fundamental part of the Java Virtual Machine (JVM) that loads
classes into memory and is responsible for finding and loading class files at run-time.
At its simplest, a class loader creates a flat
name space of class bodies that are
referenced by a string name. The method
definition is:
Class r = loadClass(String className,
boolean resolveIt);
The variable className contains a string
that is understood by the class loader and
is used to uniquely identify a class
implementation. The variable resolveIt is a
flag to tell the class loader that classes
referenced by this class name should be
resolved (that is, any referenced class
should be loaded as well).
All Java virtual machines include one class
loader that is embedded in the virtual
machine. This embedded loader is called
the primordial class loader.
1) Bootstrap ClassLoader - JRE/lib/rt.jar
2) Extension ClassLoader - JRE/lib/ext or any directory denoted
by java.ext.dirs
3) Application ClassLoader - CLASSPATH environment variable, -
classpath or -cp option, Class-Path attribute
of Manifest inside JAR file.
 Delegation – Always the current associated Classloader delegates the request to
load a class to the immediate parent Classloader before attempting to load on their
own. Delegation happens only when a particular class is not loaded in cache
already.
 Visibility - Classes loaded by parent Classloader are visible to all child Classloaders
but not vice versa.
 Uniqueness - Once a class is loaded by any of its parent Classloader, child
Classloader in the hierarchy will never reload the class again.
Case Sensitivity - Java is case sensitive, which means
identifier Hello and hellowould have different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first
letter should be in Upper Case.
Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.Example public void
myMethodName()
Program File Name - Name of the program file should exactly match the class
name. When saving the file, you should save it using the class name (Remember
Java is case sensitive) and append '.java' to the end of the name (if the file name
and the class name do not match your program will not compile).
There can be
only one public
class per
source code
file.
Comments can
appear at the
beginning or end of
any line in the source
code file; they are
independent of any
of the positioning
rules discussed here.
If there is a public class
in a file, the name of
the file must match the
name of the public
class. For example, a
class declared as public
class Dog { } must be in
a source code file
named Dog.java.
If the class is part of a
package, the
package statement
must be the first line
in the source code
file, before any
import statements
that may be present.
If there are import
statements, they must go
between the package
statement (if there is one)
and the class declaration. If
there isn't a package
statement, then the import
statement(s) must be the
first line(s) in the source
code file. If there are no
package or import
statements, the class
declaration must be the first
line in the source code file.
import and package
statements apply to all
classes within a source
code file. In other
words, there's no way to
declare multiple classes
in a file and have them
in different packages,
or use different imports.
A file can have
more than one
nonpublic class.
 while loop:
 A while loop is a control structure that allows you to repeat a task a certain number of
times.
while(Boolean_expression){}
 do-while loop:
 A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
do
{
//Statements
}while(Boolean_expression);
 for loop:
 A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times
for(initialization; Boolean_expression; update){ // statements}
 Enhanced for loop in Java:
 As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
for(declaration : expression)
{
//Statements
}
A primitive can be one of eight types: char, boolean, byte,
short, int, long, double, or float. Once a primitive has been
declared, its primitive type can never change, although in
most cases its value can change.
Sample s1;
A variable that refers a class name is known as reference variable. A reference variable cannot work like an
object until it is converted into an object.
s1 = new Sample();
Reference variable is converted into an object.
 Instance variables are defined inside the class, but outside of any method, and are
only initialized when the class is instantiated. Instance variables are the fields that
belong to each unique object.
class Employee
{
// define fields (instance variables) for employee instances
private String name;
private String title,
private String manager;
// other code goes here including access methods for private // fields
}
Can use any of the four access levels
(which means they can be marked
with any of the three access modifiers)
Can be marked final
Can be marked transient
Cannot be marked abstract
Cannot be marked synchronized
Cannot be marked strictfp
Cannot be marked native
Cannot be marked static, because
then they'd become class variables.
 Local variables are variables declared within a method.
 That means the variable is not just initialized within the method, but also declared within the
method.
 Just as the local variable starts its life inside the method, it's also destroyed when the method has
completed. Local variables are always on the stack, not the heap.
class Foo
{
public void printHello()
{
String printText = “HelloWorld”
}
}
 Declaring a variable with the final keyword makes it impossible to reinitialize that variable
once it has been initialized with an explicit value (notice we said explicit rather than
default).
 For primitives, this means that once the variable is assigned a value, the value can't be
altered. For example, if you assign 10 to the int variable x, then x is going to stay 10,
forever. So that's straightforward for primitives,
 But what does it mean to have a final object reference variable?
 A reference variable marked final can't ever be reassigned to refer to a different object. The data
within the object can be modified, but the reference variable cannot be changed. In other words,
a final reference still allows you to modify the state of the object it refers to, but you can't modify
the reference variable to make it refer to a different object.
..
Multidimensional arrays are
actually arrays of arrays.
Syntax:
int twoD[][] = new int[4][5];
String is immutable ( once created can
not be changed )object . The object
created as a String is stored in
the Constant String Pool .
Every immutable object in Java is thread
safe ,that implies String is also thread safe .
String can not be used by two threads
simultaneously.
String once assigned can not be
changed.
String demo = " hello " ;
// The above object is stored in constant
string pool and its value can not be
modified.
demo="Bye" ; //new "Bye" string is
created in constant pool and referenced
by the demo variable
// "hello" string still exists in string constant
pool and its value is not overrided but we
lost reference to the "hello"string
 String is Immutable in Java because String objects are cached in String pool. Since
cached String literal is shared between multiple client there is always a risk, where
one client's action would affect all other client. For example, if one client changes
value of String "Test" to "TEST", all other client will also see that value.
 Another reason of why String class is immutable could de due to HashMap. Since
Strings are very popular as HashMap key, it's important for them to be immutable so
that they can retrieve the value object which was stored in HashMap.
Since HashMap works in principle of hashing, which requires same has value to
function properly. Mutable String would produce two different hashcode at the time
of insertion and retrieval if contents of String was modified after insertion, potentially
losing the value object in map.
 StringBuffer is mutable means one can change the value of the object . The object
created through StringBuffer is stored in the heap . StringBuffer has the same
methods as the StringBuilder , but each method in StringBuffer is synchronizedthat
is StringBuffer is thread safe .
StringBuffer demo1 = new StringBuffer("Hello") ;
 StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can
also be modified . The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread safe.
StringBuilder demo2= new StringBuilder("Hello");
 Exception handling allows developers to detect errors easily without writing special code
to test return values. Even better, it lets us keep exception-handling code cleanly
separated from the exception-generating code. It also lets us use the same exception-
handling code to deal with a range of possible exceptions.
 An exception means that an action member cannot complete the task it was supposed
to perform as indicated by its name.
 Look at the following class definition:
class Account {
public static void Transfer(Account from, Account to, float amount) {...
}
}
 The Transfer method accepts two Account objects and a float value that identifiers
an amount of money to transfer between accounts. The Transfer method could
failed for many reasons, like from or to argument might be null.
 When the Transfer method is called, its code must check for all the failed possibilities,
and if any of which is detected, it cannot transfer the money and should notify the
caller that it failed by throwing an exception.
 The Transfer method transfers money from one account to another. If this method
doesn’t validate its arguments right away, the method could subtract money from
the from account successfully, and then discover that the to account argument is
null.
 At this point, the method would throw an exception because it cannot transfer that
money. However, the method must also add that money back to the from account.
If it fails to do this, the state of the from account is incorrect.
 A ubiquitous mistake made by developers who have not been properly trained on the proper
use of exceptions is to use catch blocks too frequently and often improperly.
 When you catch an exception, you’re stating that you expected this exception, you understand
why it occurred, and you know how to deal with it. In other words, you’re defining a policy for
the application.
 This code indicates that it was expecting any and all exceptions and knows how to recover from
any and all situations.
try {
//try to execute code that the programmer //knows might fail..
}
catch (exception) {
}
 A type that’s part of a class library should never catch and swallow all exceptions
because there is no way for the type to know exactly how the application intends to
respond to an exception.
 If the application code throws an exception, another part of the application is probably
expecting to catch this exception. The exception should be allowed to filter its way up
the call stack and let the application code handle the exception as it sees fits.
 In addition, it is possible that an exception was thrown because some object was in a
bad state. If library code catches and swallows the exception, the program continues
running with unpredictable results and with potential security vulnerabilities.
 It is better for the exception to be unhandled and for the application to terminate.
 In fact, most unhandled exceptions will be discovered during testing of your code. To fix
these unhandled exception, you will either modify the code to look for specific exception,
or you will rewrite the code to eliminate the conditions that cause the exception to be
thrown.
 The final version of the code that will be running in a production environment should see
very few (if any) unhandled exceptions and be extremely robust.
 When an exception takes place, the JVM creates an exception object to identify
the type of exception that occurred
 The Throwable class is the super class of all error and exception types generated by
the JVM or java programs
 Three Throwable subclass categories are possible: Error, Runtime and Nonruntime
Exceptions
 Errors are events generated by the JVM that have had a critical and fatal impact on the running
application.
 They are typically not handled by regular programs
 ArithmeticException
 ArrayIndexOutOfBounds
 ArrayStore
 ClassCast
 IllegalArgument
 IllegalState
 IllegalThreadState
Runtime (unchecked
exceptions):
Arithmetic Exceptions: dividing by
zero
Null Pointer Exceptions:
attempting to reference a
method of a null pointer
Class Cast Exception: casting
incompatible object, super or
subclass types
Index Out of Bounds Exception:
accessing a index value outside
of an array range
Typically result from logical errors
 Nonruntime (checked exceptions):
 These exceptions occur outside of the runtime system
 Input / Output exceptions
 Caught or specified by the system compiler
 throw – to generate an exception or to describe an instance of an exception
 try – used to enclose a segment of code that may produce a exception
 catch – placed directly after the try block to handle one or more exception types
 finally – optional statement used after a try-catch block to run a segment of code
regardless if a exception is generated
try {
<code segment that may
throw an exception..>
} catch (ExceptionType) {
<exception handler..>
} catch (ExceptionType) {
<exception handler..>
} finally {
<optional code segment..>
}
try {
<code segment that may
throw an exception..>
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(“File Not Found!”);
}
Once a try statement has been used
to enclose a code segment, the
catch can be used to handle one or
more specific exception types. By
defining catch statements for
specific exception types, a more
accurate handling of the exception
can be tailored to the programs
needs.
The purpose of the optional finally
statement will allow the execution of
a segment of code regardless if the
try statement throws an exception or
executes successfully
The advantage of the finally
statement is the ability to clean up
and release resources that are
utilized in the try segment of code
that might not be released in cases
where an exception has occurred
 Here is a code sample showing how to define your own exception.
 Define a class:
public class EmptyStackException extends Exception { }
 Here is how you use the class:
public class Stack {
public Object Pop() throws EmptyStackException {
if (Empty()) throw new EmptyStackException();
...
}
}
 Note that you must use new to create an exception object; you cannot just throw
an exception.
 Assertions let you test your assumptions during development, but the
assertion code basically evaporates when the program is deployed,
leaving behind no overhead or debugging code to track down and
remove
Without Assertion
private void methodA(int num) {
if (num >= 0) {
useNum(num + x); }
else {
// num must be < 0
// This code should never be reached!
System.out.println("Yikes! num is a
negative number! " + num); }
}
With Assertion
private void methodA(int num) {
assert (num>=0); // throws an
AssertionError
// if this test isn't true
useNum(num + x);
}
Enabling Assertions at Runtime
You enable assertions at runtime with
java –ea com.geeksanonymous.TestClass
or
java -enableassertions com.geeksanonymous.TestClass
Disabling Assertions at Runtime
java -da com.geeksanonymous.TestClass
or
java -disableassertions com.geeksanonymous.TestClass
Command-Line Example What It Means
java -ea java -enableassertions Enable assertions.
java -da java -disableassertions Disable assertions (the default behavior of Java 6).
java -ea:com.foo.Bar Enable assertions in class com.foo.Bar
java -ea:com.foo... Enable assertions in package com.foo and any of its
subpackages.
java -ea -dsa Enable assertions in general, but disable assertions in
system classes.
java -ea -da:com.foo... Enable assertions in general, but disable assertions in
package com.foo and any of its subpackages.
 Don't Use Assertions to Validate Arguments to a Public Method
 Do Use Assertions to Validate Arguments to a Private Method
 Don't Use Assertions to Validate Command-Line Arguments
 Do Use Assertions, Even in Public Methods, to Check for Cases that You Know Are
Never, Ever Supposed to Happen
 Don't Use Assert Expressions that Can Cause Side Effects!

More Related Content

What's hot

Unit2 java
Unit2 javaUnit2 java
Unit2 javamrecedu
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & PackagesArindam Ghosh
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101kankemwa Ishaku
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packagesmcollison
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+javaYe Win
 

What's hot (20)

Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Unit2 java
Unit2 javaUnit2 java
Unit2 java
 
core java for hadoop
core java for hadoopcore java for hadoop
core java for hadoop
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Core java
Core java Core java
Core java
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & Packages
 
Core Java
Core JavaCore Java
Core Java
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
 
Core java
Core javaCore java
Core java
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 

Viewers also liked

Presentacion en equipo
Presentacion en equipoPresentacion en equipo
Presentacion en equipoonumkri
 
Chelysheva_E_poster presentation_EAFO
Chelysheva_E_poster presentation_EAFOChelysheva_E_poster presentation_EAFO
Chelysheva_E_poster presentation_EAFOEAFO2014
 
Googol Chp hot water
Googol Chp hot waterGoogol Chp hot water
Googol Chp hot waterMark Wang
 
ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16
ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16
ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16Lamprini Magaliou
 
Derecho de los alumnos en la retícula
Derecho de los alumnos en la retículaDerecho de los alumnos en la retícula
Derecho de los alumnos en la retícula111430383-5
 
Googol gas generaor model list
Googol gas generaor model listGoogol gas generaor model list
Googol gas generaor model listMark Wang
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objectsMahmoud Alfarra
 
We Need Multiple, Independent Web Archives
We Need Multiple, Independent Web ArchivesWe Need Multiple, Independent Web Archives
We Need Multiple, Independent Web ArchivesMichael Nelson
 
PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...
PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...
PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...Indian dental academy
 
pengurusan dan pembelajaran pelajar (kump15_buahnaga)
pengurusan dan pembelajaran pelajar (kump15_buahnaga)pengurusan dan pembelajaran pelajar (kump15_buahnaga)
pengurusan dan pembelajaran pelajar (kump15_buahnaga)Aamir Din
 

Viewers also liked (14)

Presentacion en equipo
Presentacion en equipoPresentacion en equipo
Presentacion en equipo
 
Chelysheva_E_poster presentation_EAFO
Chelysheva_E_poster presentation_EAFOChelysheva_E_poster presentation_EAFO
Chelysheva_E_poster presentation_EAFO
 
6 Undeniable Benefits
6 Undeniable Benefits6 Undeniable Benefits
6 Undeniable Benefits
 
Googol Chp hot water
Googol Chp hot waterGoogol Chp hot water
Googol Chp hot water
 
Tarea No. 2
Tarea No. 2Tarea No. 2
Tarea No. 2
 
ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16
ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16
ροδος εργασία Μπουσμαλή Άννας & Λάζρι Ντενίσα Γυμν. Κολινδρού 2015-16
 
Derecho de los alumnos en la retícula
Derecho de los alumnos en la retículaDerecho de los alumnos en la retícula
Derecho de los alumnos en la retícula
 
Presentación1
Presentación1Presentación1
Presentación1
 
Googol gas generaor model list
Googol gas generaor model listGoogol gas generaor model list
Googol gas generaor model list
 
European Travel Trends | Q2 2016
European Travel Trends | Q2 2016European Travel Trends | Q2 2016
European Travel Trends | Q2 2016
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objects
 
We Need Multiple, Independent Web Archives
We Need Multiple, Independent Web ArchivesWe Need Multiple, Independent Web Archives
We Need Multiple, Independent Web Archives
 
PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...
PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...
PATHOLOGY OF HYPERTENSION /certified fixed orthodontic courses by Indian dent...
 
pengurusan dan pembelajaran pelajar (kump15_buahnaga)
pengurusan dan pembelajaran pelajar (kump15_buahnaga)pengurusan dan pembelajaran pelajar (kump15_buahnaga)
pengurusan dan pembelajaran pelajar (kump15_buahnaga)
 

Similar to Java basics

Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Ayes Chinmay
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objectsvmadan89
 
Java syntax-and-grammars-oct8
Java syntax-and-grammars-oct8Java syntax-and-grammars-oct8
Java syntax-and-grammars-oct8MISSIASABTAL1
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel Fomitescu
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PunePankaj kshirsagar
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSujit Majety
 
Object Oriented Programming - Java
Object Oriented Programming -  JavaObject Oriented Programming -  Java
Object Oriented Programming - JavaDaniel Ilunga
 
Core java &collections
Core java &collectionsCore java &collections
Core java &collectionsRavi varma
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 

Similar to Java basics (20)

Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Java notes
Java notesJava notes
Java notes
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Java syntax-and-grammars-oct8
Java syntax-and-grammars-oct8Java syntax-and-grammars-oct8
Java syntax-and-grammars-oct8
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java PPT
Java PPTJava PPT
Java PPT
 
Object Oriented Programming - Java
Object Oriented Programming -  JavaObject Oriented Programming -  Java
Object Oriented Programming - Java
 
Java notes jkuat it
Java notes jkuat itJava notes jkuat it
Java notes jkuat it
 
Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
Java_presesntation.ppt
Java_presesntation.pptJava_presesntation.ppt
Java_presesntation.ppt
 
Core java
Core javaCore java
Core java
 
Core java &collections
Core java &collectionsCore java &collections
Core java &collections
 
Core java1
Core java1Core java1
Core java1
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Basic syntax
Basic syntaxBasic syntax
Basic syntax
 
Java basic-syntax
Java basic-syntaxJava basic-syntax
Java basic-syntax
 

Java basics

  • 2.
  • 3.  James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name Green and ended up later being renamed as Java, from a list of random words.  Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.  On 13 November 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).  On 8 May 2007, Sun finished the process, making all of Java's core code free and open- source, aside from a small portion of code to which Sun did not hold the copyright.
  • 4. Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model. Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master. Architectural-neutral :Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
  • 5. Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications. Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
  • 6. JDK: Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc… Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method. You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient. JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries. JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java
  • 7.  Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system.  Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.
  • 8. Class - A class can be defined as a template/ blue print that describes the behaviours/states that object of its type support. Object - Objects have states and behaviours. Example: A dog has states - colour, name, breed as well as behaviours -wagging, barking, eating. An object is an instance of a class. Methods - A method is basically a behaviour. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
  • 9.  Java is available at Download Java  Right-click on 'My Computer' and select 'Properties'.  Click on the 'Environment variables' button under the 'Advanced' tab.  Set following environment variables:  <JAVA_HOME> : Path to where java is installed. Example: C:Program FilesJavajdk1.8.0_45  <PATH> : Path to bin directory of jdk. Example: C:Program FilesJavajdk1.8.0_45bin  <CLASSPATH> : Path to lib directory of jdk. Example: C:Program FilesJavajdk1.8.0_45lib
  • 10.  Open command prompt.  Run following command  javac  java
  • 11.
  • 12. Compile-time EnvironmentCompile-time Environment Java Bytecodes move locally or through network Java Source (.java) Java Compiler Java Bytecode (.class ) Java Interpreter Just in Time Compiler Runtime System Class Loader Bytecode Verifier Java Class Libraries Operating System Hardware Java Virtual machine
  • 13.  javap takes a class and dumps information about its methods to standard out. It doesn't decompile the code into Java source code, but it will disassemble the bytecode into the bytecode instructions defined by the Java Virtual Machine specification.  Javap is useful when you want to see what your compiler is doing for (or to) you, or when you want to see what effect a code change will have on the compiled class file. public class Test1 { String s = null; public Test1() { s = new String(); } } $ javap -c Test1 Compiled from Test1.java public class Test1 extends java.lang.Object { java.lang.String s; public Test1(); } Method Test1() 0 aload_0 1 invokespecial #1 4 aload_0 5 aconst_null 6 putfield #2 9 aload_0 10 new #3 13 dup 14 invokespecial #4 17 putfield #2 20 return
  • 14.  Classloaders describes the behavior of converting a named class into the bits responsible for implementing that class.  Classloaders are fundamental part of the Java Virtual Machine (JVM) that loads classes into memory and is responsible for finding and loading class files at run-time.
  • 15. At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is: Class r = loadClass(String className, boolean resolveIt); The variable className contains a string that is understood by the class loader and is used to uniquely identify a class implementation. The variable resolveIt is a flag to tell the class loader that classes referenced by this class name should be resolved (that is, any referenced class should be loaded as well). All Java virtual machines include one class loader that is embedded in the virtual machine. This embedded loader is called the primordial class loader. 1) Bootstrap ClassLoader - JRE/lib/rt.jar 2) Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs 3) Application ClassLoader - CLASSPATH environment variable, - classpath or -cp option, Class-Path attribute of Manifest inside JAR file.
  • 16.  Delegation – Always the current associated Classloader delegates the request to load a class to the immediate parent Classloader before attempting to load on their own. Delegation happens only when a particular class is not loaded in cache already.  Visibility - Classes loaded by parent Classloader are visible to all child Classloaders but not vice versa.  Uniqueness - Once a class is loaded by any of its parent Classloader, child Classloader in the hierarchy will never reload the class again.
  • 17. Case Sensitivity - Java is case sensitive, which means identifier Hello and hellowould have different meaning in Java. Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example class MyFirstJavaClass Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.Example public void myMethodName() Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile).
  • 18. There can be only one public class per source code file. Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here. If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java. If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present. If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file. import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports. A file can have more than one nonpublic class.
  • 19.  while loop:  A while loop is a control structure that allows you to repeat a task a certain number of times. while(Boolean_expression){}  do-while loop:  A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. do { //Statements }while(Boolean_expression);
  • 20.  for loop:  A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times for(initialization; Boolean_expression; update){ // statements}  Enhanced for loop in Java:  As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays. for(declaration : expression) { //Statements }
  • 21.
  • 22.
  • 23.
  • 24. A primitive can be one of eight types: char, boolean, byte, short, int, long, double, or float. Once a primitive has been declared, its primitive type can never change, although in most cases its value can change.
  • 25. Sample s1; A variable that refers a class name is known as reference variable. A reference variable cannot work like an object until it is converted into an object. s1 = new Sample(); Reference variable is converted into an object.
  • 26.  Instance variables are defined inside the class, but outside of any method, and are only initialized when the class is instantiated. Instance variables are the fields that belong to each unique object. class Employee { // define fields (instance variables) for employee instances private String name; private String title, private String manager; // other code goes here including access methods for private // fields }
  • 27. Can use any of the four access levels (which means they can be marked with any of the three access modifiers) Can be marked final Can be marked transient Cannot be marked abstract Cannot be marked synchronized Cannot be marked strictfp Cannot be marked native Cannot be marked static, because then they'd become class variables.
  • 28.  Local variables are variables declared within a method.  That means the variable is not just initialized within the method, but also declared within the method.  Just as the local variable starts its life inside the method, it's also destroyed when the method has completed. Local variables are always on the stack, not the heap. class Foo { public void printHello() { String printText = “HelloWorld” } }
  • 29.  Declaring a variable with the final keyword makes it impossible to reinitialize that variable once it has been initialized with an explicit value (notice we said explicit rather than default).  For primitives, this means that once the variable is assigned a value, the value can't be altered. For example, if you assign 10 to the int variable x, then x is going to stay 10, forever. So that's straightforward for primitives,  But what does it mean to have a final object reference variable?  A reference variable marked final can't ever be reassigned to refer to a different object. The data within the object can be modified, but the reference variable cannot be changed. In other words, a final reference still allows you to modify the state of the object it refers to, but you can't modify the reference variable to make it refer to a different object.
  • 30. ..
  • 31.
  • 32.
  • 33. Multidimensional arrays are actually arrays of arrays. Syntax: int twoD[][] = new int[4][5];
  • 34. String is immutable ( once created can not be changed )object . The object created as a String is stored in the Constant String Pool . Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously. String once assigned can not be changed. String demo = " hello " ; // The above object is stored in constant string pool and its value can not be modified. demo="Bye" ; //new "Bye" string is created in constant pool and referenced by the demo variable // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the "hello"string
  • 35.  String is Immutable in Java because String objects are cached in String pool. Since cached String literal is shared between multiple client there is always a risk, where one client's action would affect all other client. For example, if one client changes value of String "Test" to "TEST", all other client will also see that value.  Another reason of why String class is immutable could de due to HashMap. Since Strings are very popular as HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Since HashMap works in principle of hashing, which requires same has value to function properly. Mutable String would produce two different hashcode at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in map.
  • 36.  StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is synchronizedthat is StringBuffer is thread safe . StringBuffer demo1 = new StringBuffer("Hello") ;  StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. StringBuilder demo2= new StringBuilder("Hello");
  • 37.
  • 38.  Exception handling allows developers to detect errors easily without writing special code to test return values. Even better, it lets us keep exception-handling code cleanly separated from the exception-generating code. It also lets us use the same exception- handling code to deal with a range of possible exceptions.  An exception means that an action member cannot complete the task it was supposed to perform as indicated by its name.  Look at the following class definition: class Account { public static void Transfer(Account from, Account to, float amount) {... } }
  • 39.  The Transfer method accepts two Account objects and a float value that identifiers an amount of money to transfer between accounts. The Transfer method could failed for many reasons, like from or to argument might be null.  When the Transfer method is called, its code must check for all the failed possibilities, and if any of which is detected, it cannot transfer the money and should notify the caller that it failed by throwing an exception.
  • 40.  The Transfer method transfers money from one account to another. If this method doesn’t validate its arguments right away, the method could subtract money from the from account successfully, and then discover that the to account argument is null.  At this point, the method would throw an exception because it cannot transfer that money. However, the method must also add that money back to the from account. If it fails to do this, the state of the from account is incorrect.
  • 41.  A ubiquitous mistake made by developers who have not been properly trained on the proper use of exceptions is to use catch blocks too frequently and often improperly.  When you catch an exception, you’re stating that you expected this exception, you understand why it occurred, and you know how to deal with it. In other words, you’re defining a policy for the application.  This code indicates that it was expecting any and all exceptions and knows how to recover from any and all situations. try { //try to execute code that the programmer //knows might fail.. } catch (exception) { }
  • 42.  A type that’s part of a class library should never catch and swallow all exceptions because there is no way for the type to know exactly how the application intends to respond to an exception.  If the application code throws an exception, another part of the application is probably expecting to catch this exception. The exception should be allowed to filter its way up the call stack and let the application code handle the exception as it sees fits.  In addition, it is possible that an exception was thrown because some object was in a bad state. If library code catches and swallows the exception, the program continues running with unpredictable results and with potential security vulnerabilities.  It is better for the exception to be unhandled and for the application to terminate.  In fact, most unhandled exceptions will be discovered during testing of your code. To fix these unhandled exception, you will either modify the code to look for specific exception, or you will rewrite the code to eliminate the conditions that cause the exception to be thrown.  The final version of the code that will be running in a production environment should see very few (if any) unhandled exceptions and be extremely robust.
  • 43.  When an exception takes place, the JVM creates an exception object to identify the type of exception that occurred  The Throwable class is the super class of all error and exception types generated by the JVM or java programs  Three Throwable subclass categories are possible: Error, Runtime and Nonruntime Exceptions
  • 44.
  • 45.  Errors are events generated by the JVM that have had a critical and fatal impact on the running application.  They are typically not handled by regular programs
  • 46.  ArithmeticException  ArrayIndexOutOfBounds  ArrayStore  ClassCast  IllegalArgument  IllegalState  IllegalThreadState Runtime (unchecked exceptions): Arithmetic Exceptions: dividing by zero Null Pointer Exceptions: attempting to reference a method of a null pointer Class Cast Exception: casting incompatible object, super or subclass types Index Out of Bounds Exception: accessing a index value outside of an array range Typically result from logical errors
  • 47.  Nonruntime (checked exceptions):  These exceptions occur outside of the runtime system  Input / Output exceptions  Caught or specified by the system compiler
  • 48.  throw – to generate an exception or to describe an instance of an exception  try – used to enclose a segment of code that may produce a exception  catch – placed directly after the try block to handle one or more exception types  finally – optional statement used after a try-catch block to run a segment of code regardless if a exception is generated
  • 49. try { <code segment that may throw an exception..> } catch (ExceptionType) { <exception handler..> } catch (ExceptionType) { <exception handler..> } finally { <optional code segment..> }
  • 50. try { <code segment that may throw an exception..> } catch (IOException e) { System.out.println(e.getMessage()); } catch (FileNotFoundException e) { System.out.println(“File Not Found!”); } Once a try statement has been used to enclose a code segment, the catch can be used to handle one or more specific exception types. By defining catch statements for specific exception types, a more accurate handling of the exception can be tailored to the programs needs.
  • 51. The purpose of the optional finally statement will allow the execution of a segment of code regardless if the try statement throws an exception or executes successfully The advantage of the finally statement is the ability to clean up and release resources that are utilized in the try segment of code that might not be released in cases where an exception has occurred
  • 52.  Here is a code sample showing how to define your own exception.  Define a class: public class EmptyStackException extends Exception { }  Here is how you use the class: public class Stack { public Object Pop() throws EmptyStackException { if (Empty()) throw new EmptyStackException(); ... } }  Note that you must use new to create an exception object; you cannot just throw an exception.
  • 53.  Assertions let you test your assumptions during development, but the assertion code basically evaporates when the program is deployed, leaving behind no overhead or debugging code to track down and remove
  • 54. Without Assertion private void methodA(int num) { if (num >= 0) { useNum(num + x); } else { // num must be < 0 // This code should never be reached! System.out.println("Yikes! num is a negative number! " + num); } } With Assertion private void methodA(int num) { assert (num>=0); // throws an AssertionError // if this test isn't true useNum(num + x); }
  • 55. Enabling Assertions at Runtime You enable assertions at runtime with java –ea com.geeksanonymous.TestClass or java -enableassertions com.geeksanonymous.TestClass Disabling Assertions at Runtime java -da com.geeksanonymous.TestClass or java -disableassertions com.geeksanonymous.TestClass
  • 56. Command-Line Example What It Means java -ea java -enableassertions Enable assertions. java -da java -disableassertions Disable assertions (the default behavior of Java 6). java -ea:com.foo.Bar Enable assertions in class com.foo.Bar java -ea:com.foo... Enable assertions in package com.foo and any of its subpackages. java -ea -dsa Enable assertions in general, but disable assertions in system classes. java -ea -da:com.foo... Enable assertions in general, but disable assertions in package com.foo and any of its subpackages.
  • 57.  Don't Use Assertions to Validate Arguments to a Public Method  Do Use Assertions to Validate Arguments to a Private Method  Don't Use Assertions to Validate Command-Line Arguments  Do Use Assertions, Even in Public Methods, to Check for Cases that You Know Are Never, Ever Supposed to Happen  Don't Use Assert Expressions that Can Cause Side Effects!