Fundamentals of Java Programming
Entering a number the hard way!!
2
import [Link].*; import [Link].*; public class ReadTest { public static void main (String[] args) { [Link] (Enter a number: ); double x; try { InputStreamReader isr = new InputStreamReader ([Link]); BufferedReader br = new BufferedReader (isr); String s = [Link](); DecimalFormat df = new DecimalFormat(); Number n = [Link](s); x = [Link](); } catch (IOException e) { x = 0; } catch (ParseException e) { x = 0; } [Link] (You entered + x); } }
Pradip K Das
Java Fundamentals
Displaying Text in a Dialog Box
3
import [Link]; public class Welcome { public static void main (String[] args) { [Link] (null, "Welcome\nto\nJava\nProgramming"); [Link] (0); } }
Pradip K Das
Java Fundamentals
Another Java Application
4
import [Link]; public class Addition { public static void main (String[] args) { String firstNumber, secondNumber; int number1, number2, sum; firstNumber = [Link] ( "Enter first integer"); secondNumber = [Link] ( "Enter second integer"); number1 = [Link] (firstNumber); number2 = [Link] (secondNumber); sum = number1 + number2; [Link] (null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE); [Link] (0); } }
Pradip K Das
Java Fundamentals
Class as an Abstract Data Type 5
import [Link]; public class Time1 extends Object { private int hour; private int minute; private int second; public Time1() { setTime(0, 0, 0); } public void setTime (int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? s : 0); } public String toUniversalString() { DecimalFormat twoDigits = new DecimalFormat ("00"); return [Link] (hour) + ":" + [Link] (minute) + ":" + [Link] (second); } public String toStandardString() { DecimalFormat twoDigits = new DecimalFormat ("00"); return ((hour == 12 || hour ==0) ? 12 : hour % 12) + ":" + [Link] (minute) + ":" + [Link](second) + (hour < 12 ? " AM" : " PM"); } }
Pradip K Das
Java Fundamentals
Notes on Time1 Class
6
Every class in Java except Object class inherits from an existing class The Object class contains 11 methods Each instance of the class contains its own separate copy of the classs instance variables Keywords public and private are access specifiers. Variables or methods declared as private are accessible only to methods of the class in which they are declared As a rule of thumb every instance variable should be declared private (data hiding) and methods should be declared public Methods declared as private are called utility or helper methods Class Time1 contains constructor Time1.
Pradip K Das
Java Fundamentals