Java Home: JAVA_HOME= C:\Program Files\Java\jdk1.8.0_45;
It is a JDK/jre installation directory. Programs look for the Java_Home environment variable, when they need java run
Which one should java home point, JDK or JRE
Developers should need to point to the JDK where utilities such as javac reside. Others, can point to the JRE. the JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.
Path: It describes the location where executable (javac, java) are available. It is referred by Operating System eg: patch=<Java Home>\bin;
Class Path: It describes the location where the required .class files are available. It is referred by both java compiler and jvm.
NOTE: To place a jar file in class path, one have to include the name of jar file. Directory alone is not sufficient.
JAR file - Java Archive
- Bundles all the resources and class files associated to a project
- Advantages are security, download time,compression, portability and versioning
- Compile .java class files
javac -d . Hello.java - Create jar file
jar -cvf hello.jar Hello.class Hello$1.class <picsfolder if any>
- Create a java file com.team1.MHello
- Generate .class files
javac -d . MHello.java - Create manifest file with any name eg: manifest.mf and mention the class with main()
Main-Class: com.team1.MHello - Create jar file
jar -cvfm ehello.jar manifest.mf com/team1/Hello.class Hello$1.class <picsfolder if any> - Execute jar file
java -jar hello.jar
OR
Double click the jar file from Windows file explorer
- Create project & java files
- right click on project name -> Export -> Runnable jar file(under java folder) -> Create jar under launch configuration-> select required destination directory -> Finish
Java Web Start is a mechanism for program delivery through a standard Web server. Typically initiated through the browser, these programs are deployed to the client and executed outside the scope of the browser. Once deployed, the programs do not need to be downloaded again, and they can automatically download updates on startup without requiring the user to go through the whole installation process again.
- Create a simple program and jar it as TestJnlp.jar
jar -cf TestJnlp.jar *.*
- Create and assign keystore into TestJnlp.jar
keytool -genkey -keystore testKeys -alias jdc jarsigner -keystore testKeys TestJnlp.jar jdc
- Copy "TestJnlp.jar" to Tomcat's default web server folder, for example, in Widnows - C:\Program Files\Apache\Tomcat 6.0\webapps\ROOT
- Create a Jnlp file Test.jnlp
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/" href="Test.jnlp">
<information>
<title>Jnlp Testing</title>
<vendor>YONG MOOK KIM</vendor>
<homepage href="http://localhost:8080/" />
<description>Testing Testing</description>
</information>
<security>
<all-permissions/>
</security>
<resources>
<j2se version="1.6+" />
<jar href="TestJnlp.jar" />
</resources>
<application-desc main-class="com.mkyong.TestJnlp" />
</jnlp>
- Deploy jnlp file
Copy Test.jnlp to your Tomcat default web server folder also. C:\Program Files\Apache\Tomcat 6.0\webapps\ROOT - Access TestJnlp.jar from web through http://localhost:8080/Test.Jnlp
Access URL http://localhost:8080/Test.jnlp, it will prompt you to download the Test.jnlp file, just accept and double click on it.
Use JAR file in Client Program
- Copy jar file to D:\
- javac -cp d:\hello.jar client.java
- java -cp .;d:\hello.jar client
OR - alternatively one can place the jar file in jdk -> jre -> lib -> ext folder
Java, javaw, javaws
java -> execute program with console output
javaw -> execute program out console output(used in gui based applications)
javaws -> java web start utility -> It downloads and launches web application
eg: javaws D:\Cloud.jnlp"
Jar vs War vs EAR
Jar -Java archive - Group of .class files
war - web archive - Represent one web application and may contain jsps, servlets, html, css, js, xml
ear - enterprise archive - to package any thing from j2ee suite - ejb, jms
enum - Enumeration Data Type
To represent group of named constants. It is to define our own data types.
Every enum constant is public static final and represents an object of type enum
Enum is internally implemented using class concept.
every enum constant is an object of type enum
Declaration:
enum Month
{jan, feb};
internally converted to:
class Month
{
public static final Month jan=new Month();
public static final Month feb=new Month();
}
Usage:
class Test{
public static void main(String[] args){
Month mth=Month.jan;
}
}
All enums should be direct child(extends) of java.lang.Enum class
Every Enum is always final implicitly, and hence cannot be extended.
Enums can implement Interfaces
java.lang.Enum is the base class for all enums. It is an abstract class, and hence cannot create an object of Enum class. It is direct child class of Object. It implements Serializable and Comparable interfaces.
Abstract Class:
Abstract classes are incomplete. Subclasses must declare the "missing pieces" to become "concrete" classes, from which you can instantiate.
eg:
abstract class Animal{
String color
abstract void printInfo();
}
Purpose:
Provide appropriate super class from which other classes can inherit and thus share a common design.
We can have variable whose type is abstract class. The actual object to which it refers must be an instance of concrete subclass.
Constructors and static methods cannot be declared as abstract.
Interface
- Interface is declaration of methods and doesn't have any definition
- Methods in interface are public and abstract
- Any field that is declared is public, final and static
- Interface cannot be final, it gives compiler error. Only public and abstract are allowed
- Interface with NO method declarations is called marker interface.
- It is to flag or give permission to execute a particular functionality
- Marker interface is used as a added to inform a message to the java compiler so that it can add special behavior to the class implementing it
- Eg of marker interfaces in JDK api are Serializable, Remote, Cloneable, Activateble
- Why do we need Interfaces
- No multiple inheritance in java - Cannot extend more than one class at a time
- Interface can extend any number of interfaces
- Usage of interfaces
- Interface help in loose coupling
Interface vs Abstract class
Interface
Don't know any thing about implementation, just have specification
Every method is always public and abstract
Can't declare interface methods as private and protected. Also with final, static, synchronized. native and strictfp as the methods are Abstract
Every variable present inside interface is public, static and final implicitly
We can't declare instance block and static block inside interface
Constructor not applicable
Abstract Class
We have/know partial implementation.
Every method need not be public and abstract
No restriction to method modifiers.
Variables need not be public, static and final implicitly
constructor can be present
Access Specifiers vs Access Modifiers
In java there is no terminology like access specifiers, all are access modifiers.
public, private, protected, default
final, static, synchronized, abstract, native, transient, volatile, Strictfp
java.lang.Object
- It is parent class to any class in java either directly or indirectly.
- Java Compiler adds Object class as parent if it doesn't extend any other class.
- It contains 11 methods which are required for any class in java
- toString()
- This is called when a class reference is printed. It returns object in string form
- if not overridden in child class, it returns getClass().getName()+"@"+Integer.toHexString(hashCode())
- It is highly recommended to override toString() in the child class
- hashCode()
- jvm assigns unique value for every object to identify objects uniquely. It is based on address of object.
- equals()
- to compare content of objects
- clone()
- to create duplicate object to current object
- finalize()
- Before destroying any object, garbage collector calls this method.
- getClass()
- used to know current class name. It returns Class class object
- notify()
- notifyAll()
- wait()
- wait(long ms)
- wait(long ms, int ns)
- All wait() and notify() are for inter thread communication.
Java Bean is a simple java class with private variables and public getter and setter methods.
public class MyBean
{
private String name;
private boolean empty;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public boolean isEmpty(){ //getEmpty is also fine, but isEmpty is recommended
return empty;
}
Listeners listens to events and performs appropriate actions automatically.
Case1: To register a listener
public void addMyActionListener(MyActionListener l) //method name should be prefixed with add and parameter type should be method name
Case2: To unregister a listener
public void removeMyActionListener(MyActionListener l) //method name should be prefixed with remove and parameter type should be method name
New vs NewInstance
- new operator can be used only if we know the Class name at the design time. Can't be used if class name is available only at run time
- NewInstance can be used if class name is available only at run time.
- When new operator is used, if .class file is not available at run time, then it will raise Runtime Exception-NoClassDefFound error
- When newInstance method is used, if .class file is not available at run time, then it will raise Runtime Exception-ClassNotFoundException. It is a checked exception.
Parent p=new Child() vs Child c=new Child()
- We should go for Parent p=new Child(), when we do not know exact object type at run time. eg: return from ArrayList as ArrayList can hold hetero genious objects.
- By using parent reference, we can invoke only methods from Parent class.
instanceOf vs isInstance
Abstract Class vs Abstract Method
We can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.
Java
- JAVA_HOME(Java installation directory)
- C:\Program Files\Java\jdk1.6
- Path & Classpath
- Both are operating system level environment variables. %JAVA_HOME%\bin
- Path is to define the location where the system can find executables(.exe).
- Classpath is location where required class/jar files are available. It is referred or used by Java compiler & JVM. It is required only when third party jar files are referred. eg: jdbc driver.
- The classpath is the conventional way to tell the Java compiler and the Java runtime where to find compiled classes.
- The classpath used by the compiler and the runtime system don't have to be the same
- Buildpatch(IDE terminology)
- IDE uses this to figure out the classpath and sourcepath for compiling the Java code, and the classpath for running it.
- IDE also uses the build path to figure out how to package up your code and its dependencies as (for example) a WAR file.
- JDK, JRE & JVM
- JDK provides environment to develop and run java applications
- JRE provides environment to just run java applications
- JVM is an interpreter (part of JRE), which is responsible to execute the java applications line by line.
- JDK= JRE +Development tools
- JRE=JVM+Library classes
- JVM=Java interpreter + Just in time compiler (JIT)
- JIT
- Part of JVM.
- Repeatedly used code/classes are pre compiled to machine language and makes it available to JVM.
- Platform independent high level programming language
- Modifiers
- JVM
- Packages
- Exception handling
- Interfaces - for Dynamic binding
- Threads
- Network programming
- Nested classes
- Util packages
- Java Beans
- Applets and applet programming (AWT)
- Java native interface - to access system resources(replacement for pointers)
- Almost purely Objected Oriented Language (except primitive data types)
- Platform independence -> OS independent
- Architecturally neutral -> hardware independent (JVM and byte code)
- Charecter
- char - 2 bytes to support unicode chars
- Integer
- short - 2 bytes
- int - 4 bytes
- long - 8 bytes
- byte - 1 byte
- Float
- float - 4 bytes
- double - 8 bytes
- Boolean - 1 bit
- int a[]=new int[5];
- String
- Non Mutable class(Which means the value cannot be changed)
- String s={"hello"} //Memory allocated on method area
- String s=new String("Hello"); //Memory allocated on heap area
- StringBuffer
- Mutable class
- Use StringBuffer when ever modifications are needed
- methods
- length(), indexOf(), charAt(), subString(), compareTo(), equals(), equalsIgnoreCase()
Wrapper Classes:
- Classes that exists for every primitive data type
- Integer, Float, Character
- These are needed to convert from one data type to another
- Integer.parseInt(<String>)
- When method parameter is of Object type
Modifiers
Static block
Private constructor- abstract
- static -
- can be given to any member but not to class
- Its global for all the objects
- memory is allocated in method area when class is loaded into jvm
- accessed by class name
- It cannot access instance member directly
- 'this' cannot be referenced in static method
- final
- class, variable, method
- final variable can be declared either during declaration or in constructor
- final methods cannot be overriden in sub class
- final class cannot have sub class
- native
- transient
- synchronized
- access specifiers - To specify the scope of members of class and class itself. Variable, member, constructor.
- Private - access within same class
- Protected
- within the same class where member is defined
- Within sub classes within same/different package
- With in non-sub class using an object provided it is in same package
- default/package scope - access within same class, Child class same package, non sub class with in same package
- Public - any where
- Private & Protected can be given to any number of a class but not for class itself.
Static block
- They get executed as soon as class is loaded into jvm
- executed only once
- executed once per object
- executed before constructor
- Constructor is defined as private, when the class is to be made as single ton pattern.
- Singeton pattern means, for a class at a any point should have a single instance
- Users cannot create instance from outside
- Eg:
Class A{
static A obj;
private A(){}
public static getA(){
if (obj==null){
obj=new A();
}
return obj;
}
}
- Child class can only expand the scope of the inherited methods but cannot restrict the scope
- They are pure abstract classes, which doesn't have any implementation.
- It should contain methods of type public and abstract only
- Variables should be public, static & final (Class constants)
- Even if the modifiers are not mentioned explicitly, methods are treated as public & abstract, variables as public, static & final
- An interface can extend/inherit other interfaces
- interface i3 extends i1,i2
- A class implementing any interface should mandatoryly implement all the methods.
- Interfaces are used for dynamic binding
- They are interfaces with noting defined in them
- Interface m {}
- It is used to flag or give permission for a class to execute particular functionality
- Marker interfaces that exists as part of jdk api
- Cloneable - To make bit by bit copy of an object
- Clone() is a protected class in Object class and throws CloneNotSupported Exception
- A a2=(A)a1.clone();
- Remote - To access an Object on another machine
- Serializable -
- Activatable
- instanceOf() is the method used to check if a particular object is of particular Class Type or Interface Type. Alternatively, one can use reflection api as well
- Abstract class can have any scope members
- Abstract member cannot be private
- Abstract class can have combination of implemented and non implemented methods
- Java packages exist as directories in file system and contain related class files
- Classes from different packages can derive from each other
- When a class is in a package, package name should specified in which the class is available by using import statement.
- Only the classes that are referred in the client code are compiled & loaded at run time, even when all the classes are referred using import A.*
- At compilation time, the import statements are removed & the class references are overridden with fully qualified names.
- It is good coding practice to specially import required classes rather than using *.
- * means only the classes in speicified package/directory and not its sub classes.(non recursive)
- When class belongs to package, the compile command should use -d option.
- javac -d <path> <file.java> //path should specify the parent directory where the package directory should reside.
- Exceptions are run time errors(that happen due to bad code/program)
- ClassCastException - When you downcast a class to a wrong type
- EndOfFileException - Access a file beyond its length
- NumberFormatException - Convert a alpha numeric string using parseInt method
- IllegalAccessException - Access method which is not in scope
- NullPointerException - Access Object variable on an object that is not yet referencing any where(still null)
- ArrayIndexOutOfBounds - Try access array beyond length
- ArthimeticException - devide by zero
- How to handle run time errors
- Using if-else statements - However, it becomes too complex due to nested statements and code readability becomes difficult.
- Exception handling
- Handling exceptions in Java
- try {} catch(<ExceptionType to be handled obj>){ <instructions to be executed>} finally{}
- Try block can have any number of catch blocks but only ONE finally block
- Child Exception should come first than Parent exception
- Try block must have atleast a Catch() or finally block.
- Checked & Unchecked exceptions
- Exceptions checked by compiler are known as Checked exceptions
- eg: SQLException, IOException
- Unchecked exceptions - Runtime exceptions
- When exception is raised, an object of that Exception Type is created and thrown. The Object is captured in the catch block. The code after the catch block will be executed as usual.
- Finally block will be executed regardless of what ever happens (Return, break, unhandled exception). Only in case of System.exit, it will not execute Finally block.
- try catch block can be placed with in try, catch or even finally block as well.
- Exception Object printStackTrace() - It gives ErrorMessage, line where error has occured, and ExceptionType at the console.
- obj.getMessage() - returns the error message alone.
- UserDefined Exceptions:
- public class MyException extends Exception {
<add default & parameterized constructor, and call super constructor passing the message>
} - Throw - To raise exception
- throw new MyException()
- Throws clause is used to Propagate an exception. When ever there is a throws clause against a method, caller of method must handle the exception by writing a try & catch{}.
- Re-throw exception : Have both try , catch block and re-throw the exception at the end of catch block.
- If main() throws exception(not handled), jvm handles it by writing the stack trace to console and exit the program.
- Object -> Component -> Container-> Panel -> Applet
- LifeCycle Methods
- init->start->paint->stop->destroy
- public class myApp extends Applet
- JVM creates applet class instances using reflection API
- 2 types of Applets
- Trusted Applet
- In trusted applet, we specify in policy file the permissions what the applet should be given to do on the local machine. And generate a public/private certificates using key tool or 3rd party certificates. Sign the jar file using the certificate. And then load on to client machine.
- Untrusted Applet
- By default the applets one writes is Untrusted. Applet cannot access local machine/network machines to read/write a file.
- Abstract Window Toolkit. It provides limited set of components. It is because AWT depends on OS to build components. Its all native calls.
- Only components that are supported by all platforms are available in AWT package. Hence, AWT components are limited and basic.
- We have components like Button, Text Field, Choice, List, Menus, ScrollBar, Window, Frame, Panel, Dialog, Label
- Menu
- Menus are supported only by Frames in AWT. Frame has a MenuBar.
- Any option that has sub option is of type Menu.
- Any option that executes on selection is Menu Item
- Any option of type toggle is of type CheckBoxMenuItem
- Layouts
- Layouts define how the components are placed on a container
- FlowLayout
- Default layout for Panel and Applet
- Places components one after another in a row and moves to next row when the given row is filled
- It is aligned to center by default
- BorderLayout
- Default for Frame and Dialog
- Max 5 components only(North, South, East, West & Center)
- CardLayout
- Component takes entire space of the container. Similar to Tab cards.
- GridLayout
- Container having Grid Layout is divided into number of cells. Place components into each of the cell. The component occupies complete cell
- It extends by columns when the number of cells is not enough
- GridbagLayout
Nested Classes:
Jar, War and EAR
Ways to run java program
- Class with in a class
- Nested class is not recognized by jvm. Hence, a .class file is generated for inner class as well with name Outer$Inner.class
- As the inner class is member of outer class, the access specifier can be private, protected, static as well(which is not the case for outer class)
- Instantiate inner class
- Outer out = new Outer();
Outer.Inner in=out.new Inner();
in.disp() - //for static inner class
Outer.Inner in=new Outer.Inner();
- RunOutOfMemory
- StackOverflow
- Java Beans is a component architecture of Java. It allows you to define components
- It is just another java class but follows certain rules/procedures
- Must implement Serializable interface. It is because the bean has to be serialized when class that uses the bean is serialized
- Will have setter, getter methods for all its properties
- It is a reusable, inter operable software component.
- Component is a group of classes that interact with each other to fulfill a single purpose. One component is one single functionality, but it consists of multiple classes.
- eg: JButton -
- Components can be either GUI bases or Non-GUI based
- GUI components will be derived from Component Class. Non-GUI based component doesn't derive from any of the Component classes
- Java bean should ideally support following
- properties & accessors
- Might have event handlers - so support communication between 2 beans
- Must implement serializable interface for persistence
- Public default constructor so that the object will be created via reflection
- Upon a bean, a builder tool should be able to make a reflection and be able to create an object.
- Using a builder tool, if you were to drag and drop an object into design area, the builder tool should be able to create instance of your bean and be able to display properties of bean via reflection.
- Using customization, one can specify what properties to be exposed for runtime environment.
- 4 type of properties for a bean
- Simple - has Set & Get
- Index - Used for Arrays.
- bound - set & is for boolean
- PropertyChangeEvent consists old value, new value & property name
- It will have add listener method as well
- constraint - Veto change listeners- property change is allowed only if veto passes. It is in addition to value change listener
- Bean uses property support object to hold list of listners
- It should also supply registration and deregistration support.
Jar, War and EAR
- Jar - Java Archieve
- group of .class files
- War - Web Archieve
- Project transportation, delivery and deployment will be easy
- Placing the war file in webapps folder will work
- Each war file represents one web application
- We can use only web related technologies in war file. Like servlets and jsps
- Ear - Enterprise archieve
- Any thing from java & J2EE - EJB, JMS and so
- Create a jar file(zip file)
- jar -cvf dv1.jar <list of class files>
- jar -cvf test.jar c:\work d:\test
- Any type of file can be placed in jar
- Extract a jar file(unzip)
- jar -xvf <jar file>
- Find the contents of jar
- jar -tf <jar file>
- Create manifest.MF file providing the class name that has main method
- Main-Class:JarDemo
- Create jar file
- jar -cvfm myexecjar.jar demo.class demo$1.class manifest.mf
- Execute jar file
- java -jar myexecjar.jar
Ways to run java program
- java .classfile
- java -jar myexecjar.jar or double click jar file
- double click batch file
- How message is transferred from one appln to another residing on two different machines
- Source
- TCP handler adds source & destincation port numbers
- IP layer adds the protocol from which the message is obtained, source & destincation IPs to the message
- Ethernet layer adds source IP, ethernet card address of source & destination. Destination ethernet card address can change incase rounters between source & destination
- Destination
- Ethernet layer - When ethernet address matches, it picks up and pass to IP address
- IP reads the message and passes to respective TCP/UDP layer based on protocol
- TCP layer routes the message to the appln running on the respective port
- Accepts client connections, creates new socket(at different port) to client interaction when client requests connection. Serversockets will wait for next connection requests
- Every socket(both at server and client side) will have Input & output Streams
- What user reads from client input stream is obtained from Server output stream. What ever is writtern on client output stream is input to server input stream.
Java IO
- Stream is channel or medium that allows continous flow from input(Keyboard, network, mouse..) to Java applns and java appln to output devices(Monitor, Printer, Network..)
- Types of Streams
- Byte oriented streams
- InputStream
- OutputStream
- Character Oriented Streams
- Reader
- Writer
No comments:
Post a Comment