1.Basic Programme
import java.io.*;
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
}
}
C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram
2.Naming
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.
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.
Program File Name - Name of the program file should exactly match the class name. There can be only one public class per source file.
3.Constructors
public class Puppy{
int puppyAge;
public Puppy(String name){
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
Puppy myPuppy = new Puppy( "tommy" );
myPuppy.setAge( 2 );
myPuppy.getAge( );
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
4.Instances
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
5.Data Types
byte, short, int, long, float, double, boolean, char, String, boxing
data type variable [ = value][, variable [= value] ...] ;
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; //array of characters
Character ch = new Character('a');//using ahcracters
Format strings:
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
(or)
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
6.Modifiers
private, public, protected
static, final, abstract, synchronized, volatile
7.Operators
^ = Binary XOR Operator copies the bit if it is set in one operand but not both
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand
>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.
variable x = (expression) ? value if true : value if false
( Object reference variable ) instanceof (class/interface type)
8.Loops and Decision
for, wile, do-while
for(declaration : expression){}//for(int x : numbers )
break, continue
if, else, else if, switch-default,case
9.Arrays
dataType[] arrayRefVar;
arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Passing and returning arrays from methods:
printArray(new int[]{3, 1, 2, 6, 4, 2});
public static int[] printArray(int[] ary {
return ary;
}
10.Date and Regular Expressions:
GregorianCalendar(), import java.util.Date
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
java.util.regex package(Pattern Matcher adn PatternSyntaxException classes ), () - grouping, metacharacters(^ $ . re*, re+, re?,re{ n, m})
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}
Important Methods:
start and end - The start method returns the start index of the subsequence captured by the given group during the previous match operation, and end returns the index of the last character matched, plus one.
matches and lookingat - The matches and lookingAt methods both attempt to match an input sequence against a pattern. The difference, however, is that matches requires the entire input sequence to be matched, while lookingAt does not.
replaceFirst and replaceAll , appendReplacement and appendTail methods
11. Methods:
modifier returnType nameOfMethod (Parameter List) {
// method body
}
calling, passing parameter by value, method overloading,
Command-Line arguments:
java FileName Arguments
public class FileName {
public static void main(String args[]){
for(int i=0; i<args.length; i++){}
}
}
Constructors:
class MyClass {
int x;
MyClass(int i ) {
x = i;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
System.out.println(t1.x);
}
}
Variable Arguments:
typeName... parameterName
public class VarargsDemo {
public static void main(String args[]) {
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
}
}
finalize:
created before object final destruction by garbage collector - protected void finalize( ){//code}
12.File IO:
Byte Stream
FileInputStream and FileOutputStream
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Stream
FileReader and FileWriter // same above programme replace FileInputStream and FileOutpiutStream
Standard Stream
System.in System.out System.err InputStreamReader
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
FileInputStream:
InputStream f = new FileInputStream("C:/java/hello");
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
ByteArrayInputStream and DataInputStream
FileOutputStream:
OutputStream f = new FileOutputStream("C:/java/hello")
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
ByteArrayOutputStream and DataOutputStream
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++){
System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}
Directories in Java:
Creating Directory:
mkdir(), mkdirs()-{creates both a directory and all the parents of the directory}
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
d.mkdirs();
list() - liste the directory and contents
File file = null;
String[] paths;
try{
file = new File("/tmp");
paths = file.list();
for(String path:paths)
{
System.out.println(path);
}
}catch(Exception e){
e.printStackTrace();
}
13.Exceptions
Checked Exceptions, Runtime Exceptions, Errors
try
{
}catch(ExceptionType1 e1)
{
}catch(ExceptionType2 e2)
{
}catch(ExceptionType3 e3)
{
}finally
{
//The finally block always executes.
}
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.
public void deposit(double amount) throws RemoteException
{
throw new RemoteException();
}
public void withdraw(double amount) throws RemoteException, InsufficientFundsException
{
// Method implementation
}
Own Exceptions
class MyException extends Exception{
}
public class InsufficientFundsException extends Exception
{
}
public void withdraw(double amount) throws InsufficientFundsException
{
throw new InsufficientFundsException(needs);
}
try {
}catch(InsufficientFundsException e)
{
e.printStackTrace();
}
JVM Exceptions, Programmatic exceptions
import java.io.*;
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
}
}
C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram
2.Naming
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.
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.
Program File Name - Name of the program file should exactly match the class name. There can be only one public class per source file.
3.Constructors
public class Puppy{
int puppyAge;
public Puppy(String name){
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
Puppy myPuppy = new Puppy( "tommy" );
myPuppy.setAge( 2 );
myPuppy.getAge( );
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
4.Instances
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
5.Data Types
byte, short, int, long, float, double, boolean, char, String, boxing
data type variable [ = value][, variable [= value] ...] ;
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; //array of characters
Character ch = new Character('a');//using ahcracters
Format strings:
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
(or)
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
6.Modifiers
private, public, protected
static, final, abstract, synchronized, volatile
7.Operators
^ = Binary XOR Operator copies the bit if it is set in one operand but not both
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand
>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.
variable x = (expression) ? value if true : value if false
( Object reference variable ) instanceof (class/interface type)
8.Loops and Decision
for, wile, do-while
for(declaration : expression){}//for(int x : numbers )
break, continue
if, else, else if, switch-default,case
9.Arrays
dataType[] arrayRefVar;
arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Passing and returning arrays from methods:
printArray(new int[]{3, 1, 2, 6, 4, 2});
public static int[] printArray(int[] ary {
return ary;
}
10.Date and Regular Expressions:
GregorianCalendar(), import java.util.Date
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
java.util.regex package(Pattern Matcher adn PatternSyntaxException classes ), () - grouping, metacharacters(^ $ . re*, re+, re?,re{ n, m})
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}
Important Methods:
start and end - The start method returns the start index of the subsequence captured by the given group during the previous match operation, and end returns the index of the last character matched, plus one.
matches and lookingat - The matches and lookingAt methods both attempt to match an input sequence against a pattern. The difference, however, is that matches requires the entire input sequence to be matched, while lookingAt does not.
replaceFirst and replaceAll , appendReplacement and appendTail methods
11. Methods:
modifier returnType nameOfMethod (Parameter List) {
// method body
}
calling, passing parameter by value, method overloading,
Command-Line arguments:
java FileName Arguments
public class FileName {
public static void main(String args[]){
for(int i=0; i<args.length; i++){}
}
}
Constructors:
class MyClass {
int x;
MyClass(int i ) {
x = i;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
System.out.println(t1.x);
}
}
Variable Arguments:
typeName... parameterName
public class VarargsDemo {
public static void main(String args[]) {
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
}
}
finalize:
created before object final destruction by garbage collector - protected void finalize( ){//code}
12.File IO:
Byte Stream
FileInputStream and FileOutputStream
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Stream
FileReader and FileWriter // same above programme replace FileInputStream and FileOutpiutStream
Standard Stream
System.in System.out System.err InputStreamReader
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
FileInputStream:
InputStream f = new FileInputStream("C:/java/hello");
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
ByteArrayInputStream and DataInputStream
FileOutputStream:
OutputStream f = new FileOutputStream("C:/java/hello")
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
ByteArrayOutputStream and DataOutputStream
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++){
System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}
Directories in Java:
Creating Directory:
mkdir(), mkdirs()-{creates both a directory and all the parents of the directory}
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
d.mkdirs();
list() - liste the directory and contents
File file = null;
String[] paths;
try{
file = new File("/tmp");
paths = file.list();
for(String path:paths)
{
System.out.println(path);
}
}catch(Exception e){
e.printStackTrace();
}
13.Exceptions
Checked Exceptions, Runtime Exceptions, Errors
try
{
}catch(ExceptionType1 e1)
{
}catch(ExceptionType2 e2)
{
}catch(ExceptionType3 e3)
{
}finally
{
//The finally block always executes.
}
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.
public void deposit(double amount) throws RemoteException
{
throw new RemoteException();
}
public void withdraw(double amount) throws RemoteException, InsufficientFundsException
{
// Method implementation
}
Own Exceptions
class MyException extends Exception{
}
public class InsufficientFundsException extends Exception
{
}
public void withdraw(double amount) throws InsufficientFundsException
{
throw new InsufficientFundsException(needs);
}
try {
}catch(InsufficientFundsException e)
{
e.printStackTrace();
}
JVM Exceptions, Programmatic exceptions
No comments:
Post a Comment