StringBuffer capacity vs ensureCapacity and trimtoSize()

package com.me.practice;

public class StringBufferClass {
public static void main(String[] args) {

//By default it’s 0
StringBuffer stringBuffer=new StringBuffer();

//By default it’s 16
System.out.println(stringBuffer.capacity());

//Now appending “xxxx”
stringBuffer.append(“madhu”);

//Capacity won’t change if length < default capacity
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if length > default capacity
stringBuffer.append(“madhugggggggggggggggggggggggg”);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity won’t change if ensureCapacity < current capacity
stringBuffer.ensureCapacity(23);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if ensureCapacity > current capacity
stringBuffer.ensureCapacity(123);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will reduce to actual size
stringBuffer.trimToSize();
System.out.println(stringBuffer.capacity());

}
}

 

16
16
5
34
34
34
34
123
34
34

HashMap vs TreeMap vs HashTable vs concurrentHashMap values and keys

import java.util.*;
import java.util.concurrent.*;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);

//Key shouldn’t be null in treemap
//If we put two keys similar it will ovverride
//multiple Null values are allowed
TreeMap<String,String> treeMap=new TreeMap<String,String>();
treeMap.put(“null”,null);
treeMap.put(“null1”,null);
treeMap.put(“null”,”nuller”);
treeMap.put(“null2″,null);
System.out.println(treeMap);

//one key can be null
//If we put two keys similar it will ovverride
//Multiple null values allowed
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(null,null);
hashMap.put(null,”null1”);
hashMap.put(“null1”,null);
hashMap.put(“null2”,null);
hashMap.put(“null3″,null);
hashMap.put(null,”nuller”);
System.out.println(hashMap);

//No nulls as keys as well as values too
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put(“null”,”null-1″);
hashTable.put(“null1″,”null”);
hashTable.put(“null1″,”nuller”);
System.out.println(hashTable);

//No nulls as keys as well as values too
//thread safe
Map<String,String> conMap= new ConcurrentHashMap<String,String>();
conMap.put(“null1″,”null”);
conMap.put(“null”,”nuller”);
System.out.println(conMap);
}
}

 

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
{null=null-1, null1=nuller}
{null=nuller, null1=null}

If we put null as key in treemap or hashtable or concurrentHastable then it won’t  throws any  error at Compile Time.but it will throw below error at runtime

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
2147483647
-2147483648
7b
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
Exception in thread “main” java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:464)
at StaticVsNormalVsNo_Imports.main(StaticVsNormalVsNo_Imports.java:44)

Creating object(s) for class,interface,Abstract class,final class and enum in JAVA.

In java every communication among the classes merely done by the methods with the help of objects.The below link shows the various advantages with object in java.

Advantages with Object:

  • Define the structure and behavior of a class.
  • Independence-i.e One object values doesn’t affects the other object values.
  • Modularity- Once it got created ,We can move the object over methods or any where in the program.

Bundling code into individual software objects provides a number of benefits, including:

  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

WHY WE NEED OBJECT IN JAVA….? 

Creating a object for Class:

  • There are numerous ways to create an object for a particular class in java.But here i am showing only the most generalized way i.e using new keyword.

class Demo{
public String string;
//Definfing the structure of class
public Demo(String str){
this.string=str;
System.out.println(“In construcor”+string);
}
//Here we are changing the behabiour of class through method
public String getName(){
return “Brad Pitt”;
}
}
public class Demo_Object{
public static void main(String[] args)throws Exception{
//creating the object with new() operator
Demo demoObject=new Demo(” Mr..”);
String str=demoObject.getName();
System.out.println(str);
}
}

o/p:
D:\OCJP>javac Demo_Object.java

D:\OCJP>java Demo_Object
In construcor Mr..
Brad Pitt

 

Creating Object for an interface:

As all of us knew that interface is a kind of class but the only difference we see is abstraction i.e interface is 100% abstract.Directly we can’t create object for interface.Why so,Here are nice explanations

https://www.quora.com/Why-cant-we-create-an-object-to-interface-in-Java

http://softwareengineering.stackexchange.com/questions/263301/i-want-to-understand-clearly-why-cant-we-instantiate-an-object-of-an-abstract-c

But through Anonymous classes we can create the objects.Example programs are below.

interface TestInterface{
String toString();
}

public class Object_Creation3{
public static void main(String[] args)throws Exception{
System.out.println(new TestInterface(){
public String toString(){
return “HAAAAAAAAAAAhhhaaaaaaa”+this.getClass();
}
});
}
}

o/p:

D:\OCJP>javac Object_Creation3.java

D:\OCJP>java Object_Creation3
HAAAAAAAAAAAhhhaaaaaaaclass Object_Creation3$1

 

With that syntax, you create an anonymous class, which is perfectly legal.

Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class’ name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:

 

Object Creation for Abstract class:

We can’t create for object for an Abstract class because if we do also the implementation must happen i.e through extends otherwise it will left remains as an empty template.

Because it’s abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.

Take for example an “Animal” abstract class. There’s no such thing as a “pure” animal – there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn’t be able to instantiate plain Animal – that’s just a basic template. And there’s certain functionality that all animals share, such as “makeSound()", but that can’t be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?

 

abstract class AbstractClassSample{
public String name;
//public AbstractClassSample(String name){
//this.name=name;
//}
public abstract void getName();
public String getCompany(){
return “OpenText”;
}
}

public class Abstract_ObjectCreation{
public static void main(String[] args)throws Exception{
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar pichai”);
System.out.println(abstractClassSample.getCompany());
}
}

o/p:

D:\OCJP>javac Abstract_ObjectCreation.java
Abstract_ObjectCreation.java:14: error: AbstractClassSample is abstract; cannot
be instantiated
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar picha
i”);
^
1 error

But we can get benefit with inheritance in the case of Abstract class by extending the abstract class to sub class and creating object for sub class as below.

abstract class AbstractClassSample{
public String designation=”Software Engineer”;
public AbstractClassSample(String d){
this.designation=d;
}
public abstract String getName();
public String getCompany(){
return “OpenText”;
}
}

class Abstract_Inheritence extends AbstractClassSample{
public int employeeId;
public Abstract_Inheritence(int no,String d){
super(d);
this.employeeId=no;
}
public String getName(){
return “Madhu”;
}
//public String getCompany(){
// return “PegaSystems”;
// }
}

public class Test_Inhiritence{
public static void main(String[] args)throws Exception{
Abstract_Inheritence abstract_Inheritence=new Abstract_Inheritence(123,”Associate”);
String s1=abstract_Inheritence.getName();
String s2=abstract_Inheritence.getCompany();
System.out.println(s1);
System.out.println(s2);
}
}

o/p:

D:\OCJP>javac Test_Inhiritence.java

D:\OCJP>java Test_Inhiritence
Madhu
OpenText

 

 

Object Creation for final class:

We can create object for a final class as normal i.e first use case.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
}
}

o/p:
D:\OCJP>javac FinalClassObject.java

D:\OCJP>java FinalClassObject
In ConstructorMr.Ramanjan

But final class cannot be extended .It will throgh the error as below.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject extends Final_Demo{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
System.out.println(“errorr……”);
}
}

o/p:

D:\OCJP>javac FinalClassObject.java
FinalClassObject.java:7: error: cannot inherit from final Final_Demo
public class FinalClassObject extends Final_Demo{
^
FinalClassObject.java:7: error: constructor Final_Demo in class Final_Demo canno
t be applied to given types;
public class FinalClassObject extends Final_Demo{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
2 errors

Creating Object for enum:

Enums cannot be intialized as they only a private constructor.

public enum Sample{
   READ,WRITE
}   


//Will get convetred the above code into below internally.


class Sample extends Enum {
    public static final Sample READ = new Sample("READ", 0);
    public static final Sample WRITE = new Sample("WRITE", 1);

    private Sample(String s, int i)
    {
        super(s, i);
    }

    // More methods, e.g. getter
}

Is Java is case-sensitive language?

YES…yes

Look at below snippet.

public class Main_Demo{
public static void main(String[] args)throws Exception{
System.out.println(“Keep Challenging………….”);
System.out.println(“Building tomorrow’s enterprise………….”);
String name=”cognizant”;
String NAME=”Infosys”;
System.out.println(name);
System.out.println(NAME);
}
}

 

D:\OCJP>javac Main_Demo.java

D:\OCJP>java Main_Demo
Keep Challenging………….
Building tomorrow’s enterprise………….
cognizant
Infosys

D:\OCJP>

Though both having same name as name because of the feature of case sensitiveness. It takes as two different strings.

Even if i compile with case it won’t work.

D:\OCJP>javac Main_Demo.java

D:\OCJP>java MAIN_DEMO
Error: Could not find or load main class MAIN_DEMO

D:\OCJP>java main_demo
Error: Could not find or load main class main_demo

D:\OCJP>Main_Demo
‘Main_Demo’ is not recognized as an internal or external command,
operable program or batch file.

D:\OCJP>java Main_Demo
Keep Challenging………….

Case sensitive  and case- insensitive Languages:

https://en.wikipedia.org/wiki/Case_sensitivity

Some computer languages are case-sensitive for their identifiers (C, C++, Java, C#, Verilog,[1] Ruby[2] and XML). Others are case-insensitive (i.e., not case-sensitive), such as Ada, most BASICs (an exception being BBC BASIC), Fortran, SQL[3] and Pascal.

 

 

DatabaseMetadata(I) in JDBC

  • public interface DatabaseMetaData
    extends Wrapper
  • omprehensive information about the database as a whole.This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBCTM technology (“JDBC driver”) that is used with it. Different relational DBMSs often support different features, implement features in different ways, and use different data types. In addition, a driver may implement a feature on top of what the DBMS offers. Information returned by methods in this interface applies to the capabilities of a particular driver and a particular DBMS working together. Note that as used in this documentation, the term “database” is used generically to refer to both the driver and DBMS.

    A user for this interface is commonly a tool that needs to discover how to deal with the underlying DBMS. This is especially true for applications that are intended to be used with more than one DBMS. For example, a tool might use the methodgetTypeInfo to find out what data types can be used in a CREATE TABLE statement. Or a user might call the method supportsCorrelatedSubqueries to see if it is possible to use a correlated subquery or supportsBatchUpdates to see if it is possible to use batch updates.

    Some DatabaseMetaData methods return lists of information in the form of ResultSet objects. Regular ResultSet methods, such as getString and getInt, can be used to retrieve the data from these ResultSet objects. If a given form of metadata is not available, an empty ResultSet will be returned. Additional columns beyond the columns defined to be returned by the ResultSet object for a given method can be defined by the JDBC driver vendor and must be accessed by their column label.

    Some DatabaseMetaData methods take arguments that are String patterns. These arguments all have names such as fooPattern. Within a pattern String, “%” means match any substring of 0 or more characters, and “_” means match any one character. Only metadata entries matching the search pattern are returned. If a search pattern argument is set to null, that argument’s criterion will be dropped from the search.

     

  • https://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html
  • A simple example on databasemaetadata(I)
  • ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)

    Retrieves a description of the tables available in the given catalog.
  • package practice;

    import java.sql.*;
    import oracle.jdbc.driver.*;

    class getVersion
    {
    public static void main (String args[])
    throws SQLException
    {
    // Load the Oracle JDBC driver
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    //Creates the Connection object
    Connection conn = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
    // Create Oracle DatabaseMetaData object
    DatabaseMetaData meta = conn.getMetaData();
    // gets driver info:
    System.out.println(“JDBC driver version is ” + meta.getJDBCMajorVersion());
    System.out.println(“JDBC driver name is”+meta.getDriverName());

    DatabaseMetaData md = conn.getMetaData();
    String[] strings={“TABLE”};
    ResultSet rs = md.getTables(null, null, “%”,strings);
    while (rs.next()) {
    System.out.println(rs.getString(3));
    }
    }
    }

    output:

    JDBC driver version is 11
    JDBC driver name isOracle JDBC driver
    APEX$_ACL
    APEX$_WS_FILES
    APEX$_WS_HISTORY
    APEX$_WS_LINKS
    APEX$_WS_NOTES
    APEX$_WS_ROWS
    APEX$_WS_TAGS
    APEX$_WS_WEBPG_SECTIONS
    APEX$_WS_WEBPG_SECTION_HISTORY
    SYS_IOT_OVER_16977
    WWV_COLUMN_EXCEPTIONS
    WWV_DEMO_DEPT
    WWV_DEMO_EMP
    WWV_FLOWS
    WWV_FLOWS_RESERVED
    WWV_FLOW_ACTIVITY_LOG1$
    WWV_FLOW_ACTIVITY_LOG2$
    WWV_FLOW_ACTIVITY_LOG_NUMBER$
    etc…………………………………………………………………..

Driver Manger Class in JDBC

  • public class DriverManager
    extends Object
  • It is the satatic class in java SDK.
  • First, you need to establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. Typically, a JDBC application connects to a target data source using one of two classes:

    DriverManager: This fully implemented class connects an application to a data source, which is specified by a database URL. When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within the class path. Note that your application must manually load any JDBC drivers prior to version 4.0.

    DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object’s properties are set so that it represents a particular data source. See Connecting with DataSource Objects for more information. For more information about developing applications with the DataSource class, see the latest The Java EE Tutorial.

  • //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  • Class.forName() is not directly related to JDBC at all. It simply loads a class.

    Most JDBC Driver classes register themselves in their static initializers by calling registerDriver().

    registerDriver() is the real call that you hardly ever need to call yourself (unless you write your own JDBC driver).

    Note that in JDBC 4 you should not need either of those if your JDBC driver is up-to-date, as drivers can be found using the service location mechanisms instead (i.e. simply leave out that call and open your connection as usual). See the documentaton of DriverManager for details:

    The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

    my.sql.Driver

    Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

     

  • Never call DriverManager.registerDriver() method manually. The JDBC spec requires a driver to register itself when the class is loaded, and the class is loaded via Class.forName(). In JDBC 4 the drivers are able to be loaded automatically just by being on the class path.

    DriverManager.registerDriver() manually is potentially dangerous since it actually causes the Driver to be registered twice. If your code requires you to deregister a Driver to prevent a memory leak then you would only end up deregistering it once and leave a second instance registered.

https://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html

http://www.ibm.com/support/knowledgecenter/ssw_i5_54/rzaha/db2drivr.htm

  • Example:
  • package practice;

    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class SimpleConnection {
    public static void main(String[] args) throws SQLException {
    String url=”jdbc:oracle:thin:@localhost:1521:xe”;
    String uname=”system”;
    String pwd=”madhu”;

    //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    try {
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    //Class.forName(“oracle.jdbc.driver.OracleDriver”).newInstance();
    //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
    Statement statement=connection.createStatement();

    ResultSet resultSet=statement.executeQuery(“select * from contact”);
    while(resultSet.next()){
    System.out.println(resultSet.getString(1));
    }
    connection.close();
    }
    }

    output:

    madhu
    charan
    surbhi
    ammu
    indra

     

wordpress_db_statement

oracle ojdbc6.jar location: C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib

 

JDBC

  • JDBC stands for JAVA DATA BASE CONNECTIVITY.
  • It is used to establish and maintains the connection in between java application and the data base.
  • JDBC uses various types of drivers in order to maintain a connection with the data base.
  • What is API

    API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other. An API can be created for applications, libraries, operating systems, etc

  • There are many possible implementations of JDBC drivers. These implementations are categorized as follows:

    • Type 1: Drivers that implement the JDBC API as a mapping to another data access API, such as ODBC (Open Database Connectivity). Drivers of this type are generally dependent on a native library, which limits their portability. The JDBC-ODBC Bridge is an example of a Type 1 driver.Note: The JDBC-ODBC Bridge should be considered a transitional solution. It is not supported by Oracle. Consider using this only if your DBMS does not offer a Java-only JDBC driver.
    • Type 2: Drivers that are written partly in the Java programming language and partly in native code. These drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited. Oracle’s OCI (Oracle Call Interface) client-side driver is an example of a Type 2 driver.
    • Type 3: Drivers that use a pure Java client and communicate with a middleware server using a database-independent protocol. The middleware server then communicates the client’s requests to the data source.
    • Type 4: Drivers that are pure Java and implement the network protocol for a specific data source. The client connects directly to the data source.

    http://www.javatpoint.com/jdbc-driver

  • Data Source:  A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. This connection is represented by a Connection object.
  • The “type” refers to how the driver implements the API. The four types are:Type 1: JDBC-ODBC Bridge driver (Bridge)

    Type 2: Native-API/partly Java driver (Native)

    Type 3: AllJava/Net-protocol driver (Middleware)

    Type 4: All Java/Native-protocol driver (Pure)

    They will have different performance characteristics. See this link for a more detailed review.

  • The major features added in JDBC 4.0 include:
    1. Auto-loading of JDBC driver class
    2. Connection management enhancements
    3. Support for RowId SQL type
    4. DataSet implementation of SQL using Annotations
    5. SQL exception handling enhancements
    6. SQL XML support
  • package practice;

    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class SimpleConnection {
    public static void main(String[] args) throws SQLException {

    String url=”jdbc:oracle:thin:@localhost:1521:xe”;
    String uname=”system”;
    String pwd=”madhu”;

    //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

    Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);

    ResultSet resultSet=statement.executeQuery(“select * from contact”);
    while(resultSet.next()){
    System.out.println(resultSet.getString(1));
    }
    connection.close();*/
    }
    }

    output:

  • madhu
    charan
    surbhi

 

 

Java-Pass by value vs(>) Pass by reference

Does java fallows passbyValue or passbyReference?

                                   One of the most confusing stuff in the java programming.Java allows only passbyValue mechanism(If we pass a reference variable as a method parameter,Java internally takes the reference as normal java variable).The below code brief you about this.

package practice;

import java.awt.Point;

public class Demos {
public static void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point point=new Point(125, 125);
Point temp = arg1;
arg1 = arg2;
arg2 = point;
System.out.println(“X: ” + arg1.x + ” Y: ” +arg1.y);
System.out.println(“X: ” + arg2.x + ” Y: ” +arg2.y);
System.out.println(” “);
}
public static void tricky_refrence(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
arg2.setLocation(new Point(500, 500));
Point point=arg1;
arg1=arg2;
arg2=point;
System.out.println(“X: ” + arg1.x + ” Y: ” +arg1.y);
System.out.println(“X: ” + arg2.x + ” Y: ” +arg2.y);
System.out.println(” “);
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
Point pnt3 = new Point(0,0);
System.out.println(“X: ” + pnt1.x + ” Y: ” +pnt1.y);
System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(” “);
tricky(pnt1,pnt2);
System.out.println(“X: ” + pnt1.x + ” Y:” + pnt1.y);
System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(” “);
tricky_refrence(pnt2,pnt3);
System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(“X: ” + pnt3.x + ” Y:” + pnt3.y);

RefExample refExample=new RefExample(“SECOND”);
System.out.println(refExample.string);
tricky_refrenceobject(refExample);
System.out.println(refExample.string);
tricky_refrenceobjectargchange(refExample);
System.out.println(refExample.string);
int a=123;
changeValue(a);
System.out.println(a);
}
private static void changeValue(int a) {
a=10;
}
private static void tricky_refrenceobject(RefExample refExample) {
System.out.println(“——Changed the reference—-“);
RefExample refExample22=new RefExample(“THIRD”);
refExample=refExample22;
System.out.println(refExample.string);
}
private static void tricky_refrenceobjectargchange(RefExample refExample) {
System.out.println(“———We changed the reference argument—“);
refExample.string=”FORTH”;
System.out.println(refExample.string);
}
}

class RefExample{
public RefExample(String string2) {
this.string=string2;
}

public String string=”FIRST”;
}

 

X: 0 Y: 0
X: 0 Y: 0

X: 0 Y: 0
X: 125 Y: 125

X: 100 Y:100
X: 0 Y: 0

X: 500 Y: 500
X: 100 Y: 100

X: 100 Y: 100
X: 500 Y:500
SECOND
——Changed the reference—-
THIRD
SECOND
———We changed the reference argument—
FORTH
FORTH
123

 

-Thank you.

read() ,read(byte[] b) and read(byte[], int offset, int length) in InputStream class in JAVA

package io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class First {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream=null;

if(fileInputStream==null){
try {
fileInputStream=new FileInputStream(“C:\\Users\\Always Madhu\\Desktop\\p.txt”);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

int i=0;
while((i=fileInputStream.read())!=-1){
System.out.print((char)i);

}

byte[] bs=new byte[fileInputStream.available()];
for(int i1=0;i1<bs.length;i1++){
System.out.println((char)bs[i1]);
}

 

byte b1[]=new byte[fin2.available()];
fin2.read(b1,0,b1.length);
System.out.println(“\n\nThird way\n”);
for(int i=0;i<b1.length;i++)
{
System.out.print((char)b1[i]);
}

}
}

AtomicInteger Class and All its Methods With Examples in JAVA

Refer Here………….link

 

package com.me.ocjp;

import java.io.Console;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {
public static void main(String[] args) {

//constructors
AtomicInteger atomicInteger=new AtomicInteger();
atomicInteger.set(123);
System.out.println(atomicInteger);

AtomicInteger atomicInteger2=new AtomicInteger(246);
System.out.println(atomicInteger2);

System.out.println(“—————————————“);

//get() set()
atomicInteger.set(552);
System.out.println(atomicInteger.get());
atomicInteger2.set(579);
System.out.println(atomicInteger2.get());

System.out.println(“—————————————“);

//compare and SET
AtomicInteger atomicInteger3=new AtomicInteger(571);
System.out.println(atomicInteger3);

Scanner scanner=new Scanner(System.in);
System.out.println(“Enter the Number:”);
String output=scanner.next();

//if we enter other than 571 atomicInteger3 value dsnt change
//if input==571 then mentioned 125 will be updated.
atomicInteger3.compareAndSet(Integer.parseInt(output), 125);
System.out.println(atomicInteger3);

System.out.println(“—————————————“);

//Week compare and SET
AtomicInteger atomicInteger30=new AtomicInteger(552);
System.out.println(atomicInteger30);

Scanner scanner1=new Scanner(System.in);
System.out.println(“Enter the Number:”);
String output0=scanner1.next();

//if we enter other than 552 atomicInteger3 value dsnt change
//if input==552 then mentioned 1024 will be updated.
atomicInteger30.weakCompareAndSet(Integer.parseInt(output0), 1024);
System.out.println(atomicInteger30);

System.out.println(“—————————————“);

//Add and Get and ++,after add

AtomicInteger atomicInteger4=new AtomicInteger();
atomicInteger4.set(123);
System.out.println(atomicInteger4);

//Get——>———–>then adds +specified no——-returns—->
System.out.println(atomicInteger4.addAndGet(100));
System.out.println(atomicInteger4);

//Get——>retuns———–>then adds +specified no———–>
System.out.println(atomicInteger4.getAndAdd(100));
System.out.println(atomicInteger4);

//Get——>retuns———–>then adds +1———–>
System.out.println(atomicInteger4.getAndIncrement());
System.out.println(atomicInteger4);

//Get——>———–>then adds +s1——-returns—->
System.out.println(atomicInteger4.incrementAndGet());
System.out.println(atomicInteger4);

//sub and Get and –,after sub

AtomicInteger atomicInteger5=new AtomicInteger();
atomicInteger5.set(123);
System.out.println(atomicInteger5);

//Get——>———–>then adds -1 ——-returns—->
System.out.println(atomicInteger5.decrementAndGet());
System.out.println(atomicInteger5);

//Get——>retuns———–>then adds -1 no———–>
System.out.println(atomicInteger5.getAndDecrement());
System.out.println(atomicInteger5);

System.out.println(“————————————–“);

AtomicInteger atomicInteger6=new AtomicInteger();
atomicInteger6.set(123);
System.out.println(atomicInteger6);

//diff types of data representations
System.out.println(atomicInteger6.byteValue());
System.out.println(atomicInteger6.doubleValue());
System.out.println(atomicInteger6.floatValue());
System.out.println(atomicInteger6.intValue());
System.out.println(atomicInteger6.shortValue());

System.out.println(“———————“);

//—-return old value—–and sets new value—-123 552->
System.out.println(atomicInteger6.getAndSet(552));
System.out.println(atomicInteger6.get());

//it adds the atomicInteger6 value +709 and saves it to atomicInteger6
System.out.println(atomicInteger6.accumulateAndGet(709,(a, b) -> a + b));
System.out.println(atomicInteger6);

//——–return previous value—then adds the value and saves to object.
System.out.println(atomicInteger6.getAndAccumulate(709,(a, b) -> a + b));
System.out.println(atomicInteger6);

System.out.println(“—————————-“);

AtomicInteger atomicInteger7=new AtomicInteger();
atomicInteger7.set(123);
System.out.println(atomicInteger7);

//updates value by solving exp —perform add/mul/sub then
//saves to obj
//return result
System.out.println(atomicInteger7.updateAndGet(i->i*100));
System.out.println(atomicInteger7);

//return result
//updates value by solving exp —perform add/mul/sub then
//saves it to obj
System.out.println(atomicInteger7.getAndUpdate(i->i*100));
System.out.println(atomicInteger7);
}
}

 

123
246
—————————————
552
579
—————————————
571
Enter the Number:
571
125
—————————————
552
Enter the Number:

552
1024
—————————————
123
223
223
223
323
323
324
325
325
123
122
122
122
121
————————————–
123
123
123.0
123.0
123
123
———————
123
552
1261
1261
1261
1970
—————————-
123
12300
12300
12300
1230000