java
Introduction:-
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995.
features:-Object Oriented, Platform independent, Secure, etc.
installation and setting java path:-
1. install jdk.
2. set java path in environment variable path to
C:\Program Files\Java\jdk1.6.0_32\bin;.
Java class and Objects
Java Class:-
Class is a template for creating objects which defines its state and behavior. And class contains field and method to define the state and behavior of its object. i.e. A class is a prototype that defines the variables and the methods common to all objects of a certain kind.
Java Objects:-
Object is a bundle of related variables and functions (also known methods).Objects share two characteristics: They have State and Behavior.
How to Create an Object of Class:-
An object is an instance of a class created using a "new" operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
Syntax: <Class_Name> obj = new <Class_Name>();
How to Access Member of a Class
You call a method of an object by naming the object followed by a period (dot), this should be followed by the name of the method and its argument list.
obj.methodName(arg1, arg2, arg3).
Note:-
1. You cannot call non-static methods from inside a static method.
2. The Object Class is the super class for all classes in Java
OOPS Concept
1.Abstraction
2.Encapsulation
3.Polymorphism
4.Inheritance
Abstraction:-The purpose of abstraction is to hide information that is not relevant or rather show only relevant information and to simplify it by comparing it to something similar in the real world.
Abstraction means “The process of forming of general and relevant concept from more complex scenarios”.
Encapsulation:-Wrapping of data in a single logical unit. and purpose of encapsulation is “Information Hiding”.
for example Objects encapsulate data and implementation details, To the outside world.
How to bring in Encapsulation:-
1) Make the instance variables private.
2) Create public getter and setter.
Example for encapsulation
class EmployeeCount
{
private int NoOfEmployees = 0;
public void setNoOfEmployees (int count)
{
NoOfEmployees = count;
}
public double getNoOfEmployees ()
{
return NoOfEmployees;
}
}
class Encapsulation
{
public static void main(String args[])
{
System.out.println("Starting EmployeeCount...");
EmployeeCount employeeCount = new EmployeeCount ();
employeeCount. setNoOfEmployees (12003);
System.out.println("NoOfEmployees = " + employeeCount. getNoOfEmployees ());
}
}
Inheritance:-
The process by which one class acquires the properties and functionalities of another class.
1. Inheritance is a mechanism of defining a new class based on an existing class.
2. Inheritance enables reuse of code. Inheritance also provides scope for refinement of the existing class. Inheritance helps in specialization
3. The existing (or original) class is called the base class or super class or parent class. The new class which inherits from the base class is called the derived class or sub class or child class.
4. Inheritance implements the “Is-A” or “Kind Of/ Has-A” relationship.
Note : The biggest advantage of Inheritance is that, code in base class need not be rewritten in the derived class.
Inheritance Example
Consider below two classes –
class Teacher {
private String name;
private double salary;
private String subject;
public Teacher (String tname) {
name = tname;
}
public String getName() {
return name;
}
private double getSalary() {
return salary;
}
private String getSubject() {
return subject;
}
}
class OfficeStaff{
private String name;
private double salary;
private String dept;
public OfficeStaff (String sname) {
name = sname;
}
public String getName() {
return name;
}
private double getSalary() {
return salary;
}
private String getDept () {
return dept;
}
}
Points:-
1) Both the classes share few common properties and methods. Thus repetition of code.
2) Creating a class which contains the common methods and properties.
3) The classes Teacher and OfficeStaff can inherit the all the common properties and methods from below Employee class
Note:- Multi-level inheritance is allowed in Java but not multiple inheritance.
class Employee{
private String name;
private double salary;
public Employee(String ename){
name=ename;
}
public String getName(){
return name;
}
private double getSalary(){
return salary;
}
}
Polymorphism:-
Polymorphism is a feature that allows one interface to be used for a general class of actions. It’s an operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. It plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance.
Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:-
Function Overloading – within same class more than one method having same name but differing in signature.
Resolved during compilation time.
Return type is not part of method signature.
Dynamic Polymorphism:-
Function Overriding – keeping the signature and return type same, method in the base class is redefined in the derived class.
Resolved during run time.
Which method to be invoked is decided by the object that the reference points to and not by the type of the reference.
Access Specifiers :-
1)public: Accessible to all. Other objects can also access this member variable or function.
2)private: Not accessible by other objects. Private members can be accessed only by the methods in the same class. Object accessible only in Class in which they are declared.
3)protected: The scope of a protected variable is within the class which declares it and in the class which inherits from the class (Scope is Class and subclass)
4)Default: Scope is Package Level
Java Language Keywords:-
Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while
Java Naming Conventions:-
Packages: -
Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
package pokeranalyzer
package mycalculator
In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:
package com.mycompany.utilities
package org.bobscompany.application.userinterface
Classes:-
Names should be in CamelCase.
Try to use nouns because a class is normally representing something in the real world:
class Customer
class Account
Interfaces: Names should be in CamelCase.
They tend to have a name that describes an operation that a class can do:
interface Comparable
interface Enumerable
Note that some programmers like to distinguish interfaces by beginning the name with an "I":
interface IComparable
interface IEnumerable
Methods:
Names should be in mixed case.
Use verbs to describe what the method does:
void calculateTax()
string getSurname()
Variables: Names should be in mixed case.
The names should represent what the value of the variable represents:
string firstName
int orderNumberOnly
use very short names when the variables are short lived, such as in for loops:
for (int i=0; i<20;i++) { //i only lives in here }
Constants: Names should be in uppercase.
static final int DEFAULT_WIDTH
static final int MAX_HEIGHT
Variables
In Java, objects store their states in variables. Variables are used as containers to hold values (int, long, string . . .) during the life cycle of an application.
Global Variables
a) The variables that are declared outside any function body.
b) These variables exist for the entire life-cycle of the program.
c) Global variables can be accessed from anywhere within the program.
Local Variables
a) The variables that are declared within a function body.
b) Their scope is limited to within the function body.
c) Local variables cannot be accessed outside the function body.
Valid Variable Name :-
Variable:-
1. Variable names are case-sensitive.
2. A variable’s name can be any legal identifier.
3. It can contain Unicode letter,Digits and Two Special Characters such as Underscore and dollar Sign.
4. Length of Variable name can be any number.
5. Its necessary to use Alphabet at the start (however we can use underscore , but do not use it )
6. Some auto generated variables may contain ‘$‘ sign. But try to avoid using Dollar Sign.
7. White space is not permitted.
8. Special Characters are not allowed.
9. Digit at start is not allowed.
10. Subsequent characters may be letters, digits, dollar signs, or underscore characters.
11. Variable name must not be a keyword or reserved word.
Constructor:-
1)A method with the same name as class name used for the purpose of creating an object in a valid state
2) It does not return a value not even void
3) A class contains one or more constructors for making new objects of that class
4) If (and only if) the programmer does not write a constructor, Java provides a default constructor with no arguments.
Note:-
When a constructor executes, before executing its own code:
It implicitly call the default constructor of it’s super class Or can make this constructor call explicitly, with super(…);
A constructor for a class can call another constructor for the same class by putting this(…); as the first thing in the constructor. This allows you to avoid repeating code.
A Class do not inherit the constructors of a super class.
Data Types in Java:-
Primitive Data Types:-
Abstract class and interface:-
Abstract method 1) A method that is declared but not defined 2) Declared with the keyword abstract 3) Example :
abstract public void playInstrument();
The following cannot be marked with “abstract” modifier:-
Constructors, Static methods ,Private methods, and Methods marked with “final” modifier.
A class that is declared using “abstract” keyword is known as abstract class. It may or may not include abstract methods which means in abstract class but if any method is abstract than class must be abstract.
An abstract class can not be instantiated (you are not allowed to create object of Abstract class).
Remember two rules:
1) If the class is having few abstract methods and few concrete methods: declare it as abstract class.
2) If the class is having only abstract methods: declare it as interface.
With the help of interface abstraction we can get 100% abstraction.
Key points: Here are the key points to remember about interfaces:-
1)We can’t instantiate an interface in java.
2) Interface provides complete abstraction as none of its methods can have body. On the other hand, abstract class provides partial abstraction as it can have abstract and concrete(methods with body) methods both.
3) implements keyword is used by classes to implement an interface.
4Class implementing any interface must implement all the methods, otherwise the class should be declared as “abstract”.
5) Interface cannot be declared as private, protected or transient.
6) All the interface methods are by default abstract and public.
7) Variables declared in interface are public, static and final by default.
9) Interface variables must be initialized at the time of declaration otherwise compiler will through an error.
interface Try
{
int x;//Compile-time error
}
10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are public, static and final. Here we are implementing the interface “Try” which has a variable x. When we tried to set the value for variable x we got compilation error as the variable x is public static final by default and final variables can not be re-initialized.
Class Sample implements Try
{
public static void main(String arg[])
{
x=20; //compile time error
}
}
11) Any interface can extend any other interface but cannot implement it. Class implements interface and interface extends interface.
12) A class can implements any number of interfaces.
13) If there are having two or more same methods in two interfaces and a class implements both interfaces, implementation of one method is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String arg[])
{
//Statements
}
}
14) Methods with same signature but different return type can’t be implemented at a time for two or more interfaces.
interface A
{
public void aaa();
}
interface B
{
public int aaa();
}
class Central implements A,B
{
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String arg[])
{
}
}
15) Variable names conflicts can be resolved by interface name e.g:
interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implement A,B
{
public static void Main(String arg[])
{
System.out.println(x); // reference to x is ambiguous both variables are x
System.out.println(A.x);
System.out.println(B.x);
}
}
static:-
The static keyword in java is used for memory management mainly. it is Used to attach Variable / Method to class. Variable and Method marked static belong to the class rather than to any particular instance.
Static keyword can be applied on:-
1. Method
2. Variable
3. Class nested within another Class
4. Initialization Block
Static keyword can not be applied to:-
1. Class (Not Nested)
2. Constructor
3. Interfaces
4. Method Local Inner Class(Difference then nested class)
5. Inner Class methods
6. Local Variables
Static Keyword Rules:-
1. Variable / Methods marked static belong to the Class rather then to any particular Instance.
2. Static method/variables can be used without creating any instance of the class.
3. If there are instances, a static variable of a class will be shared by all instances of that class, there will be only one copy.
4. A static method can’t access non static variable and also it can not directly invoke non static method (But it can invoke/access method/variable via instances).
Static class example:-
package com.core.concepts;
public class StaticClassTest1 {
static class X{
static String str="Inside Class X";
}
public static void main(String args[])
{
X.str="Inside Class Example1";
System.out.println("String stored in str is- "+ X.str);
}
}
Static block example:-
package com.core.concepts;
public class StaticBlockTest {
static int num;
static String mystr;
static{
num = 97;
mystr = "Static keyword in Java";
}
public static void main(String args[])
{
System.out.println("Value of num="+num);
System.out.println("Value of mystr="+mystr);
}
}
static imports :-
Static imports are used to save your time and typing. If you hate to type same thing again and again then you may find such imports interesting.
class Demo1{
public static void main(String args[])
{
double var1= Math.sqrt(5.0);
double var2= Math.tan(30);
System.out.println("Square of 5 is:"+ var1);
System.out.println("Tan of 30 is:"+ var2);
}
}
import static java.lang.System.out;
import static java.lang.Math.*;
class Demo2{
public static void main(String args[])
{
//instead of Math.sqrt need to use only sqrt
double var1= sqrt(5.0);
//instead of Math.tan need to use only tan
double var2= tan(30);
//need not to use System in both the below statements
out.println("Square of 5 is:"+var1);
out.println("Tan of 30 is:"+var2);
}
}
Note:- but not recommended to use static import.
this:-
this is a reference variable that refers to the current object.
Usage of java this keyword:-
Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.
super:-
The super keyword in java is a reference variable that is used to refer immediate parent class object.
Usage of java super Keyword:-
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
Note:-in case of calling parent class constructor it should be first statement but in case of calling parent class method it may be any place of line.
final:-
The final keyword in java is used to restrict the user . the java final keyword can be used in many context.
1. variable
2. method
3. class
Note:-
1. stop value change.
2. stop method overriding.
3. stop inheritance.
Note:-constructor can not declare final because constructor is never inherited.
Overloading in Java:-
“Method Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different.”
Argument lists could differ in –
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.
Note :-
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.
Overriding in java:-
“Declaring a method in subclass which is already present in parent class is known as method overriding.”
Rules of method overriding in Java
1. Argument list: The argument list of overriding method must be same as that of the method in parent class. The data types of the arguments and their sequence should be maintained as it is in the overriding method.
2. Access Modifier: The Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.
3. private and final methods cannot be overridden as they are local to the class.
4. Return type must be the same as, or subtype of the return type declared in overriden method in Super class.
Array:-
Java array is an object the contains elements of similar data type. An array is used to store a collection of data.
Creating an array:-
1D Array:-
dataType[] oneDArray = new dataType[arraySize];
2D Array:-
dataType[][] twoDArray = new dataType[row][col];
String :-
String is an immutable object and sequence of characters which means it is constant and can cannot be changed once it has been created.
There are two ways to create a String in Java:-
1. String literal
2. Using new keyword
e.g:- String s=“Arvind”;
String s=new String(“Arvind”);
Some important methods:-
1.char charAt(int index):-returns char value for the particular index
2.int length():-returns string length
3.String substring(int beginIndex):-returns substring for given begin index
4.String substring(int beginIndex, int endIndex):-returns substring for given begin index and end index
5.boolean contains(CharSequence s):-returns true or false after matching the sequence of char value
6.boolean equals(Object another):-checks the equality of string with object
7.String replace(CharSequence old, CharSequence new):-replaces all occurrences of specified CharSequence
8.String trim():-returns trimmed string omitting leading and trailing spaces
9.String split(String regex):-returns splitted string matching regex
10.String intern():-returns interned string from String pool
11.int indexOf(int ch):-returns specified char value index
12.int indexOf(String substring):-returns specified substring index
13.String toLowerCase():-returns string in lowercase.
14.String toUpperCase():-returns string in uppercase.
Etc.
Tricky point (1) : -
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
There is a slight difference between these methods:
1. valueOf returns new instance of java.lang.Integer
2. parseInt returns primitive int.
The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong etc.
StringBuffer and StringBuilder:-
Java StringBuffer class is used to created mutable (modifiable) string.A string that can be modified or changed is known as mutable string.
StringBuffer sb=new StringBuffer("Arvind");
The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
StringBuilder sb=new StringBuilder("Arvind");
Note:-
1)StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2)StringBuffer is less efficient than StringBuilder.
StringBuilder is more efficient than StringBuffer.
StringTokenizer:-
In java, there is a way to break up a line of text into smaller piece of a string,what are called tokens. This method of breaking up tokens are come from the StringTokenizer class.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
EXCEPTIONS:-
Exceptions are actually a really good and interesting thing to learn development and they will make your code better and effective in different scenarios.
Now we understand 3 thing about Exceptions:-
What is exception ?
When it comes? And
How we handle it ?
What is Exception:-
“Abnormal termination of program execution is An Exception”.
When an error occurs within a method then this method creates an exception object and handing it to the runtime system is called throwing an exception.
This exception object contains information about the error, including its type and the state of the program when the error occurred.
After throwing an exception, the runtime system attempts to find exception handler block. And this search begins with the method in which the error occurred and proceeds through the call stack (List of methods )in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler.
When Exception comes:-
It may be many reasons behind that:-
1. java.lang.ArithmeticException: / by zero = such as divide-by-zero.
2. ArrayIndexOutOfBoundsException = Array index is out-of-bounds.
3. ClassCastException == Invalid cast.
4. java.lang.NullPointerException == need to check NullPointerException every where in case of object is null,object.method1().method2() is null
5. Java.lang.NumberFormatException == For input string: "null" or for string value with character values
6. ClassNotFoundException = first need to clean you java project then see (may be your .class file not found at run time or some times your changes not reflecting)
7. java.lang.IllegalStateException == go to the infinite loop
8. SocketTimeoutException === (e.g. previously in hellotv if epg down then our portal become down but now there is no effect on epg response)
9. NoSuchMethodException ==A requested method does not exist.
And so on.
example:-
package com.arvind;
public class ExceptionEX1 {
public static void main(String[] args) {
int n1=0;
int n2=12;
/*
System.out.println(n2/n1);
System.out.println("rest of the code...");
*/
//==========solution==========
try{
int data=n2/n1;
System.out.println(data);
}catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Types:-
1)checked exception (recoverable) (Compile Time Exceptions) :-
e.g. io exception,sql exception
2)Unchecked exception (Runtime Exceptions):-
(a)error (can not be recover) :-
e.g. hardware or system failure.
(b)runtime exception (recoverable):-
e.g. java.lang.NullPointerException, java.lang.IllegalStateException, java.lang.NumberFormatException
Exception keyword:-
There are 5 keywords used in java exception handling:-
1) try
2) catch
3) finally
4) throw
5) Throws
try {
//exception prone area
} catch (ExceptionType name) {
//exception handler block1
} catch (ExceptionType name) {
//exception handler block2
} finally {
//always executed after handler block
}
throw keyword:-
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception.
Note:- Unchecked Exception Only
package com.arvind;
public class ExceptionEX4 {
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
} }
throws keyword:-The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Note:-
1)checked exception only
2)If you are calling a method that declares an exception, you must either caught or declare the exception.
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
} }
public class ExceptionEX5{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Custom Exception:-
If you are creating your own Exception that is known as custom exception or user-defined exception.
To create a custom checked exception, we have to sub-class from the java.lang.Exception class.
Syntax:-
public class CustomException extends Exception{
}
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
=======================
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
String :---------
Tricky point (1) : -
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
There is a slight difference between these methods:
valueOf returns new instance of java.lang.Integer
parseInt returns primitive int.
The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong etc.
Tricky point (2) : -
Why is char[] preferred over String for passwords?
1) Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since Strings are used in String pool for re-usability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text
2) Java recommendation using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason.
3) toString() there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed.
String strPwd ="passwd";
char[] charPwd = new char[]{'p','a','s','s','w','d'};
System.out.println("String password: " + strPwd );
System.out.println("Character password: " + charPwd );
String password: Unknown Character password: [C@110b2345
Final thoughts: Though using char[] is not just enough you need to erase content to be more secure. I also suggest working with hash'd or encrypted password instead of plaintext and clearing it from memory as soon as authentication is completed.
How to generate a random alpha-numeric string?
Starting with Java 5, the UUID class provides a simple means for generating unique ids.
public final class UUID
extends Object
implements Serializable, Comparable<UUID>
A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value.
StringBuilder vs String concatenation in toString() in Java
ques :-Given the 2 toString() implementations below, which is prefered
or
Why using StringBuilder explicitly if the compiler converts string concatenation to a StringBuilder automatically?
public String toString(){
return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
or
public String toString(){
StringBuilder sb = new StringBuilder(100);
return sb.append("{a:").append(a)
.append(", b:").append(b)
.append(", c:").append(c)
.append("}")
.toString();
}
----------------------------------------------------------
ans.
Because StringBuilder can "append" a string instead of concatenating two strings each time creating a new object. Even if you use += operator with Strings a new object is created. This advantage will only become relevant once you try to concatenate a great number of strings.
StringBuilder does not create new Strings in the pool on operations such as concatenation, substring e.t.c. In short, every time u make an operation on String, a new String is created in the pool.
String x = "abc"
x= x+"def";
so three strings have been created in the pool. "abc", "def". "abcdef".....where as same task would have been achieved by StringBUilder while using only one object.
StringBuilder is recommended over StringBuffer, because StringBuffer is thread safe and have synchronized methods, so until or unless thread safe is required, stringbuilder is recommended as string buffer might cause performance overhead, although negligible.
...
String result = "";
for (String s : hugeArray) {
result = result + s;
}
is very time- and memory-wasteful compared with:
...
StringBuilder sb = new StringBuilder();
for (String s : hugeArray) {
sb.append(s);
}
String result = sb.toString();
Java string to date conversion
To deal with date manipulation we use Date, Calendar, GregorianCalendar, and SimpleDateFormat.
String Memory allocation with constant pool
For example
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
enter image description here
No comments:
Post a Comment