Sunday, July 26, 2015

Compare Strings


Source: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

Code:

== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
Consequently, if you want to test whether two strings have the same value you should use .equals().
// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 
You almost always want to use.equals(). In the rare situation where you know you're dealing withinterned strings, you can use ==.

Tuesday, July 14, 2015

Package and Java Namespace



Package helps to facilitates finding and using classes. It avoids namespace collision.

Source: http://www.docstore.mik.ua/orelly/java-ent/jnut/ch02_11.htm

2.11. Packages and the Java Namespace

A package is a named collection of classes (and possibly subpackages). Packages serve to group related classes and define a namespace for the classes they contain.
The Java platform includes packages with names that begin with java, javax, and org.omg. (Sun also defines standard extensions to the Java platform in packages whose names begin with javax.) The most fundamental classes of the language are in the package java.lang. Various utility classes are in java.util. Classes for input and output are in java.io, and classes for networking are in java.net. Some of these packages contain subpackages. For example, java.lang contains two more specialized packages, named java.lang.reflect and java.lang.ref, and java.util contains a subpackage, java.util.zip, that contains classes for working with compressed ZIP archives.
Every class has both a simple name, which is the name given to it in its definition, and a fully qualified name, which includes the name of the package of which it is a part. The String class, for example, is part of the java.lang package, so its fully qualified name is java.lang.String.

2.11.1. Defining a Package

To specify the package a class is to be part of, you use a package directive. The package keyword, if it appears, must be the first token of Java code (i.e., the first thing other than comments and space) in the Java file. The keyword should be followed by the name of the desired package and a semicolon. Consider a file of Java code that begins with this directive:
package com.davidflanagan.jude;   
All classes defined by this file are part of the package named com.davidflanagan.jude.
If no package directive appears in a file of Java code, all classes defined in that file are part of a default unnamed package. As we'll see in Chapter 3, "Object-Oriented Programming in Java", classes in the same package have special access to each other. Thus, except when you are writing simple example programs, you should always use the package directive to prevent access to your classes from totally unrelated classes that also just happen to be stored in the unnamed package.

2.11.2. Importing Classes and Packages

A class in a package p can refer to any other class in p by its simple name. And, since the classes in the java.lang package are so fundamental to the Java language, any Java code can refer to any class in this package by its simple name. Thus, you can always type String, instead of java.lang.String. By default, however, you must use the fully qualified name of all other classes. So, if you want to use the File class of the java.io package, you must type java.io.File.
Specifying package names explicitly all the time quickly gets tiring, so Java includes an import directive you can use to save some typing. import is used to specify classes and packages of classes that can be referred to by their simple names instead of by their fully qualified names. The import keyword can be used any number of times in a Java file, but all uses must be at the top of the file, immediately after the package directive, if there is one. There can be comments between the package directive and the import directives, of course, but there cannot be any other Java code.
The import directive is available in two forms. To specify a single class that can be referred to by its simple name, follow the import keyword with the name of the class and a semicolon:
import java.io.File;    // Now we can type File instead of java.io.File
To import an entire package of classes, follow import with the name of the package, the characters .*, and a semicolon. Thus, if you want to use several other classes from the java.io package in addition to the File class, you can simply import the entire package:
import java.io.*;   // Now we can use simple names for all classes in java.io
This package import syntax does not apply to subpackages. If I import the java.util package, I must still refer to the java.util.zip.ZipInputStream class by its fully qualified name. If two classes with the same name are both imported from different packages, neither one can be referred to by its simple name; to resolve this naming conflict unambiguously, you must use the fully qualified name of both classes.

2.11.3. Globally Unique Package Names

One of the important functions of packages is to partition the Java namespace and prevent name collisions between classes. It is only their package names that keep the java.util.List and java.awt.List classes distinct, for example. In order for this to work, however, package names must themselves be distinct. As the developer of Java, Sun controls all package names that begin with java, javax, and sun.
For the rest of us, Sun proposes a package-naming scheme, which, if followed correctly, guarantees globally unique package names. The scheme is to use your Internet domain name, with its elements reversed, as the prefix for all your package names. My web site is davidflanagan.com, so all my Java packages begin with com.davidflanagan. It is up to me to decide how to partition the namespace below com.davidflanagan, but since I own that domain name, no other person or organization who is playing by the rules can define a package with the same name as any of mine.

static

- I dont need to create object to access the static methods and variables. If method or variable is made is static, then it will not have copies created through objects.

- Behaviour is Singleton(a single person or thing of the kind under consideration). Having one object at one point of time.

- If method is made static then it is indirectly saving memory. As it will have only one object, so no more instances, so no more memory is needed.



Static Import:


12/22/2015

We invoked class Math's static fields and methods by preceding each with the class name Math and a dot (.). A static import declaration (a new feature of J2SE 5.0) enables programmers to refer to imported static members as if they were declared in the class that uses them—the class name and a dot (.) are not required to use an imported static member.
    A static import declaration has two forms—one that imports a particular static member (which is known as single static import) and one that imports all static members of a class (which is known as static import on demand). The following syntax imports a particular static member:
import static packageName.ClassName.staticMemberName;
where packageName is the package of the class (e.g., java.lang), ClassName is the name of the class (e.g., Math) and staticMemberName is the name of the static field or method (e.g., PI or abs). The following syntax imports all static members of a class:
import static packageName.ClassName.*;
where packageName is the package of the class (e.g., java.lang) and ClassName is the name of the class (e.g., Math). The asterisk (*) indicates that all static members of the specified class should be available for use in the class(es) declared in the file. Note that static import declarations import only static class members. Regular import statements should be used to specify the classes used in a program.


static and final together:

Source: http://www.coderanch.com/t/394580/java/java/Final-Static

final declares a variable to be constant. Which means once you set its value, it never changes and trying to change it gives an error. An example of using final is:
final int i = 0;
i is equal to 0, it will always be equal to 0 and can never be changed.

static is a completely different animal. static just means that this variable exists outside of any class. They are usually referenced via class name 'dot' variable name like so:
static stVar is declared in Class1. It is a member of that class but can be accessed even if no instances of Class1 exist. It can be accessed with Class1.stVar.
Hope this helps,


In addition to Jason's excellent post, here is some more information about final and static.
The keyword final is used to prevent a method from being overridden, or to prevent a class from being inherited. It can also be used to create variables whose values can't be changed, as Jason points out. 
The static keyword can be used to create a variable that is shared by all instances of its class. Thus, there is only one copy of a static variable that will be used by all objects of the class. As Jason points out, it can be accessed independently of any object. In essence, a static variable is similar to a global variable in other computer languages.
You can also create static methods. A static method can call only other static methods, access only the static data defined by its class, and not use this or super

Handson

- What if we print the String args[0], args[1] ... that we give in the main method.???

- # Data Mask tool:

Team has developed a script in java, the input for the script is file name, the column name where masking should be done(PII is located), delimeter details, Headers and footers details in the notepad.

The script when run will pick the notepad, reads the lines(details of  file) and then go and mask the data(PII) with other number. They have made it a Jar file, so that this concept is used across all platforms and on any kind of file format.


Running Java program from the command prompt


Source: http://www.tutorialspoint.com/junit/junit_environment_setup.htm


Step 1 - verify Java installation in your machine

Now open console and execute the following java command.
OSTaskCommand
WindowsOpen Command Consolec:\> java -version
LinuxOpen Command Terminal$ java -version
MacOpen Terminalmachine:~ joseph$ java -version
Let's verify the output for all the operating systems:
OSOutput
Windowsjava version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Linuxjava version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Macjava version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)
If you do not have Java installed, install the Java Software Development Kit (SDK) fromhttp://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.6.0_21 as installed version for this tutorial.

Step 2: Set JAVA environment

Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example
OSOutput
WindowsSet the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21
Linuxexport JAVA_HOME=/usr/local/java-current
Macexport JAVA_HOME=/Library/Java/Home
Append Java compiler location to System Path.
OSOutput
WindowsAppend the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the end of the system variable, Path.
Linuxexport PATH=$PATH:$JAVA_HOME/bin/
Macnot required
Verify Java Installation using java -version command explained above.

Step 3: Download Junit archive

Download latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, I downloaded Junit-4.10.jar and copied it into C:\>JUnit folder.
OSArchive name
Windowsjunit4.10.jar
Linuxjunit4.10.jar
Macjunit4.10.jar

Step 4: Set JUnit environment

Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your machine. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
OSOutput
WindowsSet the environment variable JUNIT_HOME to C:\JUNIT
Linuxexport JUNIT_HOME=/usr/local/JUNIT
Macexport JUNIT_HOME=/Library/JUNIT

Step 5: Set CLASSPATH variable

Set the CLASSPATH environment variable to point to the JUNIT jar location. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
OSOutput
WindowsSet the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\junit4.10.jar;.;
Linuxexport CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.
Macexport CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.

Step 6: Test JUnit Setup

Create a java class file name TestJunit in C:\ > JUNIT_WORKSPACE
   
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
   @Test
   public void testAdd() {
      String str= "Junit is working fine";
      assertEquals("Junit is working fine",str);
   }
}
Create a java class file name TestRunner in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}   

Step 7: Verify the Result

Compile the classes using javac compiler as follows
C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
Now run the Test Runner to see the result
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
true

Practical:
- Write a java program in a notepad
- Save it with same name as that of its class name
- Open the command prompt, set path and class path

path:
set path = "c:\java 1.5\bin"
C:\ YourFolder >javac YourCode.java
Note: If you set the class path you can execute java code from anywhere.

set classpath = c:\java\jre\lib; %classpath%


Execute java program on your local machine without SDK:

Syntax:
- Set path="JDK path" //set up jdk path:
- javac "path/filename.java" //compile java file by giving full path of the file
- java "path/filename" //execute the file by giving full path of the file


Validation:
java -version // this will check your jre version
javac -version // this will check your java compiler version if you installed


Eclipse

- Most easy one and effective one compared with other IDE's(Netbeans, BlueJ, JCreator)

- To get rid of command prompt we can use Eclipse

- Eclipse is Java's IDE(Integrated Development Environment)

- Eclipse - > select workspace(location where you wanted to save your programs) -> create java project (File-> new-> others->java project) ->Name the project and set the class path -> set JRE(if not seen the configure explicitly)

- Configuring JRE in eclipse : Follow above path, while creating a new project make sure JRE is configured.

Click configure -> select the folder where JRE is stored or you can also give your JDK folder.

Add JRE -> select Standard VM -> selct next -> give JRE folder name in directory -> Finish


- JRE should be configured before you run the java program

- Java settings will have:

Source -> where to save java program and compiled fileds(.class) files to be stored. You can even change the default folder names

- Folders under the java project in eclipse are:
.settings
.bin
src  ----- has .java files
.classpath ---- its where jar files are called, path is mentioned. When import statement is used in the code, it implicitly calls the import class file from the jar file
.project -----

- Java Build path: Has following sections

Source
Projects
Libraries
Order and Export

- SDE Plugins

Code Analyzer   --- Scans java code and identifies potential problems like performance, coding standard voilations(opened the DB but not closed) Ex: PMP, CPD and Checkstyle Ex: VSS, SVN
Configuration Management --- Used for organizing and maintain the versions of the software program.
Testing --- Automated scripts for Unit testing of the application, generate and publish reports Ex: JUnit
Build Tool -- Tool for building package application and automating the build/deploy process Ex: ANT and MAVEN


- Preferences ---- Will increase the font size

- Use Ctrl+space to get the methods, variables and syntaxes of methods.
Ex: main+ ctrl+space ---- will give you the syntax of the main method

- Outline --- will give you list of methods and variables used

- Debugger --- helps you to identify the values of the variables in java class and you can change those values in run time. Helps you test the code.

Stop the eclipse run at one point of line of code -> Debugger(bug icon) in the menu bar->Debug as -> java application


- Select Project -> Build Automatically --- means the code gets compiled automatically we need not do it manually

- In the console you have red button, when you are running the code and wanted to stop it, you can do it by clicking the red button. And also console will show results.

- Windows -> Preferences -> helps in changing the font, colors, adding line numbers to each line of code, change control keys(commands) like ctrl+shift f9 etc...




- Perspective ( C/C++....debug mode all these are perspectives)--change the settings and save the perspectives. This is generally a display that you see when you open eclipse.


- Project Explorer: 

Classes and Packages are shown in different folders.

- Navigator:

Navigator is like actual folder structure in Windows.

- Eclipse could also be used for C and C++ along with Java program.

- Build Project/Build configuaration in Eclipse??


- Syntax checker:

- Tasks:

- Search: Search in menu bar helps in searching particular string in a code, and when you click on one of the results in displayed in the bar below, it will take you to the line of code.

Select text ... Go to Search -> Occurance in File -> Identfier--- this will give the instances of the text in the code.


- Disconnect vs Terminate:


Debugger: Use Run As Debug mode instead of just run as Java application.
Step into(F5), Step over(F6), Step Return(F7) -- are common debugging tools.

in - into that function

over - execute entire function

return - we skip rest of the method


- Console: is where results are displayed. Floating console, will be created by dragging console outside eclipse window.

Run -> External Tools: Configure tools option, will help you create windows console and run commands on the console for the same.

- Bookmarks

- Marker bar (left side bar in editor)

- Breakpoint ---point where you wanted to stop your execution. You could create breakpoint select marker bar and double click. In debug mode you could see that code has stopped.

- Expanding Eclipse: We could add approx 9 million add ons to the eclipse.

http://marketplace.eclipse.org

or
help -> Eclipse Marketplace


Addons include:

a. WindowBuilder -- for graphical related activities

- Outline tab in Eclipse will help you to view list of functions in your application.

- Commit code to Bit bucket. Push code to master in Bit bucket 

Right click on project-> Team-> Commit
Same as above , instead of Commit  select Push to branch





Monday, July 13, 2015

Run Configuaration - Supplying parameters during run time


Object Oriented Programming

Main core concepts of Object Oriented programming:

Polymorphism -- Compile time behaviour is different from the run time behaviour.

Inheritance - Inherit the property of the object and upgrade the features on top of it

Encapsulation - Trying to hide the data, but just going to give the object to the user. So that object could be used to make us of the data.

 

Advantageous of java


- Open source

- We can compile and run it any where without recompiling it again. Compiled Java files, can be run any where like in linux, solaris or Unix

- .Net is not open source. C sharp, .Net or C++ --- we can compile anywhere but cant run any where.

- Code written in C sharp, .Net and C++ can be accessable from Java, but viceversa is not

- Robust, easy to learn

- Lots of Frameworks available

- If you have 100 million data, we can run it in minutes but Mainframe will take long time. And also you need to pay for every set of records to process using Mainframe, Java does not ask for pay. So now a days people wanted to move from Mainframe to Hadoop and Big data.

- Hadoop can read any data and put it in structured file.

- Java 7 has more advanced concepts

- Java also has encrypted, safest algorithms

-  Java does garbage collection implicitly(automatic memory management), C language needs garbage collection object to collect the garbage(wastage of memory)

- Java framework  - SE, EE and ME

- JAva compiler will extend if the program file is increased but for c program thats not the case, here program gets crushed

- JDK = JRE+JVM..
JVM - has class loader..using which we can run the program any of the platforms

-

 

Saturday, July 11, 2015

Implicit and Explicit wait


Exception handling

- See when ever you use Thread.sleep(300) ---- when ever you use Thread, better use InterruptedException

Ex: public static void man(Strings args[]) throws InterruptedException {
 

Friday, July 10, 2015

Setters and Getters

Note: To make use of private variables of called class in calling class, we use getter and setter methods concept.

- To get and set values to the class variables(that are set as private) from other class we use get and set methods(these are public) in the parent class.

- No need to getters and setters manually, eclipse has inbuilt feature to do so

- Set the class variables as private, but to access the variables outside the class you need to create getters and setters

- Right click on the code -> Source -> Generate Getters and Setters -> this will create getter and setter methods in the code.

- keyword--- this ---- to assign class level variable

- Getter and Setter will help you understand Encapsulation, as you are hiding the data.


Miscellaneous:

- How do you think Getters and Setting will hide the values or help for encapsulation?   ---- not sovled

-

Notes- Miscelleneous

text - question unresolved
text - question resolved
#text - Important




- Here Sleep will make which thread wait?
Thread.sleep(3000); ----makes the current operation wait for 3000 milli seconds

- Java Decomplier -- is external file that is used to get back the code from the byte code(.class file)

- It is better you perform only one main operation in a method, better create multiple methods for different operations

- How are class C and A put together in one line?
There are two classes Class A and Class C

A a = new C(); ---what does it mean

Sol: The above code is possible only if C extends A. Here 'a' is a object of class A that has access to properties of Class A and C.


- Java Build Path

- .classpath file

- How are we passing file path as parameter and also file is object. Whole syntax is not understandable ?
java.io.File file = new java.io.File("C:\\Users\\....");

- What will load method will have as parameter in the braces ?
Properties prop = new Properties();
prop.load(new FileInputStream(file));

- Why URI class has parameter and how the below code will work? Especially what value object will store based on value returned from URI construcutor?
 URI uri = new URI(requestUri); 
  String resourceUri = uri.getPath().trim();

Sol: URI uri = new URI(requestUri); //Here when you run this code, URI method(basically a constructor) will get executed. Looks like whatever value that URI method will return, will be stored in object uri. Like what resourceUri variable will hold the data.

if so ####
#object could store other values too along with address
#Any in built method(specific to java) could be used with object, like here getPath() and trim() is used.

Why cant be this? because built in methods of java could not be used without object or class name.
String resource1= new URI(requestUri); 
String resourceUri = resource1.getPath().trim();

- What does it say?
String port = (Integer.toString(uri.getPort()).trim().equals("-1")?Integer.toString(uri.toURL().getDefaultPort()).trim():Integer.toString(uri.getPort()).trim());

- Play with strings, is the below thing possible? 
result = new String(Base64.encodeBase64(rawHmac)).replace("\r\n",
"");
#here result will have value from replace method. For Strings we do not have constructor to execute so replace method itself is used directly.

Adding libraries to Java project

- Go to project->properties->java build path->add external jars.

Why does jars mean in java, are they similar to some one has writtern some class files and we are making use of them. Like we add libraries in QTP???---Not Resolved

 

Instance variables

5/13/2014
public class SimpleClass {

/*variables declared in the class but not in a method that do not have the
keyword static are called instance variables*/

private int salary; /*instance variable - declared in class and outside of a method , and with no keyword - static

private String name; /*instance variable

public static void main(String[] args) {
/* sc points at instance variable */

SimpleClass sc = new SimpleClass(); /*object sc is created, blue print of class

sc.salary =30000; /*at object, variable salary has value 300000

sc.name = "Jim"; /*at object, variable name has valu Jim

System.out.println(sc.name + "makes $" + sc.salary);

}

Staic variables

5/13/2014
public class SimpleClass2 {

/*variables declared in the class but not in a method that have the
keyword static are called Static variables.*/ /*Static variables generally used for protection like database passwords, for this which

people do not wanted to make a copy */

/* class loader creates:

1. Static variables first

* 2. Loads static methods second


* 3. Creates instance variables


* 4. Loads instance methods Ex: File names, and make copies using objects


*/



private static int salary;

private static String name;

public static void main(String[] args) {

/*variables in static methods can only read
and update static variable.
variables in static method must not read and update instance variables*/

SimpleClass2 sc2 = new SimpleClass2();

System.out.println(sc.name); /*wanted to check default value of





instance variable name, displays as null */

salary =30000; /*updating instance variable salary

name = "Jim";



System.out.println(name + " makes $ " + salary);

System.out.println(sc2.name);


}