Download presentation
Presentation is loading. Please wait.
1
1 TP #4 n Last TP exercises solved; n Parsing command line arguments; n Static; n Wrapper classes for primitive types; n Package visibility.
2
© L.Lúcio, 2004 2 Last TP exercises solved n The Logger class: package ch.unige.cours.langages.TP3; public class Logger { /** Internal priority of a logger object */ private int priority; public Logger(int priority){ this.priority = priority; } /** Change priority */ public void setPriority(int priority) { this.priority = priority; } /** Print a message if its priority is more important than the logger's priority */ public void print(String msg, int msgPriority) { if (msgPriority <= priority) System.out.println(msg); }
3
© L.Lúcio, 2004 3 Last TP exercises solved (2) n Example of usage: import ch.unige.cours.langages.TP3.*; public class Test { public static void main(String[] args) { if (args.length != 1) { System.out.println("You must pass the verbosity level to the application..."); System.exit(-1); } /* parse the level of priority from the command line */ int i = Integer.parseInt(args[0]); /* create the logger object with the adequate priority */ Logger log = new Logger(i); log.print("This is a message with priority 0",0); log.print("This is a message with priority 1",1); log.print("This is a message with priority 2",2); log.print("This is a message with priority 3",3); }
4
© L.Lúcio, 2004 4 Last TP exercises solved (3) n Command line execution:
5
© L.Lúcio, 2004 5 Static n How does the following command work? int i = Integer.parseInt(args[0]); n The parseInt method of the Integer class is defined as static, so it can be called without an instance of the class… n In a class, both data and methods that are static are common to all instances of the class: class myClass { static int counter=0; int someData; static void incr() { counter++; }
6
© L.Lúcio, 2004 6 Static (2) n What would be the output of the previous program? n Would it make sense for the static incr() method to access someData? n Why is the main (entry point for a java program) static? MyClass my1 = new MyClass(); MyClass my2 = new MyClass(); MyClass.incr(); System.out.println(my1.counter); System.out.println(my2.counter); System.out.println(MyClass.counter);
7
© L.Lúcio, 2004 7 Wrapper classes for primitive types int i = Integer.parseInt(args[0]); n In the java.lang package java provides wrappers for all the primitive types: Boolean, Byte, Character, Double, Float, Integer, Long, and Short n Useful if it is necessary to use primitive types as objects; n Provide utilities (e.g. parseInt) to ease the life of the programmer; n Provide constants about the type (e.g. max, min values); n Check the javadoc (on the web) for more information…
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.