Friday, 2 May 2014

Java 7 Features You (Probably) Didn't Hear About

Underscores in Numeric Literals

Valid:

int mask = 0b1010_1010_1010;long big = 9_223_783_036_967_937L;long creditCardNumber = 1234_5678_9012_3456L;long socialSecurityNumber = 999_99_9999L;float pi = 3.14_15F;long hexBytes = 0xFF_EC_DE_5E;long hexWords = 0xCAFE_BFFE;

•Invalid:

float pi1 = 3_.1415F;float pi2 = 3._1415F;
long ssn = 999_99_9999_L;
int x1 = _52;int x1 = 52_;

int x2 = 0_x52;int x2 = 0x_52;


Strings in Switch Statements

int monthNameToDays(String s, int year) {
switch(s) {
case "April": case "June":
case "September": case "November":
return 30;
case "January": case "March":
case "May": case "July":
case "August": case "December":
return 31;
case "February”:
...
default:
...

}
NOTE:-
Did you know it produces generally more efficient byte codes than an if-then-else statement? Case Sensitive!


Diamond Operator works many ways…

With diamond (<>) compiler infers type…
List<String>strList = new ArrayList<>();
OR
List<Map<String, List<String>>strList =
new ArrayList<>();
OR
Foo<Bar> foo = new Foo<>();

foo.mergeFoo(new Foo<>());


Multi-Catch

try {
...
} catch (ClassCastException e) {
doSomethingClever(e);
throw e;
} catch(InstantiationException |
NoSuchMethodException |
InvocationTargetException e) {
// Useful if you do generic actions
log(e);
throw e;

}


More Precise Rethrow

public void foo(String bar)
throws FirstException, SecondException{
try {
// Code that may throw both
// FirstException and SecondException
}
catch (Exception e) {
throw e;
}
}
NOTE:-
•Prior to Java 7, this code would not compile, the types in throws would have to match the types in catch –foo would have to “throws Exception”

•Java 7 adds support for this as long as try block calls all the exceptions in the throws clause, that the variable in the catch clause is the variable that is rethrown and the exceptions are not caught by another catch block.


Varargs Warnings –Erasure

class Test {
public static void main(String... args) {
List<List<String>> monthsInTwoLanguages =
Arrays.asList(Arrays.asList("January",
"February"),
Arrays.asList("Gennaio",
"Febbraio" ));
}
}
Test.java:7: warning:
[unchecked] unchecked generic array creation
for varargs parameter of type List<String>[]
Arrays.asList(Arrays.asList("January",
^
1 warning
@SuppressWarnings(value = “unchecked”) // at call

@SafeVarargs // at declaration


Java NIO.2 –File Navigation 

Two key navigation Helper Types:
Class java.nio.file.Paths
Exclusively static methods to return a Path by converting a string or Uniform Resource Identifier (URI)
Interface java.nio.file.Path
Used for objects that represent the location of a file in a file system, typically system dependent.
Typical use case:

Use Paths to get a Path. Use Files to do stuff.


Java NIO.2 Features –Files Helper Class

Class java.nio.file.Files
Exclusively static methods to operate on files, directories and other types of files
Files helper class is feature rich:
Copy
Create Directories
Create Files
Create Links
Use of system “temp” directory
Delete
Attributes –Modified/Owner/Permissions/Size, etc.
Read/Write

Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
Files.copy(src, dst,
StandardCopyOption.COPY_ATTRIBUTES,

StandardCopyOption.REPLACE_EXISTING);


Java NIO.2 Directories


DirectoryStream iterate over entries

Scales to large directories

Uses less resources

Smooth out response time for remote file systems

Implements Iterableand Closeablefor productivity
Filtering support

Build-in support for glob, regex and custom filters
Path srcPath = Paths.get(“/home/fred/src”);
try (DirectoryStream<Path> dir =
srcPath.newDirectoryStream(“*.java”)) {
for (Path file : dir)
System.out.println(file.getName());

}


Standardize Nimbus Look and Feel

Better than Metal for cross platform look-and-feel
Introduced in Java SE 6u10, now part of Swing
Not the default L&F
Scalable Java 2D impl


Mixing of AWT and Swing –Works*

As of 6u12 and 7u1, some caveats for scroll bars


JDBC 4.1

Try-with-resources statement to automatically close resources of typeConnection,ResultSet, andStatement
try (Statement stmt = con.createStatement()) { // ... }
RowSet 1.1 introduces RowSetFactoryand RowSetProvider
//Factory options (impl) set on cmd line or metainf
myRowSetFactory = RowSetProvider.newFactory();
jdbcRs = myRowSetFactory.createJdbcRowSet();
jdbcRs.setUrl("jdbc:myDriver:myAttribute"); //etc
jdbcRs.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");

jdbcRs.execute();


Draggable Applet Decoration

Applet decoration settings apply equally to in browser and out of browser launches –borderless, etc.


JavaDoc Improvements in Java 7

Section 508 accessibility guidelines
Captions, headings, etc.
Previously, JavaDoc wrote to an OutputStream on the fly meaning it built the document sequentially, imposing limitations
Now uses internal “HTMLTree” classes
Generates compliant HTML
Allows for more advancements in the future
Removes limitation of only being able to execute only once in any VM
Was fine when used as a command line tool
Continuous build, etc, made it necessary to address this!


The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions.The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

Monday, 10 March 2014

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit.

Whenever You want to work on more than one objects you can use Collection.
ex- suppose I have 30 students and I want to send sms to all students.
I want to keep all 30 students in a single unit, so I will use collection, and I can transfer that single unit each and every where.


Two interface trees, one starting with Collection and including Set, SortedSet, List, and Queue, and the other starting with Map and including SortedMap.
and If we talk about API of Collection Framework.

Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements
In above diagram you can see various Interfaces.

Collection
Set
List
----------
---------

Set-  a collection that cannot contain duplicate elements.
List-an ordered collection (sometimes called a sequence).
Queue — a collection used to hold multiple elements prior to processing.
Deque — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Deque provides additional insertion, extraction, and inspection operations.
Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.
SortedSet — a Set that maintains its elements in ascending order.
SortedMap — a Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories. 

 Next day we will learn what are those classes which implements these above Interfaces, and How we will use Collection in our Programs.

Wednesday, 26 February 2014

How to Start Java Programming

Java is an Object oriented programming. you can easily start your java programming. I am going to provide some simple steps to create java program. without wasting your precious time on internet or books.

First Of All We are going to set up our computer to make and run java program.

so First of All download JDK (java development kit) from http://www.oracle.com/technetwork/java/javase/downloads/index.html

and Install it by double click on it.

After that

to be ensure java has installed successfully.
by default all java file goes into
C:\\program files\java\
There are two folder will be there
if(jdk 7) latest version of java technology

jdk1.7...
jre 7

then open jdk1.7 /bin then you will get all tools related to Java development.
we want access all /bin folder tools every where on my computer so I am going to set path
on my computer.

We will develop java program with notepad or any editor and cmd as a beginner.

After Installation
Set path

go to run and type -- sysdm.cpl
then click on Advance system security
then click on Advance Tab
then click on Environment variable
then you will get two variables

User Variable
System Variable

Go For User Variable and Click New
Variable Name -  path
Variable value - C:\Program Files\Java\jdk1.7.0_04\bin

and click ok

after that open a new cmd (if old cmd is open then close that)

and type javac

If Some switch open and Printing like this then you are now enable to compile and run ur program your computer


C:\Users\Pankaj>javac
Usage: javac <options> <source files>
where possible options include:
  -g                         Generate all debugging info
  -g:none                    Generate no debugging info
  -g:{lines,vars,source}     Generate only some debugging info
  -nowarn                    Generate no warnings
  -verbose                   Output messages about what the compiler is doing
  -deprecation               Output source locations where deprecated APIs are used
  -classpath <path>          Specify where to find user class files and annotation processors
  -cp <path>                 Specify where to find user class files and annotation processors
  -sourcepath <path>         Specify where to find input source files
  -bootclasspath <path>      Override location of bootstrap class files
  -extdirs <dirs>            Override location of installed extensions
  -endorseddirs <dirs>       Override location of endorsed standards path
  -proc:{none,only}          Control whether annotation processing and/or compilation is done.
  -processor <class1>[,<class2>,<class3>...] Names of the annotation processors to run; bypasses
default discovery process
  -processorpath <path>      Specify where to find annotation processors
  -d <directory>             Specify where to place generated class files
  -s <directory>             Specify where to place generated source files
  -implicit:{none,class}     Specify whether or not to generate class files for implicitly refere
nced files
  -encoding <encoding>       Specify character encoding used by source files
  -source <release>          Provide source compatibility with specified release
  -target <release>          Generate class files for specific VM version
  -version                   Version information
  -help                      Print a synopsis of standard options
  -Akey[=value]              Options to pass to annotation processors
  -X                         Print a synopsis of nonstandard options
  -J<flag>                   Pass <flag> directly to the runtime system
  -Werror                    Terminate compilation if warnings occur
  @<filename>                Read options and filenames from file


C:\Users\Pankaj>