Problem Definition:- Write a Java code to reverse any string. String should be input from the user at the runtime. Write different class for the business logic of reversing a string.
P.S. Here, Eclipse Ganymede is used for coding. And, Exception Handling and entering false strings are not covered this source code. This source code is meant for beginners of Java.
Solution:-
Step 1: Class names :
- MainClass.java - This class contains main() method from where method of reversing a string, which is defined in another class, is called.
- ReverseStringLogic.java - This class contains reverseString() method which contains business logic for reversing a string and its display.
Step 2: Variable declarations in each class :
- In MainClass.java, following variables are required.
- readString with data type as String and initialised to null .
String readString = null;
- In ReverseStringLogic.java, following are the variables which will be used.
1. lengthOfStringToReverse with data type as int, initialised to 0 (zero). Purpose of this variable is to store length of string.
int lengthOfStringToReverse = 0;
2. counter with data type as int, initialised to zero. It is just a counter variable to iterate through for loop.
int counter = 0;
Step 3: Now, the actual code
1. In above source code, there is one class named MainClass. In java, name of the class and name of the file must be same.
2. Inside MainClass, object named "reverse" is created and invoked using new keyword. This object is created of class ReverseStringLogic class , for calling reverseString() method from the ReverseStringLogic class.
3. In java, to read any text entered during run time, an object of Scanner class needs to be used. Here, scanLine is an object of Scanner class.
4. System.out.println() is used to display text , which will make it easier for any layman user to enter any appropriate text. Here, System is a java class that provides access to the system, out is an output stream that is connected to console, and println() is a method which displays any text that is written inside it, on console.
5. Using scanLine.next(), input that is entered during run time, is captured and stored in appropriate variable. Here, that variable is readString.
6. Using object of ReverseStringLogic class, "reverse", method reverseString() is called. This method takes argument as readString of type String. Here, string entered during run time is stored in readString variable and is passed through argument in method reverseString().
1. In above snapshot, ReverseStringLogic class is shown which contains reverseString() method, which contains one argument, stringToReverse of type String. As length() method is used for variables of data type String, we need to import package java.lang.String. Here , java.lang is a package, and String is a class.
2. length() method is used to calculate length of any string and length of string is stored in variable lengthOfStringToReverse, which is used in "for" loop while iteration.
3. "for" loop is used to iterate through the string with its variable as counter initialised to length of string i.e. lengthOfStringToReverse minus 1. "Minus 1" is done because in java, if string contains 8 characters then the range of storing these characters is from 0 to 7. Condition given as "counter >=0", as we have to reverse the string and finally, we have post decremented the counter by 1 "counter--".
4. Inside "for" loop, charAt() method is used, which contains one argument of type integer. charAt() method takes the character present at particular location. In above code, if value of counter variable is 5 then, it will take character present at 5th location from original string and is displayed using System.out.println(). The above for loop will run those many times depending on length of the string i.e. if length of string is 8 then for loop will run 8 times. Following is the ouput of the above source code.
:..Basic Elements Of Java..:
Like any other programming language, the Java programming language is defined by grammar rules that specify how syntactically legal constructs can be formed using the language elements, and by a semantic definition that specifies the meaning of syntactically legal constructs.
:..Lexical Tokens..:
The low-level language elements are called lexical tokens (or just tokens for short) and are the building blocks for more complex constructs. Identifiers, numbers, operators, and special characters are all examples of tokens that can be used to build high-level constructs like expressions, statements, methods, and classes.
:..Identifiers..:
A name in a program is called an identifier. Identifiers can be used to denote classes, methods, variables, and labels.In Java an identifier is composed of a sequence of characters, where each character can be either a letter, a digit, a connecting punctuation (such as underscore _), or any currency symbol (such as $, ¢, ¥, or £). However, the first character in an identifier cannot be a digit. Since Java programs are written in the Unicode character set (see p. 23), the definitions of letter and digit are interpreted according to this character set.
Identifiers in Java are case sensitive, for example, price and Price are two different identifiers.
Examples of Legal Identifiers:
number, Number, sum_$, bingo, $$_100, mål, grüß
Examples of Illegal Identifiers:
48chevy, all@hands, grand-sum
The name 48chevy is not a legal identifier as it starts with a digit. The character @ is not a legal character in an identifier. It is also not a legal operator so that all@hands cannot not be interpreted as a legal expression with two operands. The character - is also not a legal character in an identifier. However, it is a legal operator so grand-sum could be interpreted as a legal expression with two operands.
:..Keywords..:
Keywords are reserved identifiers that are predefined in the language and cannot be used to denote other entities. All the keywords are in lowercase, and incorrect usage results in compilation errors.
Keywords currently defined in the language are listed in Table (a). In addition, three identifiers are reserved as predefined literals in the language: the null reference and the Boolean literals true and false (see Table (b)). Keywords currently reserved, but not in use, are listed in Table (a). All these reserved words cannot be used as identifiers. The index contains references to relevant sections where currently defined keywords are explained.
Table (a) Keywords In Java
Table (b) Reserved Literals in Java
Table (c) Reserved Keywords not Currently in Use
:..Literals..:
A literal denotes a constant value, that is, the value a literal represents remains unchanged in the program. Literals represent numerical (integer or floating-point), character, boolean or string values. In addition, there is the literal null that represents the null reference.
Table (d) Examples of Literals
:..Integer Literals..:
Integer data types are comprised of the following primitive data types: int, long, byte, and short .
The default data type of an integer literal is always int, but it can be specified as long by appending the suffix L (or l) to the integer value. Without the suffix, the long literals 2000L and 0l will be interpreted as int literals. There is no direct way to specify a short or a byte literal.
In addition to the decimal number system, integer literals can also be specified in octal (base 8) and hexadecimal (base 16) number systems. Octal and hexadecimal numbers are specified with 0 and 0x (or 0X) prefix respectively. Examples of decimal, octal and hexadecimal literals are shown in Table (e). Note that the leading 0 (zero) digit is not the uppercase letter O. The hexadecimal digits from a to f can also be specified with the corresponding uppercase forms (A to F). Negative integers (e.g. -90) can be specified by prefixing the minus sign (-) to the magnitude of the integer regardless of number system (e.g., -0132 or -0X5A). Number systems and number representation. Java does not support literals in binary notation.
Table (e) Examples of Decimal, Octal, and Hexadecimal Literals
:..Floating-point Literals..:
Floating-point data types come in two flavors: float or double.The default data type of a floating-point literal is double, but it can be explicitly designated by appending the suffix D (or d) to the value. A floating-point literal can also be specified to be a float by appending the suffix F (or f).
Floating-point literals can also be specified in scientific notation, where E (or e) stands for Exponent. For example, the double literal 194.9E-2 in scientific notation is interpreted as 194.9*10-2 (i.e., 1.949).
Examples of double Literals
0.0 0.0d 0D
0.49 .49 .49D
49.0 49. 49D
4.9E+1 4.9E+1D 4.9e1d 4900e-2 .49E2
Examples of float Literals
0.0F 0f
0.49F .49F
49.0F 49.F 49F
4.9E+1F 4900e-2f .49E2F
Note that the decimal point and the exponent are optional and that at least one digit must be specified.
Boolean Literals
The primitive data type boolean represents the truth-values true or false that are denoted by the reserved literals true or false, respectively.
:..Character Literals..:
A character literal is quoted in single-quotes ('). All character literals have the primitive data type char.
Characters in Java are represented by the 16-bit Unicode character set, which subsumes the 8-bit ISO-Latin-1 and the 7-bit ASCII characters. In Table (f), note that digits (0 to 9), upper-case letters (A to Z), and lower-case letters (a to z) have contiguous Unicode values. Any Unicode character can be specified as a four-digit hexadecimal number (i.e., 16 bits) with the prefix \u.
:..Escape Sequences..:
Certain escape sequences define special character values. These escape sequences can be single-quoted to define character literals. For example, the character literals '\t' and '\u0009' are equivalent. However, the character literals '\u000a' and '\u000d' should not be used to represent newline and carriage return in the source code. These values are interpreted as line-terminator characters by the compiler, and will cause compile time errors. One should use the escape sequences '\n' and '\r', respectively, for correct interpretation of these characters in the source code.
We can also use the escape sequence \ddd to specify a character literal by octal value, where each digit d can be any octal digit (0–7), as shown in Table (h). The number of digits must be three or fewer, and the octal value cannot exceed \377, that is, only the first 256 characters can be specified with this notation.
:..String Literals..:
A string literal is a sequence of characters, which must be quoted in quotation marks and which must occur on a single line. All string literal are objects of the class String.
Escape sequences as well as Unicode values can appear in string literals:
"Here comes a tab.\t And here comes another one\u0009! (1)"What's on the menu?" (2)"\"String literals are double-quoted.\"" (3)"Left!\nRight!" (4)
In (1), the tab character is specified using the escape sequence and the Unicode value respectively. In (2), the single apostrophe need not be escaped in strings, but it would be if specified as a character literal('\''). In (3), the double apostrophes in the string must be escaped. In (4), we use the escape sequence \n to insert a newline. Printing these strings would give the following result:
Here comes a tab. And here comes another one !What's on the menu?"String literals are double-quoted."Left!Right!
One should also use the string literals "\n" and "\r", respectively, for correct interpretation of the characters "\u000a" and "\u000d" in the source code.
:..White Spaces..:
A white space is a sequence of spaces, tabs, form feeds, and line terminator characters in a Java source file. Line terminators can be newline, carriage return, or carriage return-newline sequence.
A Java program is a free-format sequence of characters that is tokenized by the compiler, that is, broken into a stream of tokens for further analysis. Separators and operators help to distinguish tokens, but sometimes white space has to be inserted explicitly as separators. For example, the identifier classRoom will be interpreted as a single token, unless white space is inserted to distinguish the keyword class from the identifier Room.
White space aids not only in separating tokens, but also in formatting the program so that it is easy for humans to read. The compiler ignores the white spaces once the tokens are identified.
:..Comments..:
A program can be documented by inserting comments at relevant places. These comments are for documentation purposes and are ignored by the compiler.
Java provides three types of comments to document a program:
- A single-line comment: // ... to the end of the line
- A multiple-line comment: /* ... */
- A documentation (Javadoc) comment: /** ... */
Single-line Comment
All characters after the comment-start sequence // through to the end of the line constitute a single-line comment.
pre>// This comment ends at the end of this line.
int age; // From comment-start sequence to the end of the line is a comment.
Multiple-line Comment
A multiple-line comment, as the name suggests, can span several lines. Such a comment starts with /* and ends with */.
/* A commenton severallines.*/
The comment-start sequences (//, /*, /**) are not treated differently from other characters when occurring within comments, and are thus ignored. This means trying to nest multiple-line comments will result in compile time error:
/* Formula for alchemy.gold = wizard.makeGold(stone);/* But it only works on Sundays. */*/
The second occurrence of the comment-start sequence /* is ignored. The last occurrence of the sequence */ in the code is now unmatched, resulting in a syntax error.
Documentation Comment
A documentation comment is a special-purpose comment that when placed before class or class member declarations can be extracted and used by the javadoc tool to generate HTML documentation for the program. Documentation comments are usually placed in front of classes, interfaces, methods and field definitions. Groups of special tags can be used inside a documentation comment to provide more specific information. Such a comment starts with /** and ends with */:
/*** This class implements a gizmo.* @author K.A.M.* @version 2.0*/
For details on the javadoc tool, see the documentation for the tools in the Java 2 SDK.
Volatile Variable in java
Volatile variable is more useful in java. Now a days we using multithread in many
Java projects. During this we can use the volatile keyword.
Best scenario for using volatile variable:
In multiple thread concept may be single instance can be used by multiple thread .That time the volatile variable will be use for programmer...Because without volatile variable means if one thread will be changed by user it will affect by other threads also.
During this time we can mention master copy variable we mention as volatile variable..because of this other than master variable will be update value it actually update in cache memory not in main memory variable memory
Declaring a volatile variable
Class exvolatile
{
volatile int val;
.....
}
JaVa ThE pUrE oBjEcT OrIeNtEd LaNguAgE
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak” but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype. Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent (that is, architectureneutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. As you can probably guess, many different types of CPUs are used as controllers. The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target. Although it is possible to compile a C++ program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and time-consuming to create. An easier— and more cost-efficient—solution was needed. In an attempt to find such a solution, Gosling and others began work on a portable, platform-independent language that could be used to produce code that would run on a variety of CPUs under differing environments. This effort ultimately led to the creation of Java.
About the time that the details of Java were being worked out, a second, and ultimately more important, factor was emerging that would play a crucial role in the future of Java. This second force was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java was being implemented, Java might have remained a useful but obscure language for programming consumer electronics. However, with the emergence of the World Wide Web, Java was propelled to the forefront of computer language design, because the Web, too, demanded portable programs.
Most programmers learn early in their careers that portable programs are as elusive as they are desirable. While the quest for a way to create efficient, portable (platform-independent) programs is nearly as old as the discipline of programming itself, it had taken a back seat to other, more pressing problems. Further, because much of the computer world had divided itself into the three competing camps of Intel, Macintosh, and UNIX, most programmers stayed within their fortified boundaries, and the urgent need for portable code was reduced. However, with the advent of the Internet and the Web, the old problem of portability returned with a vengeance. After all, the Internet consists of a diverse, distributed universe populated with many types of computers, operating systems, and CPUs. Even though many types of platforms are attached to the Internet, users would like them all to be able to run the same program. What was once an irritating but low-priority problem had become a high-profile necessity.
By 1993, it became obvious to members of the Java design team that the problems of portability frequently encountered when creating code for embedded controllers are also found when attempting to create code for the Internet. In fact, the same problemthat Java was initially designed to solve on a small scale could also be applied to the Internet on a large scale. This realization caused the focus of Java to switch from consumer electronics to Internet programming. So, while the desire for an architectureneutral programming language provided the initial spark, the Internet ultimately led to Java’s large-scale success.
As mentioned earlier, Java derives much of its character from C and C++. This is by intent. The Java designers knew that using the familiar syntax of C and echoing the object-oriented features of C++ would make their language appealing to the legions of experienced C/C++ programmers. In addition to the surface similarities, Java shares some of the other attributes that helped make C and C++ successful. First, Java was designed, tested, and refined by real, working programmers. It is a language grounded in the needs and experiences of the people who devised it. Thus, Java is also a programmer’s language. Second, Java is cohesive and logically consistent. Third, except for those constraints imposed by the Internet environment, Java gives you, the programmer, full control. If you program well, your programs reflect it. If you program poorly, your programs reflect that, too. Put differently, Java is not a language with training wheels. It is a language for professional programmers.
Because of the similarities between Java and C++, it is tempting to think of Java as simply the “Internet version of C++.” However, to do so would be a large mistake. Java has significant practical and philosophical differences. While it is true that Java was influenced by C++, it is not an enhanced version of C++. For example, Java is neither upwardly nor downwardly compatible with C++. Of course, the similarities with C++ are significant, and if you are a C++ programmer, then you will feel right at home with Java. One other point: Java was not designed to replace C++. Java was designed to solve a certain set of problems. C++ was designed to solve a different set of problems. Both will coexist for many years to come.
As mentioned at the start of this chapter, computer languages evolve for two reasons: to adapt to changes in environment and to implement advances in the art of programming. The environmental change that prompted Java was the need for platform-independent programs destined for distribution on the Internet. However, Java also embodies changes in the way that people approach the writing of programs. Specifically, Java enhances and refines the object-oriented paradigm used by C++. Thus, Java is not a language that exists in isolation. Rather, it is part of an ongoing process begun many years ago. This fact alone is enough to ensure Java a place in computer language history. Java is to Internet programming what C was to systems programming: a revolutionary force that changed the world.
Polymorphism, Encapsulation, and Inheritance
When properly applied, polymorphism, encapsulation, and inheritance combine to produce a programming environment that supports the development of far more robust and scaleable programs than does the process-oriented model. A well-designed hierarchy of classes is the basis for reusing the code in which you have invested time and effort developing and testing. Encapsulation allows you to migrate your implementations over time without breaking the code that depends on the public interface of your classes. Polymorphism allows you to create clean, sensible, readable, and resilient code. Of the two real-world examples, the automobile more completely illustrates the power of object-oriented design. Dogs are fun to think about from an inheritance standpoint, but cars are more like programs. All drivers rely on inheritance to drive different types (subclasses) of vehicles. Whether the vehicle is a school bus, a Mercedes sedan, a Porsche, or the family minivan, drivers can all more or less find and operate the steering wheel, the brakes, and the accelerator. After a bit of gear grinding, most people can even manage the difference between a stick shift and an automatic, because they fundamentally understand their common superclass, the transmission.
People interface with encapsulated features on cars all the time. The brake and gas pedals hide an incredible array of complexity with an interface so simple you can operate them with your feet! The implementation of the engine, the style of brakes, and the size of the tires have no effect on how you interface with the class definition of the pedals.
The final attribute, polymorphism, is clearly reflected in the ability of car manufacturers to offer a wide array of options on basically the same vehicle. For example, you can get an antilock braking system or traditional brakes, power or rack-and-pinion steering, 4-, 6-, or 8-cylinder engines. Either way, you will still press the break pedal to stop, turn the steering wheel to change direction, and press the accelerator when you want to move. The same interface can be used to control a number of different implementations. As you can see, it is through the application of encapsulation, inheritance, and polymorphism that the individual parts are transformed into the object known as a car. The same is also true of computer programs. By the application of object-oriented principles, the various parts of a complex program can be brought together to for a cohesive, robust, maintainable whole.