Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Declaring console static and global
import java.util.*;
public class Test
{
static Scanner console = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter name");
String name = console.next();
System.out.println("Hello" + name);
}
}
• import java.lang – happens automatically –
includes String, Math, wrapper classes
• import java.util.*; - necessary for Scanner
Public static methods
• All methods of Math are public and static
• General use of a Math method is
Math.methodName (params)
• Or Math.pow(2,3)
• If you import the class statically, you can use
the method directly
• import static java.lang.Math.*;
• pow(2,3)
• Formal parameter – a variable declared in the
method heading
• Actual parameter – a variable or expression
listed in a method call
public class Demo
{
public static void main(String[] args)
{
// Part III - strings
String s = "Java is fun!";
System.out.println(s); // print it (7)
sMethod(s);
System.out.println(s); // print it (9)
}
public static void sMethod(String sTest)
{
sTest = sTest.substring(8, 11); // change it
System.out.println(sTest); // print it (8)
}
}
Java is fun!
fun
Java is fun!
COSC236 Modularity
5
precaution with strings
•
•
•
•
•
Remember - the String class is immutable
String str;
str = "hello";
str 1500 "hello"
str = "Hello There"; str 1800 "Hello There"
anytime you use assignment with a String variable,
new memory space is allocated
• also, the String class has no methods that allow you
to change an existing string
COSC236 Modularity
6
public class DemoPassByReference
{
public static void main(String[] args)
{
// Part II - objects and object references
StringBuffer sb = new StringBuffer("Hello, world");
System.out.println(sb); // print it (4)
sbMethod(sb);
System.out.println(sb); // print it (6)
System.out.println("-----------------");
}
public static void sbMethod(StringBuffer sTest)
{
sTest = sTest.insert(7,"cruel "); // change it
System.out.println(sTest); // print it (8)
}
}
Hello, world
Hello, cruel world
Hello, cruel world
COSC236 Modularity
7
• Wrapper classes – Integer, Double, etc are also
immutable
• See example7-11 on p. 402