0% found this document useful (0 votes)
33 views

Static String

String is a sequence of characters that can be created using string literals or the new keyword. There are various string methods like length() that return the number of characters. Static methods can be called directly by the class name without creating an object, while instance methods require an object to be created first before calling them. The main method in Java is static so that the program can be run without needing to create an object, which would require unnecessary memory allocation.

Uploaded by

sanjeev kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Static String

String is a sequence of characters that can be created using string literals or the new keyword. There are various string methods like length() that return the number of characters. Static methods can be called directly by the class name without creating an object, while instance methods require an object to be created first before calling them. The main method in Java is static so that the program can be run without needing to create an object, which would require unnecessary memory allocation.

Uploaded by

sanjeev kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Java – String Class

String is a sequence of characters,

for e.g. “Hello” is a string of 5 characters.

Creating a String

There are two ways to create a String in Java

1. String literal

2. Using new keyword

String literal

String str1 = "Welcome";


String str2 = "Welcome";
Using New Keyword

String str1 = new String("Welcome");


String str2 = new String("Welcome");

String Methods

String Length

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


System.out.println("The length of the txt string is: " + txt.length());
Java – static keyword
OUTPUT
Obj1-----2
Obj2-----2
Java Static Method vs Instance Method

Instance Methods
Methods that require an object of its class to be created before calling it
is called as Instance methods.
To invoke a instance method, we have to create an Object of the class
in within which it defined.

Static Methods

Static methods do not depend on the need to create object of a


class. You can refer them by the class name itself or meaning you
refer object of the class.
Why is the Java main method static?
It is because the object is not required to call a static method. If it were
a non-static method, JVM creates an object first then call main()
method that will lead the problem of extra memory allocation.

You might also like