A first look
A Java class is a Ring class. This lesson calls static methods, creates objects, chains calls and asks which Java is running.
What you will learn#
- how a Java class becomes a Ring class with the same name,
- static methods and constants, called on the class name,
- calling a method on the object that another method returned,
System.outand the Java version of the program.
The program#
# Tutorial 1: a first look - classes, objects, static members and the Java version
load "java.ring"
using {
"java.lang"
"java.util"
}
# 1. a class of Java is a class of Ring
oList = new ArrayList
oList.add("Ring")
oList.add("Java")
? "list: " + oList.toString()
? "size: " + oList.size()
# 2. static methods and constants are called on the class name (java.lang has ready objects)
? "max: " + Math.max(3,9)
? "biggest int: " + Integer.MAX_VALUE
? "pi: " + Math.PI
# 3. a method that gives an object lets you call the next one
oSB = new StringBuilder("Ring")
oSB.append(" + ").append("Java").append("!")
? oSB.toString()
# 4. System.out is a Java object
System.out.@println("printed by System.out.println")
# 5. which Java runs the program?
? "Java " + jVersion()
? "the class of oList: " + oList.getClass().getName()list: [Ring, Java]
size: 2
max: 9
biggest int: 2147483647
pi: 3.14
Ring + Java!
printed by System.out.println
Java 21.0.8
the class of oList: java.util.ArrayListHow it works#
Classes and objects#
using { "java.util" } makes the classes of a package available by their short names. new ArrayList creates a Java object; its methods are called like the methods of a Ring object. The classes of java.lang (System, Math, Integer...) are ready-made objects: write Math.max(3,9), no new needed.
Static members#
A static method belongs to the class, not to an object: Integer.parseInt("42"). A constant such as Integer.MAX_VALUE is read the same way.
Chaining#
A method that returns an object lets you call the next method on it: System.getProperty("java.version") gives a text, and Instant.now().toString() gives an object and then a text.
Exercises#
- Print
Math.sqrt(2),Math.PIandMath.pow(2,10). - Print the name of your operating system (
System.getProperty("os.name")). - Create a
StringBuilder, append two texts and print the result.