Reading Command Line Arguments (i) Common way class ReadCmdLineArgs { public static void main(String[] args) { System.out.println("Command Line Args:"); System.out.println("------------------"); if (args.length != 0) { for (int i = 0; i < args.length; i++) { System.out.println((i + 1) + ". " + args[i]); } } else { System.out.println("No command line args. specified"); } } } (ii) Another for loop syntax class ReadCmdLineArgs { public static void main(String[] args) { System.out.println("Command Line Args:"); System.out.println("------------------"); if (args.length != 0) { int i = 1; for (String arg : args) { System.out.println((i++) + ". " + arg); } } else { System.out.println("No command line args. specified"); } } } ------------------------------------------------------------------------------ Object Instantiation class ObjInstantiation { public static void main(String[] args) { new Greet().showGreeting();//Nameless object Greet g = new Greet(); g = new Greet();//implicit deref. g.showGreeting(); g = null;//explicit deref. g.showGreeting();// NullPointerException } } class Greet { Page | 1 [email protected]
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Reading Command Line Arguments(i) Common wayclass ReadCmdLineArgs {
public static void main(String[] args) {System.out.println("Command Line Args:");System.out.println("------------------");if (args.length != 0) {
for (int i = 0; i < args.length; i++) {System.out.println((i + 1) + ". " + args[i]);
}} else {
System.out.println("No command line args. specified");}
}}
(ii) Another for loop syntaxclass ReadCmdLineArgs {
public static void main(String[] args) {System.out.println("Command Line Args:");System.out.println("------------------");if (args.length != 0) {
int i = 1;for (String arg : args) {
System.out.println((i++) + ". " + arg);}
} else {System.out.println("No command line args. specified");
}* Predefined reference variable refines the scope of the variables with same name declared in different levels.* Predefined reference should not be done in static context.
Greet() {//provided to ensure the success of g = new Greet(); }/*if not given:
cannot find symbolsymbol : constructor Greet()*/
Greet(String name) {/*refining the scope of instance variable name using the predefined reference variable this since, its direct usage refers only to the local variable name*/
this.name = name; }
void showGreeting() {System.out.println("Hi " + name + "!!!");
}}
Case Study:java ConstructorsHi Anonymous!!!
java Constructors uceHi uce!!!
Note: Default constructor is provided by the JVM only when a class does not have one of its own.
---------------------------------------------------------------------------------Counting the instance of a class
Class TestInstanceCounter
class TestInstanceCounter {public static void main(String[] args) {
SomeClass sc1 = new SomeClass();SomeClass sc2 = new SomeClass();
System.out.println("You have created " + SomeClass.countInstances() + " instances of " + "the class called \"SomeClass\"");
---------------------------------------------------------------------------------Rectangle r = new Container(10, 20, 30); /*valid
because where ever a class (instance) is expected, we can pass its instance or the instance of its direct or indirect subclass*/
Container c = new Rectangle(10, 20); /*invalidbecause of the reason above; Here class Rectangle is the super class of class Container*/---------------------------------------------------------------------------------
This is a square.It’s an instance of Square.This is an unknown shape. case 1 in the switch is matched and an object of Square is returned from getShape(). It is assigned to s [up-casting: super-class object = sub-class object. sub-class object is wrapped inside a super-class object]. It is down-casted [unwrapped it from the cover of super-class that hinders the visibility of sub-class specific fields and methods] to type Square after proper checking using instanceof before actually using it.
java TestInheritance 2This is a circle.It’s an instance of Circle. case 2 in the switch is matched and an object of Circle is returned from getShape(). It is assigned to s [up-casting: super-class object = sub-class object. sub-class object is wrapped inside a super-class object]. It should be down-casted [unwrapped it from the cover of super-class that hinders the visibility of sub-class specific fields and methods] to type Circle after proper checking using instanceof before actually using it.
java TestInheritance 3This is a triangle.It’s an instance of Triangle. case 3 in the switch is matched and an object of Triangle is returned from getShape(). It is assigned to s [up-casting: super-class object = sub-class object. sub-class object is wrapped inside a super-class object]. It should be down-casted [unwrapped it from the cover of super-class that hinders the visibility of sub-class specific fields and methods] to type Triangle after proper checking using instanceof before actually using it.
java TestInheritance squareNumberFormatException “square” [String type] cannot be parsed into int using Integer.parseInt(String);
---------------------------------------------------------------------------------Reference variable: this
class TestThisFunc {public static void main(String[] args) {
System.out.println("Hello World!");}
}class SomeClass {
private int x = 0;private int y = 0;private int z = 0;
---------------------------------------------------------------------------------Printing the Object
class PrintObject {public static void main(String[] args) {
Rectangle r = new Rectangle(10, 20);Container c = new Container(100, 200, 300);System.out.println(r);/*Classname@hashCode*/System.out.println(r.toString());/*Classname@hashCode*/
System.out.println(r.hashCode());/*hash code in integer form*/System.out.println(Integer.toHexString(
r.hashCode()));/*hash code in hexadecimal form*/System.out.println(r.getClass().getName());/*returns classname*/
"@" +Integer.toHexString(r.hashCode()));/*mimicking the operation done
while an object is printed*/
System.out.println(r);System.out.println(c);
}}---------------------------------------------------------------------------------java.lang.Object.toString(); //programmer need to override it to personalize itjava.lang.Object.hashCode();//programmer need to override it to personalize itjava.lang.Object.getClass();//no overridingjava.lang.Object.equals();//programmer need to override it to personalize it---------------------------------------------------------------------------------
Overriding toString() in class Rectanglepublic String toString() {
} class String has overridden the hashCode() in Object.
Implicitly created String object [String str = “hello”;] are stored in the string constant pool. Hence same valued String objects created implicitly have the same reference (and hence same hash code)- to impart optimization. Implicit creation of object: String str = “hello”; Explicit creation of object: String str = new String(“hello”); class Rectangle makes use of hashCode() in the class String to mimic this behavior. L and B are used as delimiters since Rectangle (11, 20) and Rectangle (1, 120) may have same hash code otherwise.---------------------------------------------------------------------------------
Overriding hashCode() in Containerpublic int hashCode() {
---------------------------------------------------------------------------------Boxing and un-boxing
class Boxing {public static void main (String[] args) {
Integer integer = 10; /*boxing of primitive type 10 [int] into class type integer [class Integer]. From jdk 1.5 onwards. Assigning an int to Integer was not possible in earlier version of jdk.*/
int j = integer + 10; /*un-boxing*/System.out.println (integer);System.out.println (j);
/** Abstraction refers to vague definition or not very definitive nature of a class or a method.* An abstract function should not have a body.* If a class contains abstraction explicitly coded or inherited then the class must be stated as an abstract class using abstract keyword.* A class with at least one abstract method should be declared abstract.* We cannot create objects of an abstract class.* Abstraction is used to enforce specifications and to hide complexity.* A class inheriting an abstract class should define (should give body by overriding them) all the abstract functions in it or should be explicitly declared abstract.**/
Abstract Class Abstract FunctionCannot create object. No body.
Keyword abstract can also be used just to prevent the object creation rather than to explicitly specify the abstraction. When the class contains only static functions, we may prevent it from accessing through instance.
If a class contains abstraction explicitly coded or inherited then the class must be stated as an abstract class using abstract keyword.
abstract class Vehicle {public abstract int numOfWheels();public abstract String steeringType();public abstract boolean hasGears();public abstract String fuelType();public abstract String getModel();
}
abstract class TwoWheelers extends Vehicle {public int numOfWheels() {
return 2;}public String steeringType() {
return "Handle Bar";}
}
abstract class FourWheelers extends Vehicle {public int numOfWheels() {
return 4;}public String steeringType() {
return "Steering Wheel";}
}
class Stallion extends TwoWheelers {public boolean hasGears() {
100% abstract data structure. It can contain only constant variables, abstract methods, classes and other interfaces. An interface cannot contain non-abstract functions and variables. We cannot create objects of an interface. On compilation, an interface generates a .class extension file.
interface Shapes { int i = 10;// implicit conversion to public static final int i = 10; void drawCircle();// public abstract void drawCircle();}
class DrawShape1 implements Shapes { //directly implementing Shapes public void drawCircle() {//Interface methods are implicitly public abstract System.out.println(
"drawCircle() - implemented in DrawShape1."); } public void function1() { System.out.println(
class SomeClass extends DrawShape1 { //indirectly implementing Shapes via DrawShape1}
class DrawShape2 implements Shapes { //directly implementing Shapes public void drawCircle() { System.out.println(
"drawCircle() - implemented in DrawShape2."); } public void function1() { System.out.println(
"function1()- implemented in DrawShape2."); }}
class TestInterface1 { public static void main(String args[]) { /*DrawShape1 ds1 = new DrawShape1(); ds1.drawCircle(); ds1.function1();
DrawShape2 ds2 = new DrawShape2(); ds2.drawCircle(); ds2.function1(); */
Shapes s = new Shapes(); /*Shapes is abstract and cannot be instantiated*/
Shapes s = new DrawShape2(); s.drawCircle(); s.function1(); /*cannot find symbol function1() in interface Shapes since function1() is invisible to Shape (reference variable s)*/ }}
System.out.println("This is a circle with a radius of " + r); } public void drawCircle() { System.out.println("This is a circle."); } public void drawSquare() { System.out.println("This is a square."); }}
class TestInterface3 { public static void main(String args[]) { DrawShape ds1 = new DrawShape(); ds1.drawCircle(); ds1.drawCircle(10); ds1.drawSquare(); }}
class DrawShape implements CircleSquareTriangle { public void drawCircle() { System.out.println("This is a circle."); } public void drawSquare() { System.out.println("This is a square."); } public void drawTriangle() { System.out.println("This is a triangle."); }}
class TestInterface5 { public static void main(String args[]) { DrawShape ds1 = new DrawShape(); ds1.drawCircle(); ds1.drawTriangle(); ds1.drawSquare(); }}
class DrawShape implements CircleSquareTriangle { public void drawCircle() { System.out.println("This is a circle."); } public void drawSquare() { System.out.println("This is a square."); } public void drawTriangle() { System.out.println("This is a triangle."); }}
class TestInterface6 { public static void main(String args[]) { DrawShape ds1=new DrawShape(); ds1.drawCircle(); ds1.drawTriangle(); ds1.drawSquare(); }}
--------------------------------------------------------------------------------- The modifier final with a method prevents it from being overridden.
A final method cannot be overridden. The modifier final with a class prevents it from being inherited.
A final class cannot be inherited. Return type of functions is not considered in overloading. If the return type is non-primitive then we can use sub-type while overloading the method.
public Rectangle doSomething() {}
public Container doSomething() { //overriding}
While overriding a function the access modifier can only be broadened, widened, or strengthened.
While overriding a function if the data type of an identifier is changed in the overridden function, it becomes overloading. Modifier abstract cannot be used in combination with final, private or static.
abstract + final abstraction is resolved by overriding the functions, but final prevents the function from being overridden.
abstract + private abstraction is resolved by overriding the functions in the sub-class, but private members are not inherited.
abstract + static static methods can be referred to by qualifying using class-name. Abstract methods are not definitive and hence make no sense.
--------------------------------------------------------------------------------- implements - has a relationship. extends - is a relationship. An interface can extend one or more interfaces. A class can extend only one class. A class can implement one or more interfaces. An interface cannot extend a class, since nothing can be non-abstract in an interface. In Java, multiple inheritance can be attained only with the involvement of interface(s). Where ever an interface is expected, we can pass the instance of a class that directly or indirectly implements the interface.
In java, packages are used to organize files, physically. It has no significance as far as source files are concerned. The real use comes when dealt with class files- they should be in the package hierarchy as defined by the package statement which comes as the first statement of the source code. Source files need not be in the package defined. eg:---MainFrame.java---package src.ui;
MainFrame.java need not be in path current-directory\src\ui\ when it is compiled. But MainFrame.class should be in the path current-directory\src\ui when it is executed.
: The option “-d” is used to create the class files in some defined directory. Here the produced class files will be in the path source-directory-path\build\com\dh\lang\ & source-directory-path\build\com\dh\math\[follows that the source files are in source-directory-path\src\com\dh\lang\ and in source-directory-path\src\com\dh\math\]
Building...source-directory-path\build>jar -cf ..\dist\MyAPI.jar com
: Here the jar file MyAPI.jar is created in source-directory-path\dist\ using the class files in package com. (cf = create file)
source-directory-path\build>jar -cvf ..\dist\MyAPI.jar com: Here the progress of jar file creation will be displayed.(option v)
Using API...source-directory-path\src>javac -cp ..\lib\MyAPI.jar;..\lib\YourAPI.jar -d ..\build com\dh\appl\*.java
: Here we create an application using the API collection in MyAPI.jar, which reside in source-directory-path\lib (option -cp is used). If there is more than one jar file, each is separated by a semi-colon in Windows and colon in Linux.
Making application executable on double click...- While creating a jar file META-INF\MANIFEST.MF is automatically created with some default attributes.
source-directory-path\build>jar -cvmf manifest.txt ..\dist\MyAppl.jar com: The appends the attributes defined in manifest.txt(option m) to META-INF\MANIFEST.MF and create a jar file MyAppl.jar which will be executable.
Exceptions are runtime anomalies that may result in the abnormal termination of the program.Exceptions are mainly thrown by system or by a function
Thrown by systemArrayIndexOutOfBoundsExceptionClassCastExceptionNullPointerExceptionThrown by functionNumberFormatException
In java all exceptions are classes. Mainly there are two types of exceptions. They are:Exceptions|x-- Checked Exceptions: that are trapped by the compiler|x-- Unchecked Exceptions: that are not trapped by the compiler
A checked exception must be either reported or caught (handled). Otherwise the compiler may fail to compile the program. An unchecked exception may be excepted from handling- it causes failure at runtime only.
Hierarchy of Exception classesjava.lang.Object|+-- java.lang.Throwable
|+-- java.lang.Exception
|+-- java.lang.RuntimeException
Direct or indirect subclasses of class Exception are checked exceptions with an exception of class RuntimeException. Direct or indirect subclasses of class RuntimeException are unchecked exceptions.
"An error occurred. Check the error.log for details.");} catch (java.io.FileNotFoundException ex) {
System.out.println("Could not create error.log file.");}
} System.out.println("Program terminated normally."); }}--------------------------------------------------------------------------------class SomeClass {// created by API provider public void someFunction() throws IllegalAccessException {
//there are lots of statements here and validations follow before //I throw the exception
throw new IllegalAccessException("Security violation."); //checked exception
} public void setBlahBlah(int value) throws ArithmeticException{
System.out.println("I am still inside the Outer try block."); } catch(ArithmeticException e) { //outer try catch System.out.println("Divide by Zero error - Outer Try."); } catch(ArrayIndexOutOfBoundsException e) { //outer try catch System.out.println("Array element does not exist - Outer Try."); }
System.out.println("Program terminated normally.");// last statement of the program }}--------------------------------------------------------------------------------class SomeClass {// class provided by an API-Provider public static void someFunction(int i) { try {// implicit inner try if (i == 1) { i /= 0;
} else { int ar[] = {10, 20}; ar[50] = 10; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array element does not exist - Exception caught in someFunction()."); }
class NestedTryMethod {// My Class public static void main(String args[]) { try {//explicit try int i = 10 / args.length; SomeClass.someFunction(args.length); } catch(ArithmeticException e) { System.out.println(
"Divide by Zero error - Exception caught in main()."); }
System.out.println("Program terminated normally."); }}--------------------------------------------------------------------------------class ThrowCheckedException {// created by developer of the application public static void main(String args[]) {
try {new SomeClass().someFunction();
} catch(IllegalAccessException e) {System.out.println("You do not have necessary privilege to
continue this operation.");}
//new SomeClass().someFunction(); }}--------------------------------------------------------------------------------class ThrowUncheckedException {// created by an Application Developer public static void main(String args[]) {
throw new ArithmeticException("Negative Number.");} else {
System.out.println(value + " is a positive value. I like it!!!");
}//other statements follow
}}--------------------------------------------------------------------------------class MyException extends RuntimeException { // created by API provider
MyException() {}MyException(String msg) {
super(msg);}
}
class SomeClass {// created by API provider public boolean isEvenNo(int x) throws MyException {
if (x < 0) {throw new MyException(
"Negative value - Invalid.");} else if (x == 0) {
throw new MyException("Zero value - Invalid.");
} else if ((x % 2) != 0) {throw new MyException(
"Odd Number - Invalid.");}return true;
}}
class UserDefinedException {// created by developer of the application public static void main(String args[]) { try { if (new SomeClass().isEvenNo(
Integer.parseInt(args[0]))) {//may raise a exception called as MyException
System.out.println("The no " + args[0] + " is a even number.");
/********************************************************************************* * This program uses the Keyboard as the input device to accept data from the * * MS-DOS prompt (console). It gets a character from the keyboard, and prints the * * ASCII value of the character inputted as well as the character itself. * *********************************************************************************/
import java.io.*; //for IOException & read() throws and java.io.IOException
public class TestKeyboardIO1 { public static void main(String[] args) throws IOException { /*System.out.println("Type in a character and press ENTER."); System.out.println("------------------------------------");
// reads a byte from the keyboard Buffer.// Returns an int.
--------------------------------------------------------------------------------/******************************************************************************** * This program uses the Keyboard as the input device to accept data from the * * MS-DOS prompt (console). It gets a string from the keyboard and prints it. * ********************************************************************************/
public class TestKeyboardIO2 { public static void main(String args[]) throws IOException { /* converting from byte stream (InputStream subclass) to character stream (Reader subclass)*/ /*InputStreamReader in_stream_reader =
new InputStreamReader(System.in);*/
/* converting from Reader subclass (in_stream_reader) to a BufferedReader object*/ /*BufferedReader buf_reader =
new BufferedReader(in_stream_reader);*/
BufferedReader buf_reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type in a sentence and press ENTER to terminate."); System.out.println("------------------------------------------------"); String data1 = buf_reader.readLine();// method to read a line. //String data1 = new BufferedReader(
// new InputStreamReader(System.in)).readLine();
System.out.println();
System.out.println("Type in a sentence and press ENTER to terminate."); System.out.println("------------------------------------------------"); String data2 = buf_reader.readLine();// method to read a line. //String data2 = new BufferedReader(
public class ShowFile { public static void main(String args[]) throws IOException { if (args.length != 0) { File file = new File(args[0]); if (file.exists() && file.isFile()) { FileInputStream input_file =
new FileInputStream(file); /*FileInputStream input_file =
new FileInputStream(args[0]);*/ int file_size = input_file.available(); byte[] data = new byte[file_size]; input_file.read(data); System.out.println(new String(data)); input_file.close(); } else { System.out.println("\"" + args[0] +
"\" not found !!!");}
} else { System.out.println("Error in usage:"); System.out.println(
public class WriteFile { public static void main(String args[]) throws IOException { if (args.length != 0) { File file = new File(args[0]);
if (file.exists()) { System.out.print("This file already exists. Overwrite? (y/n): "); int response = System.in.read(); if(response == 'N'||response =='n') { // if you do not want to overwrite the file. System.exit(0); // stop program } } else { System.out.print("Creating new file: " + args[0] + "..."); }
System.out.println(); System.out.println("[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]); System.out.println("--------------------------------------------------------------------------------");
FileOutputStream output_file = new FileOutputStream(file); // output file. boolean continue_write = true; byte[] data; // byte array to which the data is read into. while (continue_write) {// continue reading lines till the user types '~' and ENTER. data = new BufferedReader(
new InputStreamReader(System.in)).readLine().getBytes(); if (data.length == 1 && ((char)data[0]) == '~') {// if end-of-file continue_write = false; } else {// if not end-of-file output_file.write(data); output_file.write('\n'); } } System.out.println("--------------------------------------------------------------------------------"); output_file.close(); } else {//end of while System.out.println("Usage: java WriteFile <filename>");
} }}
/*public class WriteFile{ public static void main(String args[]) throws IOException { if(args.length!=0) { File file=new File(args[0]);
if(file.exists()) { System.out.print("This file already exists. Overwrite? (y/n): "); int response=System.in.read(); if(response=='N'||response=='n') // if you do not want to overwrite the file. { System.exit(0); // stop program } }
else System.out.print("Creating new file: " + args[0] + "...");
System.out.println(); System.out.println("[Press \'~\' as the first char on a new line to terminate the file.]"); System.out.println("Enter data for file: " + args[0]); System.out.println("--------------------------------------------------------------------------------");
FileInputStream input_file = new FileInputStream(source_file);
FileOutputStream output_file = new FileOutputStream(dest_file);
/********************************************************************** * (i) Finding the size of the source file using available(). * * (ii) Creating a byte array, the no. of elements of which is equal * * to the size of source file. * * (iii)Read data from the source file into the byte array. * * (iv) Write the byte array to the destination file. * **********************************************************************/
int file_size = input_file.available();byte input_file_data[] = new byte[file_size];input_file.read(input_file_data);output_file.write(input_file_data);
/********************************************************************** * Close the input/output streams. * **********************************************************************/
input_file.close();output_file.close();
source_file.delete();}
/********************************************************************** * Delete the source file and return a successful process message. * **********************************************************************/
System.out.println("File " + source_file.getName() + " successfully moved to " + dest_file.getName() +
" !!!"); } else {// if you do not want to move the file. System.out.println("File move operation aborted !!!"); System.exit(0); } }}--------------------------------------------------------------------------------
public class Client2 { public static void main(String args[]) { try { Socket clientSideSocket = new Socket("localhost", 8000); BufferedReader serverReader = new BufferedReader(
new InputStreamReader(clientSideSocket.getInputStream())); PrintWriter serverWriter = new PrintWriter(
clientSideSocket.getOutputStream(), true);BufferedReader keyboardReader = new BufferedReader(
new InputStreamReader(System.in));
double radius = 0; while (true) { System.out.print("Please enter the Radius of a Circle..."); radius = Double.parseDouble(keyboardReader.readLine()); serverWriter.println(radius);