CS535 Object-Oriented Programming & Design
Fall Semester, 1996
Basic Java Structures
[To Lecture Notes Index]
San Diego State University -- This page last updated Wednesday, 11 September, 1996
Contents of Basic Java Structures
- Reference
- Java
- Basics
- Java Resources
- First Program
- Syntax
- IO
- Basic Data Types
- Operations on Primitive Types
- NaN and Infinity
- Casting
- Default Values of Variables
- Control Structures
- Jump Statements
- Functions
- Arrays
- Arrays, References, Memory Leaks
- Strings
- Reading Command Line Arguments
Basic Java Structures Slide # 1
Core Java, Chapter 3
Basic Java Structures Slide # 2
Why is Java so "Hot"?
Multi-platform development
-
- Compiled code runs on multiple platforms
-
- Solaris, Windows 95, Windows NT, Linux/x86, OS/2, AIX, Macs
Distributed Programming
-
- Embed programs in WWW home pages ( Applets )
-
- Programs are down loaded and run locally
-
- Networking class make client-server programming easier
Standard API
- Makes GUI easier to program
Philosophical Differences with C/C++
C/C++
- C is replacement for assemble language
-
- C/C++ strive to give programmer control over machine and all performance
issues.
Java
- Distributed programming requires security
Basic Java Structures Slide # 3
C and Java
Uses C/C++ basic syntax
Uses C/C++ basic data types
- int, char, float, double, long, short, byte
"Pure" OO language
-
- No stand alone functions
-
- All code is part of a class
No explicit pointers
- Uses garbage collection
Uses standard C/C++ control structures
Java is strongly typed
Basic Java Structures Slide # 4
Newsgroups
comp.lang.java.advocacy | comp.lang.java.announce |
comp.lang.java.api | comp.lang.java.misc |
comp.lang.java.programmer | comp.lang.java.security |
comp.lang.java.setup | comp.lang.java.tech |
sdsu.java |
Web Sites (few among hundreds)
- Yahoo
- http://www.yahoo.com/Computers_and_Internet/Languages/Java/
-
- Gamelan - hundreds of examples
- http://www.gamelan.com/
Source of Java - Sun
- http://java.sun.com/
Local Copy of API
- http://www.sdsu.edu/doc/java/
Local Copy of Sun's Java Tutorial
- http://www.sdsu.edu/doc/JavaLanguageTutorial/index.html
Local Examples
- On Rohan see: /opt/java/demo
Books
- 100+ Java books are in the works
- See http://sunsite.unc.edu/javafaq/books.html
Basic Java Structures Slide # 5
class HelloWorldExample
{
public static void main( String args[] )
{
System.out.println("Hello World");
}
}
Setting Path etc. for Java
Add to your path:
- /opt/java/bin
Add CLASSPATH to your environment
- setenv CLASSPATH '.:/opt/java/classes:/opt/local/lib/java/classes.zip'
-
Compiling & Running the Program
Place code in file: FirstProgram.java
rohan 34-> ls
FirstProgram.java
rohan 35-> javac FirstProgram.java
rohan 36-> ls
FirstProgram.java HelloWorldExample.class
rohan 37-> java HelloWorldExample
Hello World
Basic Java Structures Slide # 6
Fancy Compiling
class HelloWorldExample
{
public static void main( String args[] )
{
System.out.println("Hello World");
}
}
Put the above program in a file named:
- HelloWorldExample.java
Now compile and run the program using the command:
rohan 42-> java -cs HelloWorldExample
The -cs (or -checksource) option recompiles all needed files and runs the
program
A file is recompiled if:
- it has not been compiled yet
-
- the binary file is older than the source file
Basic Java Structures Slide # 7
Real Fancy Compiling
Create a directory to hold your java source code
For this example the directory will be
- "/home/ma/whitney/java/classes"
Add the directory to your classpath
setenv CLASSPATH
'.:/opt/java/classes:/opt/local/lib/java/classes.zip:/home/ma/whitney/java/classs'
Note the above must not contain any newlines
Place the file HelloWorldExample.java in or in any subdirectory
of"~whitney/java/classes"
From any location you can compile and run the program using:
rohan 42-> java -cs HelloWorldExample
Basic Java Structures Slide # 8
Warning
When we start using packages problems can occur when you compile a main program
from in a package directory
Basic Java Structures Slide # 9
/* Standard C comment works
*/
// C++ comment works
/** Special comment for documentation
*/
class Syntax
{
public static void main( String args[] )
{
int aVariable = 5;
double aFloat = 5.8;
if ( aVariable < aFloat )
System.out.println( "True" ) ;
int b = 10;
char c;
c =
'a';
}
}
Basic Java Structures Slide # 10
Keywords
abstract | do | implements | package | throw |
boolean | double | import | private | throws |
break | else | instanceof | protected | transient |
byte | extends | int | public | try |
case | final | interface | return | void |
catch | finnally | long | short | volatile |
char | float | new | super | |
const | if | null | switch | |
continue | | | synchronized |
default | | | this |
Reserved for possible future use (not used now)
byvalue | cast | future | generic | goto |
inner | operator | outer | rest | var |
Boolean
true, false act like keywords but are boolean constants
Basic Java Structures Slide # 11
Style - Layout
class Syntax {
public static void main( String args[] ) {
int aVariable = 5;
if ( aVariable < aFloat )
System.out.println( "True" ) ;
}
}
class Syntax
{
public static void main( String args[] )
{
int aVariable = 5;
if ( aVariable < aFloat )
System.out.println( "True" ) ;
}
}
class Syntax
{
public static void main( String args[] )
{
int aVariable = 5;
if ( aVariable < aFloat )
System.out.println( "True" ) ;
}
}
Basic Java Structures Slide # 12
Style - Names
Sun API Classes use the following style:
Class names
- ClassNames
Variable and function names
- variableAndFunctionNames
Names of constants
- NAMES_OF_CONSTANTS
Basic Java Structures Slide # 13
Standard Java Output
class Output
{
public static void main( String args[] )
{
// Standard out
System.out.print( "Prints, but no linefeed " );
System.out.println( "Prints, adds linefeed at end" );
double test = 4.6;
System.out.println( test );
System.out.println( "You can use " + "the plus operator on "
+ test + " String mixed with numbers" );
System.out.println( 5 + "\t" + 7 );
System.out.flush(); // flushes output buffer
System.err.println( "Standard error output" );
}
}
Output
Prints, but no linefeed Prints, adds linefeed at end
4.6
You can use the plus operator on 4.6 String mixed with numbers
5 7
Standard error output
Basic Java Structures Slide # 14
To Avoid Typing "System" all the Time
import java.io.PrintStream;
class Output
{
public static void main( String args[] )
{
PrintStream out = System.out;
out.print( "Look Mom, No System" );
out.flush();
out.println( "Be careful with print, flush can be useful" );
out.println( "Everything you can do with System.out" +
"You can do here" );
}
}
Basic Java Structures Slide # 15
Simple Input
import sdsu.io.ASCIIInputStream;
public class Test_SDSU_io
{
public static void main(String args[]) throws Exception
{
ASCIIInputStream cin = new ASCIIInputStream(System.in);
System.out.print( "Type two integers: " );
System.out.flush();
int size = cin.readInt();
int area = cin.readInt();
System.out.println( "They were " + size + " and " + area );
System.out.print( "Type two words: " );
System.out.flush();
String firstWord = cin.readWord();
String secondWord = cin.readWord();
System.out.println( "They were " + firstWord + " and "
+ secondWord );
}
}
Some ASCIIInputStream Methods
readChar() | readWord() |
readLong() | readLine() |
readFloat() | flushLine(); |
readDouble() | |
Basic Java Structures Slide # 16
Really Simple IO
import sdsu.io.Console;
public class Test_SDSU_Console
{
public static void main( String[] args )
{
// Simple printing
Console.println( 5 );
Console.print( "Hi Mom" );
Console.println( " Hi Dad" );
Console.print( "Print an integer ");
int why = Console.readInt();
Console.println( "You typed: " + why );
int easy = Console.readInt( "Print another integer" );
Console.print( "You typed: %20i\n ", easy );
String message = Console.readLine( "Type a line of text" );
Console.println( "");
// printf like features
double x = 1.23456789012;
Console.print( "x = %f\n", x);
Console.print( "x = % .5f\n", x);
Console.print( "x = %10.8f\n", x);
}
}
Basic Java Structures Slide # 17
On-Line Documentation
Index to local documentation for Java and other systems
- http://www.sdsu.edu/doc/
Standard Java Classes - Local copy of documentation
- http://www.sdsu.edu/doc/java/index.html
SDSU Java Class library documentation
- http://www.eli.sdsu.edu/java-SDSU/index.html
Basic Java Structures Slide # 18
class PrimitiveTypes
{
public static void main( String args[] )
{
// Integral Types
byte aByteVariable; // 8-bits
short aShortVariable; // 16-bits
int aIntVariable; // 32-bits
long aLongVariable; // 64-bits
// Floating-Point Types
float aFloatVariable; // 32-bit IEEE 754 float
double aDoubleVariable; // 64-bit IEEE 754 float
// Character Type
char aCharVariable; // always 16-bit Unicode
// Boolean Types
boolean aBooleanVariable; // true or false
}
}
Integral and Floating-Point types make up arithmetic types
Basic Java Structures Slide # 19
Primitive Type Ranges
type | from | to |
byte | -128 | 127 |
short | -32,768 | 32,767 |
int | -2,147,483,648 | 2,147,483,647 |
long | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
Float Types
float values are of the form s*m*2e where
- s = 1 or -1
- 0 <= m <= 224 and m is an integer
- -149 < e < 104
-
- 1e-44 3.4e38 approximate range in decimal
-
- 7 significant decimal digits
double values are of the form s*m*2e where
- s = 1 or -1
- 0 <= m <= 253 and m is an integer
- -1045 < e < 1000
-
- 1e-314 1.8e308 approximate range in decimal
-
- 15 significant decimal digits
Basic Java Structures Slide # 20
Arithmetic Literals
class ArithmeticLiterals
{
public static void main( String args[] )
{
long aLong = 5L;
long anotherLong = 12l;
int aHex = 0x1;
int alsoHex = 0X1aF;
int anOctal = 01;
int anotherOctal = 0731;
long aLongOctal = 012L;
long aLongHex = 0xAL;
float aFloat = 5.40F;
float alsoAFloat = 5.40f;
float anotherFloat = 5.40e2f;
float yetAnotherFloat = 5.40e+12f;
double aDouble = 5.40;
double alsoADouble = 5.40d;
double moreDouble = 5.40D;
double anotherDouble = 5.40e2;
double yetAnotherDouble = 5.40e+12d;
}
}
Basic Java Structures Slide # 21
Integral Types
Equality | = != |
Relational | < <= > >= |
Unary | + - |
Arithmetic | + - * / % |
Pre, postfix increment/decrement | ++ -- |
Shift | << >> >>> |
Unary Bitwise logical negation | ~ |
Binary Bitwise logical operators | & | ^ |
class Operations
{
public static void main( String args[] )
{
int a = 2;
int b = +4;
int c = a + b;
if ( b > a )
System.out.println("b is larger");
else
System.out.println("a is larger");
System.out.println( a << 1); // Shift left: 4
System.out.println( a >> 1); // Shift right: 1
System.out.println( ~a ); // bitwise negation: -3
System.out.println( a | b); // bitwise OR: 6
System.out.println( a ^ b); // bitwise XOR: 6
System.out.println( a & b); // bitwise AND: 0
}
}
Basic Java Structures Slide # 22
Floating-Point Types
Operations
Equality | = != |
Relational | < <= > >= |
Unary | + - |
Arithmetic | + - * / % |
Pre, postfix increment/decrement | ++ -- |
NaN, +[[infinity]], -[[infinity]]
Zero divide with floating-point results in +[[infinity]], -[[infinity]]
Overflow results in either +[[infinity]], -[[infinity]].
Underflow results in zero.
An operation that has no mathematically definite result produces NaN - Not a
Number
NaN is not equal to any number, including another NaN
class NaN
{
public static void main( String args[] )
{
float size = 0;
float average = 10 / size;
float infinity = 1.40e38f * 1.40e38f;
System.out.println( average ); // Prints Inf
System.out.println( infinity ); // Prints Inf
}
}
Basic Java Structures Slide # 23
class Compare
{
public static void main( String args[] )
{
float nan = Float.NaN;
float positiveInfinity = Float.POSITIVE_INFINITY;
float negativeInfinity = Float.NEGATIVE_INFINITY;
// The following statements print false
System.out.println( nan == nan );
System.out.println( nan < nan );
System.out.println( nan > nan );
System.out.println( positiveInfinity < positiveInfinity );
// The following statements print true
System.out.println( positiveInfinity == positiveInfinity );
System.out.println( 5.2 < positiveInfinity );
System.out.println( 5.2 > negativeInfinity );
}
}
Basic Java Structures Slide # 24
class Casting
{
public static void main( String args[] )
{
int anInt = 5;
float aFloat = 5.8f;
aFloat = anInt; // Implicit casts up are ok
anInt = aFloat ; // Compile error,
// must explicitly cast down
anInt = (int) aFloat ;
float error = 5.8; // Compile error, 5.8 is double
float works = ( float) 5.8;
char c = (char) aFloat;
double aDouble = 12D;
double bDouble = anInt + aDouble;
// anInt is cast up to double,
int noWay = 5 / 0; // Compile error, compiler detects
// zero divide
int zero = 0;
int trouble = 5 / zero; // Metroworks Compiler error
// No error on Sun compiler
int notZeroYet;
notZeroYet = 0;
trouble = 5 / notZeroYet ; // No compile error!
}
}
Basic Java Structures Slide # 25
Ints and Booleans are Different!
class UseBoolean
{
public static void main( String args[] )
{
if ( ( 5 > 4 ) == true )
System.out.println( "Java's explicit compare " );
if ( 5 > 4 )
System.out.println( "Java's implicit compare " );
if ( ( 5 > 4 ) != 0 ) // Compile error
System.out.println( "C way does not work" );
boolean cantCastFromIntToBoolean = (boolean) 0;
// compile error
int x = 10;
int y = 5;
if ( x = y ) // Compile error
System.out.println( "This does not work in Java " );
}
}
Basic Java Structures Slide # 26
All arithmetic variables are initialize to 0
char variables are initialize to the null character: '\u000'
boolean variables are initialize to false
reference variables are initialize to null
Compiler usually complains about using variables before explicitly giving them
a value
class InitializeBeforeUsing
{
public static void main( String args[] )
{
int noExplicitValue;
System.out.println( noExplicitValue ); // Compile error
int someValue;
boolean tautology = true;
if ( tautology )
{
someValue = 5;
}
System.out.println( someValue ); // Compile error
}
}
Basic Java Structures Slide # 27
Characters
class CharactersLiterals
{
public static void main( String args[] )
{
char backspace = '\b';
char tab = '\t';
char linefeed = '\n';
char formFeed = '\f';
char carriageReturn = '\r';
char doubleQuote = '\"';
char singleQuote = '\'';
char aCharacter = 'b';
char unicodeFormat = '\u0062'; // 'b'
}
}
Unicode
Superset of ASCII
Includes:
- ASCII, Latin letter with diacritics
- Greek, Cyrillic
- Korean Hangul
- Han ( Chinese, Japanese, Korean )
- Others
For more information see: The Unicode Standard Vol 1 or
URL
http://www.stonehand.com/unicode.html
Basic Java Structures Slide # 28
Contains all the standard C/C++ control structures
class Control
{
public static void main( String args[] )
{
int a = 5;
int b = 10;
if ( a > b ) System.out.println( "a is bigger ");
if ( a > b )
System.out.println( "a is bigger ");
else
System.out.println( "b is bigger ");
switch ( a )
{ //Controlling expression converted to int
case 4:
b++;
break;
case 10:
b--;
break;
default: // optional
System.out.println( "Default action" );
};
while ( a < b )
{
a++;
};
Basic Java Structures Slide # 29
// Control Structures Continued
for ( int loop = 0; loop < a; loop++ )
{
System.out.println( a );
};
System.out.println( loop ); // Error, loop does not
// exist here
do
{
System.out.println( a-- );
System.out.println( b );
}
while ( a > b );
int max = ( a > b ) ? a : b;
if ( ( a > 5 ) && ( b < 10 ) )
System.out.println( "Good" );
a += ( a = 5 );
}
}
Basic Java Structures Slide # 30
break, continue, return
class ControlStructures
{
public static void main( String args[] )
{
for ( int row = 0; row < 5; row++ )
{
for ( int column = 0; column < 4 ; column++ )
{
System.out.println( row + "\t" + column );
if ( ((row + column) % 2 ) == 0 )
break;
System.out.println( " After if " );
}
};
Outer:
for ( int row = 0; row < 5; row++ )
{
for ( int column = 0; column < 4; column++ )
{
System.out.println( row + "\t" + column );
if ( ((row + column) % 2 ) == 0 )
break Outer;
System.out.println( " After if " );
}
}
}
}
Output
0 0 | 3 0 |
1 0 | After if |
After if | 3 1 |
1 1 | 4 0 |
2 0 | 0 0 |
Basic Java Structures Slide # 31
class SampleFunction
{
public static int subtractOne( int decreaseMe )
{
return decreaseMe - 1;
}
public static void main( String[] args )
{
int startValue = 5;
int smaller = subtractOne( startValue );
int larger = addOne( startValue );
System.out.println( "smaller = " + smaller + "\n" +
"larger = " + larger );
}
public static int addOne( int increaseMe )
{
return increaseMe + 1;
}
}
Output
smaller = 4
larger = 6
Basic Java Structures Slide # 32
Parameter Passing - By value only
class TestParameter
{
public static void main( String[] args )
{
int startValue = 5;
noChange( startValue );
System.out.println( startValue );
}
public static void noChange( int fixed )
{
fixed = fixed + 10;
}
}
Output
5
Basic Java Structures Slide # 33
class ArrayExamples
{
public static void main( String args[] )
{
int declarationTypeA[] = new int[5];
float[] floatArray = new float[ 25 ];
int[] integerArray;
int[] alias;
integerArray = new int[ 10 ]; // Indexed from 0 to 9
for ( int index = 0; index < integerArray.length; index++ )
integerArray[ index ] = 5;
alias = integerArray; // Arrays are references
alias[ 3 ] = 10;
System.out.println( integerArray[ 3 ] );
integerArray = new int[ 8 ];
System.out.println( integerArray[ 3 ] );
System.out.println( alias[ 3 ] );
System.out.println( integerArray );
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char[] vowels = { 'a', 'e', 'o', 'i', 'u' };
}
}
Output
10
0
10
[I@5e300868
Basic Java Structures Slide # 34
Multidimensional Arrays
class MultidimensionalArrayExample
{
public static void main( String args[] )
{
int[][] squareArray = new int [ 10 ] [ 20 ];
squareArray[ 2 ] [ 5 ] = 25;
int[][][] threeDArray = new int [ 10 ] [ 20 ][ 5 ];
int[][] triangularArray;
triangularArray = new int [ 30 ] [ ] ;
for ( int row = 0; row < triangularArray.length; row ++ )
triangularArray [ row ] = new int [ row ];
for ( int row = 0; row < triangularArray.length; row ++ )
for ( int col = 0; col < triangularArray[ row ].length; col++ )
triangularArray[ row ][ col ] = 10;
}
}
Basic Java Structures Slide # 35
Arrays are references!
Garbage collection reclaims arrays that can not be accessed!
References are initialized to null
When done with a reference set it to null
class ArrayExamples
{
public static void main( String args[] )
{
int[] integerArray = new int[ 4 ];
integerArray[ 1 ] = 12
integerArray = new int[ 2 ]; // Memory Leak - No!
integerArray[ 1 ] = 5;
int[] aliasForArray = integerArray;
aliasForArray[ 1 ] = 10;
System.out.println( integerArray[ 1 ] ); //Prints 10
}
}
Basic Java Structures Slide # 36
Arrays, References
int[] integerArray = new int[ 4 ];
integerArray[ 1 ] = 12
integerArray = new int[ 2 ]; // Memory Leak - No!
integerArray[ 1 ] = 5;
int[] aliasForArray = integerArray;
aliasForArray[ 1 ] = 10;
Basic Java Structures Slide # 37
Memory Problems in C/C++
Memory Leaks
- Memory that program has allocated but can no longer access
-
- int* trouble = new int( 5 );
-
- trouble = new int( 8 );
-
-
-
Dangling References
- Two or more pointers point to the same memory on the heap
-
- Using one of the pointers the memory is deallocated
-
- Second pointer can still access the memory
Estimates are that up to 40% of development time in C/C++ are spent dealing
with these two problems
Basic Java Structures Slide # 38
Java Solution
No pointers
No explicit deallocation of memory
When memory can no longer be accessed, garbage collection eventually reclaims
the memory
-
Java's solution is more dynamic, flexible, and safer than C/C++
Basic Java Structures Slide # 39
Back To Arrays and References
Java wants all variables to be initialized before they are used
One can initialize arrays with null
When done with a reference set it to null to allow the memory to be
reclaimed
class ArrayExamples
{
public static void main( String args[] )
{
float[] floatArray = null;
floatArray = new float[ 25 ];
floatArray[ 1 ] = (float) 12.23;
floatArray = null;
// now the array of 25 elements can be reused
}
}
Basic Java Structures Slide # 40
Arrays and Functions
Arrays are references, a function can modify array elements
class ArrayAsParameter
{
public static void main( String args[] )
{
int[] integerArray = new int[ 10 ];
integerArray[ 1 ] = 5;
modifyElements( integerArray, 10 );
System.out.println( integerArray[ 1 ] );
}
public static void modifyElements( int[] changeMe, int newValue )
{
for ( int index = 0; index < changeMe.length; index++ )
changeMe[ index ] = newValue;
}
}
Output
10
Basic Java Structures Slide # 41
Arrays and Functions
Arrays are references, a function can not modify the array
class ArrayAsParameter
{
public static void main( String args[] )
{
int[] integerArray = new int[ 10 ];
integerArray[ 1 ] = 5;
doesNotWork( integerArray );
System.out.println( integerArray[ 1 ] );
}
public static void doesNotWork( int[] changeMe )
{
changeMe = new int[ 10 ];
for ( int index = 0; index < changeMe.length; index++ )
changeMe[ index ] = 555;
}
}
Output
5
Basic Java Structures Slide # 42
class StringExample
{
public static void main( String args[] )
{
String firstName = " Roger ";
String lastName = " Whitney ";
String fullName = firstName + lastName;
System.out.println( fullName );
firstName = firstName.toLowerCase();
lastName = lastName.toUpperCase();
System.out.println( firstName );
firstName = firstName.trim(); // trim leading, trailing
lastName = lastName.trim(); // white space
lastName = lastName.replace( 'I', 'a' );
System.out.println( firstName + lastName );
String floatAsString = String.valueOf( 13.4e+5f);
System.out.println( floatAsString );
}
}
Output
Roger Whitney
roger
rogerWHaTNEY
1.34e+06
Basic Java Structures Slide # 43
Some String Operations
charAt(int) | replace(char,char) |
compareTo(String) | startsWith(String) |
concat(String) | substring(int,int) |
copyValueOf(char[]) | toCharArray() |
endsWith(String) | toLowerCase() |
equals(Object) | toUpperCase() |
equalsIgnoreCase(String) | trim() |
getChars(int,int,char[],int) | valueOf(int) |
indexOf(String) | valueOf(long) |
lastIndexOf(String) | valueOf(float) |
length() | valueOf(double) |
regionMatches(int,String,int,int) | |
For more information see: http://www.sdsu.edu/doc/java/java.lang.String.html
String vs. char[] vs. C/C++ char*
Neither String nor char[] end in the null character like char* in C
char[]
- Array of characters
- Only array operations are supported
String
- Is a class with numerous operations
- Integrated into Java's ~200 classes
- Strings are constant,
- Their values cannot be changed after creation
Basic Java Structures Slide # 44
class CommandLineExample
{
public static void main( String args[] )
{
System.out.println( args.length );
for ( int k = 0; k < args.length; k++ )
{
System.out.println( "Argument " + k + "\t" + args[ k ] );
};
Float secondArgument = Float.valueOf( args[ 1 ] );
System.out.println( secondArgument );
}
}
rohan 16-> java CommandLineExample 1 2 3 4 5
5
Argument 0 1
Argument 1 2
Argument 2 3
Argument 3 4
Argument 4 5
2
Basic Java Structures Slide # 45
== and Strings
public class StringTest
{
public static void main( String[] args )
{
String me = "Roger";
if ( me == "Roger" )
System.out.println( "Yes, I am me" );
else
System.out.println( "No, I am not me?" );
String shortName = me.substring(0, 3);
System.out.println( shortName );
if ( shortName == "Rog" )
System.out.println( "Very Good" );
else
System.out.println( "Trouble here" );
if ( shortName.equals( "Rog" ) )
System.out.println( "Do it this way" );
}
}
Output
Yes, I am me
Rog
Trouble here
Do it this way
Basic Java Structures Slide # 46
== and String: The Issue
String is an object
String variables are references
The == operator check to see if two string references refer to the same memory
location
if ( me == "Roger" )
System.out.println( "Yes, I am me" );
else
System.out.println( "No, I am not me?" );
Compilers are allowed, but not required to store equal strings in the same
memory location.
Be safe and use the "equals" method to compare strings