Thursday, February 14, 2013

Java Interview Question Answers

Friends, Here am posting some of key knowledge point which helps you to prepare basic interview question:


Fundamental Object-Oriented Concepts
  1. An interface can extend any number of interfaces, and a class can implement any number of interfaces. However, a class cannot extend more than one class.
  2. The field members in an interface are implicitly public, final, and static. Interface methods cannot be static, final, private, or protected. They are implicitly public, abstract, and non-static. Methods are only declared, that is, their implementations are not provided in the interface.
  3. An abstract class is a class, which cannot be instantiated. Abstract classes can have both abstract and non-abstract methods. They can extend other classes and implement interfaces as well. They may or may not implement the abstract methods declared in their superclasses.
  4. A concrete class is a class which can be instantiated. Hence, it can be considered as a non-abstract class. It cannot contain any abstract methods. Such a class can extend an abstract or a concrete class. If it extends an abstract class, it must implement all the abstract methods in its superclass. If it implements an interface, it must implement all the methods declared in that interface.
  5. Abstract classes can have constructors, while interfaces cannot.
  6. A final class cannot be extended, so it is forbidden to declare a class to be both final and abstract.
  7. Variables declared as final are constants, while methods declared as final cannot be overridden. Primitive types available in Java are boolean, char, byte, short, int, float, and double. boolean values of true and false cannot be assigned to any other primitive type.
  8. The primitive wrapper classes in Java are Number, Integer, Character, Long, Float, Double, Byte, Short, and Boolean. Number is the abstract superclass of Integer, Long, Float, Byte, and Short. Except for Character and Integer, all the other types have the same name as the corresponding primitive type with the starting letter uppercased.
  9. According to the JavaBean naming standards, if the property name is 'x' and the type is Type, the accessor(getter) method is in the form:
    public Type getX()
    and the mutator(setter) method is in the form:
    public void setX(Type newValue)
    However, a boolean property may also use the following convention for its accessor(getter) method.
    public boolean isX()
  10. Values of an enumerated type in Java are not just integers or strings as in other languages. They are instances of the defined enumerated type.
  11. Enumerated types(enums) are declared using the enum keyword. They can be defined as a separate type or as a member of a class. However, they cannot be defined in a method.
  12. When we use the "program to interface" principle, the communication is based on an interface, rather than directly referring to the actual implementing class. Benefits are flexibility, loose coupling, reusability, and polymorphic capabilities.
  13. When we use encapsulation, we keep our instance variables hidden from the outside code (with an access modifier, often private). We provide public accessor methods and force the calling code to use those methods, rather than directly accessing the instance variables of our class. Benefits are data safety and maintainability.
  14. An association is a channel between classes, through which messages can be sent. In an association, classes may access each other's methods to communicate.
  15. Association is implemented using instance variables, which are references to objects participating in the relationship. An object may contain a reference to an object of the same class.
  16. Association navigation defines the direction of the relationship, which exists between the participants of the association. A unidirectional relationship can be traversed in only one direction, that is, only one of the participants has a reference to the other. However, a bi-directional relationship can be traversed in both directions, because both participants maintain references to each other.
  17. Multiplicity specifies how many objects of one class (the target class) may be associated with a single object from the other class (the source class).
  18. Composition is a special type of association, which can be considered as a part-of relationship, where the lifetime of the part is controlled by the whole. This cannot be a bi-directional relationship.
  19. Polymorphism refers to "many forms". It allows you to use a supertype (a superclass or an interface) reference to refer to one of its subtypes.
  20. Enumerations cannot be extended and hence cannot contain abstract methods.
UML Representation of Object-Oriented Concepts
  1. In UML, abstract types (abstract classes and interfaces) and methods are represented in italics. In the case of interfaces, an additional requirement is that the word <<interface>> is added above the interface name.
  2. An association between two classes is shown as a solid line between the classes. The navigability of an association is expressed as an open arrow at the end of the association line.
  3. The multiplicity of an association is labeled on either end of the line using multiplicity indicators. The indicators are summarized below.
    Indicator
    Meaning
    0..1
    Zero or one
    1
    One only
    0..*
    Zero or more
    1..*
    One or more
    n
    Only n
    m..n
    Between m and n
  4. A class, which implements an interface, is connected to that interface using a dashed line with a triangle pointing to the interface.
  5. The generalization/inheritance relationship is represented by an empty/open triangle that points from the more specialized class to the more general class. In the case of multiple subclasses for the same superclass, there might be multiple lines ending in separate triangles or all the lines merging into a single triangle.
  6. UML uses '+' and '-' symbols to indicate public and private modifiers, respectively.
  7. Composition relationship is represented by a line between two classes with a filled diamond at the end of the class which represents the whole.
  8. A class diagram is drawn as a rectangle with three parts. The first part has the name of the class in bold. The second part lists the attributes (name and type separated by a colon) and the third part lists the operations.
  9. Object diagrams are useful for describing complex relationships between objects. The object diagram shows the name of the instantiated object separated from the class name by a ":" and underlined to show an instantiation.
  10. Role names can be specified to name associations in cases, where it may not be clear what role a class is playing in a particular association.
  11. An alternate notation called lollipop notation can also be used to indicate interface implementation, where the interface is represented by a small circle attached to the class by a solid line. In this case, you do not list the operations defined by the interface.
Java Implementation of Object-Oriented Concepts
  1. The visibility rules for access modifiers are as follow:
    o private - can only be accessed from inside the class.
    * No modifier - can be accessed only by other classes in the same package. Members having no modifier can be considered to have default access level.
    * protected - can only be accessed by classes in the same package or its subclasses.
    * public - can be accessed by any class.
  2. An enumeration is defined using the enum keyword, as shown below.
    For example,
    enum Fruit{
    Apple,
    Mango,
    Banana
    }
    Variables of the defined enum type can then be created like this:
    Fruit f = Fruit.Apple;
    Fruit f1 = Fruit.Mango;
    Fruit f2 = Fruit.Banana;
  3. Enumerated types can contain instance variables, methods, and constructors.
  4. When an array is created, all its elements get initialized to the default values for its data type automatically.
  5. To get the size of an array, we use an array instance variable called 'length'. Arrays are indexed beginning with zero and ending with length-1.
  6. When the multiplicity of an association is more than 1, the instance variable to represent it must be modeled as an array or a collection.
  7. A class, which implements an interface, must be marked abstract, if it does not implement all the methods defined by it.
  8. Marking the methods of an interface as public or abstract are allowed even though it is not required, since they are implicitly public and abstract.
  9. Static variables of a class are shared by all objects of the class, while a separate copy of instance variables is maintained by each object.
  10. Interface implementation uses the keyword 'implements' and inheritance uses the keyword 'extends'. If a class extends another class and also implements one or more interfaces, the 'extends' clause must precede the 'implements'clause.
  11. We can define the top of any class hierarchy with an abstract class or an interface, which implements no methods but simply defines the methods that the derived classes will support. The derived classes provide their own implementations for these methods. The client code does not invoke the methods on the derived classes but directly on the interface or abstract class instead. This is how we implement the "program to an interface" principle.
  12. An abstract method cannot be declared final, private, or static.
  13. An interface-type reference variable can hold an object of any class, which implements the interface. A class-type reference variable can hold an object of any subclasses from its inheritance hierarchy.
  14. All variables in the Java language must have a data type. Primitive types can be of integer, floating-point, character, or boolean type. The available types are listed below.
    TypeSize
    byte8-bits (integral)
    short16-bits (integral)
    int32-bits (integral)
    long64-bits (integral)
    float32-bits (floating-point)
    double64-bits (floating-point)
    char16-bits (Unicode)
  15. To define long literals, we can place a suffix 'L' or 'l' after the number.
    1. Eg: long l=100598L;
    2. long l=100598l;
  16. The default type of a floating point literal is double. To specify it as float, we need to append 'F' or 'f' to the literal.
    1. Eg: float f=5.3F;
    2. float f=5.3f;
  17. The char literal can be represented as a single character within two single quotes, as a unicode character or as an integer less than 65536.
  18. A boolean literal can have only one of the two values: true or false.
  19. A String literal is a set of characters enclosed within two double quotes.
  20. All instance and static variables are initialized to their default values. The default values for the various data types are listed below.
    Variable TypeDefault Value
    Object referencenull
    byte, short, int, long0
    float, double0.0
    booleanfalse
    char'\u0000'
  21. Local variables never give a default value, so they have to be explicitly initialized before use.
  22. Parameters are formal arguments to methods or constructors. These are also used to pass values into methods and constructors. The scope of a parameter is the entire method or the constructor into which it is passed.
Algorithm Design and Implementation
  1. The syntax of the 'for' loop is as follows: for(expr1; expr2; expr3) { body }
    where expr1 is the initialization expression, expr2 is the conditional test and expr3 is the iteration expression.
    Any or all of these three sections could be omitted and the code would still be legal.
    For example: for( ; ; ) {} // an endless loop
  2. The enhanced for loop is in the form:
    for (Type Identifier: Expression) Statement
    The expression must be either an array or a collection. It provides a simple way to iterate through the contents of an array or a collection.
  3. The body of the 'while'loop may not be executed even once. 
    For example: while(false){} 
    The body of the 'do-while' loop is always executed at least once. 
    For example: do { } while(false);
  4. The argument to the switch statement can be a byte, a short, a char, an int, or an enum type. The argument passed to the case statement should be a literal or a final variable.
  5. The break statement is used to exit from a loop or a switch statement. The continue statement is used to stop just the current iteration of a loop and to proceed the next one.
  6. In Java, method arguments are always passed by value. In case of primitive type arguments, the value of primitive variable is copied into the parameter received within the called method. Modifying the primitive variable, does not affect the original variable that has been passed into the method.
  7. When you pass an object reference into a method, only a copy of the reference variable is actually passed. The copies of the variable in the caller and called methods are identical, so both refer to the same object. If the object is modified inside the method, the change is affected to the object referenced outside the method as well.
  8. The "==" operator compares the values of primitive types and object references. When comparing reference variables using the "==" operator, it returns true only if the reference variables are referring to the same object.
  9. All Java classes implicitly extend java.lang.Object. The Object class provides the equals(Object obj) method, which can be overridden to return "true" if two objects are considered meaningfully equal.
  10. '||' and '&&' are called short-circuit operators, because the right operand is not evaluated if the result of the operation can be determined after evaluating only the left operand. In case of '&' and '|', both operands are always evaluated.
  11. '++' increment operator - Increments a value by 1 '--' decrement operator - Decrements a value by 1
    Prefix (the operator is placed before the variable)
    Example: x=++y;

    Postfix (the operator is placed after the variable)
    Example: x=y++;


    In the first case, 'y' will be incremented first and then assigned to 'x'. In the second case, 'y' will be assigned to 'x'first and then it will be incremented.
  12. The % operator is used to get the remainder of a division operation.
  13. String objects are immutable, so attempting to modify a string results in the creation of a new String.
  14. The length() method of the String class returns the number of characters in the String object on which it is invoked. String indexing is zero-based, hence the valid indexes are 0 to String.length()-1.
  15. The replace method of the String class returns a new string resulting from replacing all occurrences of oldChar in the string with the specified newChar.
  16. String replace(char oldChar, char newChar)
  17. The indexOf(char ch) method of the String class is used to get the location of a specified character within a String.
  18. The trim() method of the String class returns a copy of a string, with leading and trailing whitespace(s) omitted.
  19. The charAt(index) method of the String class returns the character at the specified index in a String.
  20. The startsWith(String prefix) returns true if a String starts with the given prefix, and the endsWith(String suffix) method returns true if a String ends with the given suffix.
  21. The substring method of the String class returns a portion of the String on which it is invoked. Two overloaded substring methods are given below. 
    public String substring(int beginIndex);
    - Returns all the characters from the specified beginIndex till the end of the String.

    public String substring(int beginIndex, int endIndex);
    - Returns all the characters from the specified beginIndex till endIndex - 1.
  22. The operators '+' and '+=' are overloaded to work with String objects, the '+' operator concatenates two strings, while the '+=' operator concatenates and assigns the resulting string to the variable on the left.
Java Development Fundamentals
  1. The java.util package contains the collections framework, legacy collection classes, event model, date, and time facilities, internationalization, and miscellaneous utility classes such as a string tokenizer, a random-number generator, and a bit array.
  2. The java.net package contains classes to implement networking applications. These include socket programming classes and the classes, which use Universal Resource Locators (URLs) to retrieve data on the Internet.
  3. The java.io class contains classes, which provide input and output through data streams, serialization, and the file system.
  4. In Java language, every class is placed in a package. If the source code for a class doesn't have a package statement at the top, then the class is considered to be located in the default package.
  5. There are three top-level elements that may appear in a compilation unit. None of these elements is mandatory. If they are present, then they must appear in the following order:
    * package declaration
    * import statements
    * class definitions
  6. In a source file, there can be only one public class, and the name of the file should match that of the class.
  7. There can be only one package statement, but any number of import statements, in a source file. Import and package declarations apply to all classes in a source code file.
  8. When you use a class, which is defined in another package without importing the package, the fully qualified class name must be used. If you do import the package, you can use the simple unqualified class name.
  9. If you import classes from two different packages and refer to a class, which has the same name in both packages, then you must use the fully qualified class name to avoid ambiguity.
  10. Java compiler automatically imports three entire packages: 
    * The default package (the package with no name)
    * The java.lang package
    * The current package by default
  11. The java.lang package provides classes that are fundamental to the design of Java programming language. The Object class, which is the superclass of all Java classes and the Exception class, which is the superclass of all exceptions belong to this package.
  12. Import statements can be of two forms - wildcard import and explicit class import. 
    For example:
    import java.util.*; //wildcard - imports all classes in java.util package
    import java.util.ArrayList; //explicit - imports the ArrayList class in java.util package
  13. Classpath can be set either by setting the CLASSPATH environment variable or by using the -classpath option along with the javac or java commands.
  14. To include a JAR file in the class path, the path must refer to the JAR, not merely the directory that contains the JAR.
  15. For class files in the default unnamed package, the class path ends with the directory that contains the class files.For example, for a class Test, which does not have a package statement, the directory containing Test.class must be in the class path.
  16. For class files in a named package, the class path ends with the directory that contains the first package in the full package name. For example, if Test class belongs to the package hello.abc, and the directory structure is xyz/hello/abc/Test.class, then the directory hello must be in the class path.
  17. If you want to include the current directory in the search path, you must include "." in the classpath.
  18. The - jar option is used with the java command to execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name.
  19. The options -version and -showversion can be used along with the java tool to display the product version information. The difference is that the -version switch displays the version information and exits, while the -showversion switch displays more information than just the version information.
  20. To set a system variable, we use the java tool with the -D option as shown below. The propertyname=value pair which must be appended directly after -D
    C:> java -Dproperty=value
  21. The -d option of the javac command helps you to set the destination directory, where the compiler must place the class files. If a class is specified to be located in a package, the javac command puts the class file in a subdirectory reflecting the package name and creating directories as needed. However, the main destination directory must exist before executing the command and cannot be automatically created by the command.
Java Platforms and Integration Technologies
  1. Java 2 Platform, Micro Edition (J2ME) provides a robust flexible environment for applications running on consumer devices such as mobile phones, PDAs, and other embedded devices.
  2. J2ME (Java 2, Micro Edition) consists of three software layers - JVM, Configuration, and Profile. The configuration acts as an interface between the JVM and the profile, while a profile defines the set of APIs available for a particular family of devices.
  3. Configurations provide base functionalities for a particular range of devices that share similar characteristics such as network connectivity and memory footprint.
  4. There are two J2ME configurations: Connected Limited Device Configuration (CLDC) and Connected Device Configuration (CDC).
  5. CLDC is the smaller of the two configurations and is specifically designed for devices with low memory and limited resources like mobile phones, two-way pagers, and PDAs.
  6. CDC is designed for devices that have more resources like memory and speed such as TV set-top boxes and high-end PDAs.
  7. A J2ME application requires J2ME runtime environment to execute.
  8. J2ME applications developed for a given device do not necessarily work on other devices.
  9. J2SE API is included in all J2EE environments, so J2SE applications can run in both J2SE and J2EE environments .
  10. Java Naming and Directory Interface (JNDI) provides a unified interface to Java applications for lookup and directory services.
  11. JNDI API exists in five packages. 
    They are

    * javax.naming
    * javax.naming.directory
    * javax.naming.event
    * javax.naming.ldap
    * javax.naming.spi
  12. RMI (Remote Method Invocation) allows methods of remote Java objects to be invoked from other Java virtual machines possibly on different hosts. The API is defined in the java.rmi package.
  13. The RMI (Remote Method Invocation) technology makes use of stubs and skeletons. The stub and skeleton handle the communication between the client application and the server object.
  14. RMI (Remote Method Invocation) offers the following advantages over sockets:
    * Simplicity and Ease of use
    * No protocol design required
    However, the disadvantage of RMI is that it is slower than socket communication.
  15. Object serialization is the mechanism used by RMI to pass objects between two JVMs, either as arguments or as a return type of a method invocation from a client to a server.
  16. The Java Message Service (JMS) API is defined in the javax.jms package. It provides a common way for Java programs to create, send, receive, and read messages of an enterprise messaging system.
  17. JMS (Java Message Service) offers loosely-coupled communication through messages that are delivered by a messaging server. It means that the sender and the receiver do not have to be available at the same time in order to send and receive messages.
  18. JDBC technology refers to an API that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources such as spreadsheets or flat files.
  19. JDBC API is included in both java.sql and javax.sql packages. The java.sql package is referred as the JDBC core API, and the javax.sql package is referred as the JDBC Optional Package API.
  20. The JDBC driver API is contained in the java.sql.Driver interface and must be implemented by every database driver.
  21. SQL (Structured Query Language) is designed for querying data contained in a relational database.
  22. A Relational Database Management System (RDBMS) is a Database Management System (DBMS) that is based on relational model.
Client Technologies
  1. Swing components are pure Java GUI components, which are defined in the javax.swing package.
  2. Abstract Window Toolkit (AWT) components are defined in the java.awt package. They use native peer components, so they are considered to be heavyweight as compared to swing components, which are pure Java components.
  3. Swing provides many more components than AWT with enhanced capabilities.
  4. The Swing technology provides GUI components with a pluggable look-and-feel like Motif or Windows look-and-feel.
  5. Use of native code enables AWT to run faster than Swing.
  6. JavaScript can be used in web pages to provide form manipulations such as client side validations, event handling, and some visual effects.
  7. JavaScript works only on a JavaScript-compliant web browser. It might be interpreted differently by different browsers also.
  8. HTML stands for HyperText Markup Language. It is a stateless language, which can embed text, pictures, sounds, and links in a single document.
  9. HTML can be used to render the look and feel of a web page, but it cannot do any dynamic tasks like input validation.
  10. A MIDlet is a Java program for embedded devices, more specifically for the J2ME virtual machines. They are programmed based on the Mobile Information Device Profile (MIDP), a set of Java APIs, which together with the Connected Limited Device Configuration (CLDC) provides a complete Java 2 Micro Edition (J2ME) runtime environment for cellular phones, two-way pagers and palmtops.
  11. In order to deploy a J2ME MIDlet Suite on a J2ME device, it must first be deployed as a JAD (Java Application Descriptor) and a JAR (Java Archive) file. The JAD file provides information to the application manager about the contents of the associated JAR file.
  12. Applets are user interface components, which typically execute in a web browser. They need a JVM to execute on - either the browser's JVM or the one from Java plug-in.
  13. Applets are portable, since they are written in Java and do not require any client-side installation. They make use of Java security features and execute within the browser's sandbox under a lot of restrictions.
  14. An applet has a better chance of running in an intranet than in an internet, because it needs a standardized set of client components.
  15. Swing applets can have menus, while AWT applets cannot.
Server Technologies
  1. In the business tier, a Message-Driven Bean (MDB) allows J2EE (Java 2 Enterprise Edition) applications to receive JMS (Java Messaging Service) messages asynchronously, that is, senders are independent of receivers.
  2. Simple Object Access Protocol (SOAP) is an XML-based platform-neutral protocol to send structured messages.
  3. Enterprise JavaBeans (stateful session beans, stateless session beans, and message-driven beans) are part of the business tier of a J2EE application.
  4. Servlets and JSP are part of the web tier of a J2EE application.
  5. JAX-RPC is for web services interoperability across heterogeneous platforms and languages. It provides support for WSDL-to-Java and Java-to-WSDL mappings as part of the development of web services clients and endpoints.
  6. Entity beans are used for persisting business layer data.
  7. Stateful session beans retain the conversational state of their clients across multiple method calls. However, stateless session beans are dedicated to their clients only for the duration of the method call.
  8. Entity beans can be shared by multiple clients at the same time.
  9. Stateful session beans are dedicated to a single client throughout their life and hence cannot be accessed concurrently by multiple clients. Even Stateless session beans are dedicated to a client, while their method is in execution.
  10. A message-driven bean allows J2EE applications to receive JMS messages asynchronously. They contain business logic for handling received messages.
  11. Servlets and JSP components are responsible for producing dynamic content in response to requests from the server. JSP pages are typically used for creating structured or free-form textual data, while servlets are used more for implementing logic.
  12. JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.
  13. Servlets are well-suited for dynamically generating binary data such as images. Such requests can be mapped to servlets that know how to generate the content. JSP pages are a poor choice for generating binary data.
  14. Data shared between JSP pages and servlets is best-maintained in application, session, request, or page scope as a JavaBean component.
  15. WSDL (Web Service Definition Language) specifies an XML format for describing a web service as a set of endpoints operating on messages. The operations and messages are described abstractly and then bound to a concrete network protocol and message format to define an endpoint.
  16. Universal Description Discovery and Integration (UDDI) is an XML registry that provides standard mechanisms for businesses to describe and publish their services, discover other businesses and integrate with them.
  17. SMTP (Simple Mail Transfer Protocol) is a TCP/IP protocol used in sending and receiving e-mail.
  18. XML (Extensible Markup Language) is a W3C initiative that allows information and services to be encoded with meaningful structure and semantics.

Tuesday, January 22, 2013

Configure Claws Mail in ubuntu

For Configure Claws Mail client in Ubuntu, first you need to provide your POP3 and SMTP credential and your mail server detail to client:
 1. Configuration->Create New Account / Edit Account Option:
 2. Basic Configuration : View on Screen Shoot:




3. Send Configuration: View on Screen Shoot:
4. SSL Configuration: View on Screen Shoot:

5. Advance Configuration: View on Screen Shoot:


Not: If you found any error on out bound mail, related to SMTP, something like TLS not available after start. Please check your SMTP setting as provided upper. 

Enjoy your Claws mail client.






Friday, January 18, 2013

DNS Lookup Error in google chrom browser in linux


1. click on terminal 2. sudo nano /etc/resolv.conf 3. add following DNS entries into file (free google dns server) nameserver 208.67.222.222 nameserver 208.67.220.220 nameserver 202.51.5.52 4. sudo /etc/init.d/resolvconf restart 5. restart chrom browser. 6. check proxy setting. proxy should be disable / enabled according to your network setting. 7. type ping google.com Now you should be able to access internet or able to resolve DNS error. Enjoy.

Tuesday, December 25, 2012

SOAP Web-Service via .netBean

Step 1: Create a normal Java Web Project in .netBean IDE. Step 2: Select project node and right click and select web service. Step 3: Once a web service via design mode. Add operation via design mode, also add input parameter and output parameters and exceptions in web service .
Step 4: add required business logic in newly added operation. Step 5: Compile Project and Deploy into server and test it via wsdl file.

Thursday, October 11, 2012



Yet Waiting for USCIS decison...........am not sure, how long USCIS wants me to wait for this case ?????

सोच लो तो क्या मुस्किल है, मुस्किल है नामुनकिन नहीं.


Wednesday, September 26, 2012

Set JAVA_HOME / PATH

Login to your account and open .bash_profile file

$ vi ~/.bash_profile

et JAVA_HOME as follows using syntax export JAVA_HOME=<path-to-java>. If your path is set to /usr/java/jdk1.5.0_07/bin/java, set it as follows:

export JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java

Set PATH as follows:

export PATH=$PATH:/usr/java/jdk1.5.0_07/bin


$ source ~/.bash_profile

Monday, September 24, 2012

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)


A frequent error message received when using the mysql command line utility is: Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ While this error message can be frustrating, the solution is simple.


When connecting to a MySQL server located on the local system, the mysql client connects thorugh a local file called a socket instead of connecting to the localhost loopback address 127.0.0.1. For the mysql client, the default location of this socket file is /tmp/mysql.sock. However, for a variety of reasons, many MySQL installations place this socket file somewhere else like /var/lib/mysql/mysql.sock.
While it is possible to make this work by specifying the socket file directly in the mysql client command
mysql --socket=/var/lib/mysql/mysql.sock ...
it is painful to type this in every time. If you must do so this way (because you don’t have permissions to the file in the solution below), you could create an alias in your shell to make this work (like alias mysql=”mysql –socket=/var/lib/mysql/mysql.sock” depending on your shell).
To make your life easier, you can make a simple change to the MySQL configuration file /etc/my.cnf that will permanently set the socket file used by the mysql client. After making a backup copy of /etc/my.cnf, open it in your favorite editor. The file is divided into sections such as
[mysqld] datadir=/usr/local/mysql/data
socket=/var/lib/mysql/mysql.sock


[mysql.server] user=mysql
basedir=/usr/local/mysql

If there is not currently a section called [client], add one at the bottom of the file and copy the socket= line under the [mysqld] section such as:
[client] socket=/var/lib/mysql/mysql.sock
If there is already a [client] section in the my.cnf file, add or edit the socket line as appropriate. You won’t need to restart your server or any other processes. Subsequent uses of the mysql client will use the proper socket file.