Sei sulla pagina 1di 14

JAva TRaining

JRE ----made of 2 things -JVM (Java virtual machine) -library

JAva is both compiled and interpreted

Hotspot VM (one of the components within JVM) ---JIT compilers --- byte code is loaded into memory first time and then converted into native code and kept in memory for future execution

JVM----| |________Class Loader | |________JIT Compiler | |________ByteCode Verifier (To detect changes made directly in the bytecode)

*Multithreading is built in , in Java language

java libraries .jar files

JDK will have 1. A compiler (javac) 2. an interpreter (java) 3. a doc generator (javadoc) 4. libraries (.jar)

J2SE standard edition --- contains language basics (only standalone and web based applets)

J2EE enterprise edition --- API tools which are used to develop enterprise applications

J2ME Micro edition -- for mobiles

KVM -- different kind of VM small memory footprint

J2SE = Java 5 (version 1.5) we already have 1.6,1.7 J2EE = JEE

Only one public class in one source file is allowed. name of file = name of the public class. If there is no public class in the source file , name can be anything

output of compilation (javac) is a file named after the class getting compiled containing the main method.

public static void main(String args[]) {

} //static functions bind to class, can be called without object creation, so main must be static. //args will store the command line arguments.

bootstrap class loader bootstraps the java program (loads the first class) and then subsequently used classes are loaded into memory.

Variable Types :

1. Instance variables -- ones defined within a class (non-static) 2. Local var 3. class var (static vars inside class)

//non-static block //this block is executed on object creation (goes within the contructors) { }

//static blocks //this block is executed only once when the class is loaded static{ }

javadoc comments are used by javadoc - can be used to generate javadocs /** text @author --> special annotations

@version*/

BigInteger --->

arrays are objects in java

*passes value of reference of object when objects are passed to a method

Typecasting

1. Typecaste variable and 2. Typecaste objects

there are wrapper classes for each primitive in java (just so you can use them as objects)

containers only work with wrapper types , not with primitive type

auto boxing/unboxing --> assign wrapper class type to primitive type and vice versa

identity equalizer/checker (==) [If 2 references refer to the same object in memory]

otherwise use Object equals() (we can define when to treat 2 objects as equal)

String is a special class (immutable)

str1 = "Java Training"; str2 = "Java Training";

content of a string variable is immutable. whenever a string is changed , a new object is created with the new content.

System.out.ptintln("Same?" + str1==str2); //prints true!!

str1 = "Hello"; str2 = "World"; str2 = ""

Strings are created in a string constant pool whenever strings are created with string literals , in heap area. So such behavior holds true across classes!!

for cases where heavy manipulation is required , always use StringBuffer and StringBuilder. These are mutable classes having method called append. So whenever changed , a new object is not created , but the old one is modified.

Methods in StringBuffer are synchronized (so can be used in multithreaded apps , are threadsafe) methods in StringBuilder are not synchronized.

In java there is a class called class. This keeps track of type of object. getClass() returns the object of class class.

String name = myobject.getClass().getName() boolean ex1 = "Texas" instance of String; //true

java.lang is the package that contains the language fundamentals. Every class implicitly extends/inherits from a class called object.

pojo = plain old java object

this() contractor call

this() can be used to call a constructor from another constructor

public StudentRecord(){ }

public StudentRecord(string gh){ this(); //must be the first statement of a constructor and can only be used within a constructor //definition }

Access Specifiers 1. public 2. protected 3. default (you don't specify anything) 4. private

An outer class can either be default or public in java , cannot be private , protected

protected is available to all classes within the package and to subclass outside the package

When a class extends another class it is called a subclass

classes are wrapped in .jar files to be distributed as libraries . They can also me executables.

Java bean is something that can be reused and which can expose its properties

public class test(){ public test(){ }

public method(){ // }

public class bash extends test{ public yash(){ super() //calls the base class constructor . must be the first line }

public method2{

super.method(); } }

Final Classes - Classes that cannot be extended . example String class Final is also a way to create immutable objects . Those objects which cannot be changed.

Final methods cannot be overridden. The main method is final. (not necessary to specify explicitly)

Headfirst Java ****

EXCEPTION HANDLING exception raising___

*throw new <name of class for which exception is to be created> *throws <IO exception>

public void method () throws ageException

errors --> cannot be recovered exception -->can be recovered

All runtimeException are unchecked exceptions , others are checked exceptions.

Extend your class from runtime exception or the other ones.

Memory model :

Java program starts 3 memory areas :

Code Area : where JIT code is kept , heap area = stack area =

Instance members would always go in heap . Objects always go in heap.

static variables also go in heap .

Local variables go in stack.

Java collections

hash code () method returns a hash representation of any object in java (32 bit integer representation)

hashCode method is overridden if equals is overridden(). If 2 objects are expected to be equal their hash codes shud be the same.

Within the map interface is a nested interface called entry. Every entry has key , value parts

Also see the comparator function*

Earlier there were only 2 classes : Vector and HashTable (these are synchronized classes) , present as legacy classes.

java -xss <stacksize 512MB>

ways in which sync can be done :

lock is applied on object

sync method -- > lock is applied on the object instance synch static methods --- > lock is applied on class object of type object sync block

sync blocks are used for : Atomicity Critical sections : sections which can have race conditions

Memory visibility

quartz -- > open source software to do cron jobs

timer class / timer task class for scheduling jobs

system.out.format("time's up" %n);

Concurrency :

new package in java 5 : java.util.concurrent

patterns seen in the industry have been provided here for multithreading

task scheduling framework:

runnable .run does not return any value , callable can return the value needed between threads

synchronizers : Semaphores are typically used to retract access to fixed size pool of resources.

CountDownLatch -- > in threads there is method called join . if main() says t1.join() and t2.join() then main will wait until both of them are also completed. So if one thread says countDown(5) : Once all 5 threads complete then only that thread will continue

keep waiting for a group of threads to be completed. Countdown latch cannot be restarted.

CyclicBarrier keep waiting for all the threads to reach a particular point ,then continue together

A vector and arraylist classes both use dynamic arrays

In vector the methods are synchronized , a vector is thread safe. Arraylist is not

class x { get() put() }

when is the class thread safe ? if i share the object of this class across threads , and then invoke methods of this class , and i don't corrupt the object data , then it is threadsafe Best way to make thread safe is to make objects immutable. by using final keyword.

2 ways to use synchronized lists :

--- collections.synchronizedList(list) , it returns a list which is synchronized . basically a wrapper that makes all the methods of this list synchronized.

concurrent collections provide a syncHashMap --just a wrapper ; while iterating over a collection , the item number might change , but in multithreading environment we expect it might change , thats why syncHashMAp doesn't throw such exception . The size method for this is approximation method.

Atomic Variables

atomic integer will provide methods like increment decrement which are synchronized.

Locks : lock classes for added flexibility like non-blocking access using tryLock()

synchronized blocks by default are re entrant read write lock()

If you want to send the object on network or write it on disk , you want it to be serializable . To be able to serialize a object , you must implement serializable interface

class student implements Serializable {

//otherwise compiler will generate this for you , to check the sanctity of class. private static final long serialVersionUID = 343848582092000L; //to generate this , use a tool in /java/bin using generateserialVersionUID otherwise in eclipse auto

student s; Objectoutputstream ops = new ObjectutputStream(); oos.writeobject(s) ;

when deserializing , constructor is never called. make any variable transient to prevent them from being serialization.

externalizable :

long and double shut not be applied to volatile because java uses 232 bits for that .

Potrebbero piacerti anche