SlideShare a Scribd company logo
1 of 44
Download to read offline
Math and String Classes
Lecture 9
Naveen Kumar
Constructing Objects
 new Rectangle(5, 10, 20, 30)
Detail:
– The new operator makes a Rectangle object
– It uses the parameters (5, 10, 20, and 30) to initialize
the data of the object
– returns the object
 Usually the output of the new operator is stored
in a variable
Rectangle box = new Rectangle(5, 10, 20, 30);
Constructing Objects
Default constructor
 new Rectangle()
// constructs a rectangle with its top-left corner
// at the origin (0, 0), width 0, and height 0
Example
import java.awt.Rectangle;
public class Move
{
public static void main(String[] args)
{
Rectangle box = new Rectangle(5, 10, 20, 30);
// Move the rectangle
box.translate(15, 25);
// Print information about the moved rectangle
System.out.println("After moving, the top-left corner is:");
System.out.println(box.getX());
System.out.println(box.getY());
}
}
Random class
 Random r = new Random();
 int i = r.nextInt(int n) Returns random int ≥ 0 and < n
 int i = r.nextInt() Returns random int (full range)
 long i = r.nextLong() Returns random long (full range)
 float f = r.nextFloat() Returns random float ≥0.0 and <1.0
 double d = r.nextDouble() Returns random double ≥ 0.0 and < 1.0
 boolean b = r.nextBoolean() Returns random double (true ,false)
 double x;
x = Math.random(); // assigns random number to x
5
import java.util.Random;
Object References
 Describe the location of objects
 The new operator returns a reference to a new object
Rectangle box = new Rectangle();
 Multiple object variables can refer to the same object
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
box2.translate(15, 25);
 Primitive type variables ≠ object variables
Cast
 (typeName) expression
Example:
 (int) (balance * 100)
Purpose:
 To convert an expression to a different type
7
Constants: final
 A final variable is a constant
 Once its value has been set, it cannot be changed
 Named constants make programs easier to read and maintain
 Convention: use all-uppercase names for constants
final double QUARTER_VALUE = 0.25;
final double DIME_VALUE = 0.1;
8
Constants: static final
 static is used with class members
 If constant values are needed in several methods, declare them
together and tag them as static and final
 Give static final constants public access to enable other classes to
use them
public class Math
{
. . .
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
}
double circumference = Math.PI * diameter; (call without object)
9
Syntax : Constant Definition
 In a method:
final typeName variableName = expression ;
 In a class:
accessSpecifier static final typeName variableName =
expression;
Example:
 final double NICKEL_VALUE = 0.05;
 public static final double LITERS_PER_GALLON = 3.785;
Purpose:
 To define a constant in a method or a class
10
Increment, and Decrement
 items++ is the same as items = items + 1
 items-- subtracts 1 from items
 ++a;
 --a;
 a++;
 a--;
11
Arithmetic Operations
 / is the division operator
 If both arguments are integers, the result is an
integer. The remainder is discarded
– 7.0 / 4 yields 1.75
– 7 / 4 yields 1
 Get the remainder with % (pronounced "modulo")
7 % 4 is 312
The Math class
 Math class: contains methods like sqrt and pow
 To compute xn, you write Math.pow(x, n)
 However, to compute x2 it is significantly more efficient simply to
compute x * x
 To take the square root of a number x, use the Math.sqrt;
for example,
Math.sqrt(x)
13
Java.lang.Math
Mathematical Methods in Java
14
Math.sqrt(x) square root
Math.pow(x, y) power xy
Math.exp(x) ex
Math.log(x) natural log
Math.sin(x), Math.cos(x), Math.tan(x) sine, cosine, tangent (x in radian)
Math.round(x) closest integer to x
Math.min(x, y), Math.max(x, y) minimum, maximum
java.lang.Math methods
Constants: E, PI
 sin(_), cos(_), abs(_), tan(_),
 ceil(_), floor(_), log(_),
 max(_,_), min(_,_), pow(_,_), sqrt(_),
 round(_), random(),
 toDegrees(_), toRadians(_)
15
Self Check
 What is the value of 1729 / 100? and 1729 % 100?
 What does the following statement compute ?
double average = 20 + 25 + 30 / 3;
 What is the value of Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
in mathematical notation?
Answers
 17 and 29
 Only 30 is divided by 3. To get the correct result, use
parentheses. Moreover, if all three are integers, you must divide
by 3.0 to avoid integer division:
(20 + 25 + 30) / 3.0
16
Calling Static Methods
 A static method does not operate on an object
double x = 4;
double root = x.sqrt(); // Error
 Static methods are defined inside classes
 Naming convention: Classes start with an uppercase
letter; objects start with a lowercase letter
Math
System.out
17
Static Method Call
 ClassName. methodName(parameters)
Example:
 Math.sqrt(4)
Purpose:
 To invoke a static method (a method that
does not operate on an object) and supply its
parameters18
Self Check
 Why can't you call x.pow(y) to compute xy ?
 Is the call System.out.println(4) a static
method call?
Answers
 x is a number, not an object, and you cannot
invoke methods on numbers
 No–the println method is called on the object
System.out19
Strings
 A string is a sequence of characters
 Strings are objects of the String class
 String constants:
"Hello, World!"
 String variables:
String message = "Hello, World!";
 String length:
int n = message.length();
 Empty string: ""
20
Concatenation
 Use the + operator:
String name = "Dave";
String message = "Hello, " + name;
// message is "Hello, Dave"
 If one of the arguments of the + operator is a
string, the other is converted to a string
String a = "Agent";
int n = 7;
String bond = a + n; // bond is Agent7
21
Converting between Strings and
Numbers
 Convert to number:
int n = Integer.parseInt(str);
double x = Double.parseDouble(x);
int num = Integer.parseInt("1234");
 Convert to string:
String str = "" + n;
str = Integer.toString(n);
String str = String.valueOf(num);22
Substrings
 String greeting = "Hello, World!";
String sub = greeting.substring(0, 5);
// sub is "Hello"
 Supply start and end positions, end is not
included
 First position is at 0
23
Self Check
 Assuming the String variable s holds the value "Agent", what is
the effect of the assignment s = s + s.length() ?
 Assuming the String variable river holds the value "Mississippi",
what is the value of
river.substring(1, 2)? and
river.substring(2, river.length() - 3)?
Answers
 s is set to the string Agent5
 The strings "i" and
 "ssissi"
24
Frame Windows
 The JFrame class JFrame frame = new JFrame();
 frame.setSize(300, 400);
frame.setTitle("An Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
 import javax.swing.*;
25
Frame program
import javax.swing.*;
public class frame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("An Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
26
Self Check
 How do you display a square frame with a title bar that
reads "Hello, World!"?
 How can a program display two frames at once?
Answers
 Modify the EmptyFrameViewer program as follows:
frame.setSize(300, 300);
frame.setTitle("Hello, World!");
 Construct two JFrame objects, set each of their sizes,
and call setVisible(true) on each of them
27
Drawing Shapes
 paintComponent: called whenever the component
needs to be repainted:
public class frame1 extends JComponent
{
public void paintComponent(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
. . .
}
}
28
Drawing Shapes
 Graphics class lets you manipulate the graphics state
(such as current color)
 Graphics2D class has methods to draw shape objects
 Use a cast to recover the Graphics2D object from the
Graphics parameter
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box);
 java.awt package29
Rectangle Drawing Program Classes
 frame1: its paintComponent method produces the drawing
 frame: its main method constructs a frame and a frame1, adds the
component to the frame, and makes the frame visible
– Construct a frame
– Construct an object of your component class:
frame1 component = new frame1();
– Add the component to the frame
frame.add(component);
However, if you use an older version of Java (before Version 5), you
must make a slightly more complicated call:
frame.getContentPane().add(component);
– Make the frame visible
30
An example (produce a drawing
with two boxes)
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JPanel;
import javax.swing.Jcomponent; /** A component that draws two rectangles. */
public class frame1 extends Jcomponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g; // Recover Graphics2D
Rectangle box = new Rectangle(5, 10, 20, 30); // Construct a rectangle and
g2.draw(box); // draw it
box.translate(15, 25); // Move rectangle 15 units to the right and 25 units down
g2.draw(box); // Draw moved rectangle
} }
31
Create frame and add drawing
import javax.swing.JFrame;
public class frame {
public static void main(String[] args) {
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setTitle("Two rectangles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1 component = new frame1();
frame.add(component);
frame.setVisible(true);
} }32
Self Check
 How do you modify the program to draw two squares?
 How do you modify the program to draw one rectangle and one
square?
 What happens if you call g.draw(box) instead of g2.draw(box)?
Answers
 Rectangle box = new Rectangle(5, 10, 20, 20);
 Replace the call to box.translate(15, 25) with
box = new Rectangle(20, 35, 20, 20);
 The compiler complains that g doesn't have a draw method
33
Applets
 This is almost the same outline as for a component, with two minor
differences:
– You extend JApplet, not JComponent
– You place the drawing code inside the paint method, not inside
paintComponent
 To run an applet, you need an HTML file with the applet tag
 You view applets with the appletviewer
34
JApplet
/*
<APPLET CODE="frameapplet.class" WIDTH=350 HEIGHT=200>
</APPLET>
*/
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JApplet; /** An applet that draws two rectangles. */
public class frameapplet extends JApplet
{
public void paint(Graphics g)
{ // Prepare for extended graphics
Graphics2D g2 = (Graphics2D) g; // Construct a rectangle and draw it
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box); // Move rectangle 15 units to the right and 25 units down
box.translate(15, 25); // Draw moved rectangle
g2.draw(box);
}
}
35
Graphical Shapes
 Rectangle, Ellipse2D.Double, and Line2D.Double describe graphical
shapes
 We won't use the .Float classes
 These classes are inner classes–doesn't matter to us except for the
import statement:
import java.awt.geom.Ellipse2D; // no .Double
 Must construct and draw the shape
Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height);
g2.draw(ellipse);
36
Drawing Lines
To draw a line:
 Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2);
or
 Point2D.Double from = new Point2D.Double(x1, y1);
Point2D.Double to = new Point2D.Double(x2, y2);
Line2D.Double segment = new Line2D.Double(from, to);
37
Self Check
 Give instructions to draw a circle with center (100,100) and radius 25
 Give instructions to draw a letter "V" by drawing two line segments
 Give instructions to draw a string consisting of the letter "V"
Answers
 g2.draw(new Ellipse2D.Double(75, 75, 50, 50);
 Line2D.Double segment1 = new Line2D.Double(0, 0, 10, 30);
g2.draw(segment1);
Line2D.Double segment2 = new Line2D.Double(10, 30, 20, 0);
g2.draw(segment2);
 g2.drawString("V", 0, 30);
38
Upper-left corner, Width , Height
Colors
 Standard colors Color.BLUE, Color.RED, Color.PINK etc.
 Specify red, green, blue between 0.0F and 1.0F
 Color magenta = new Color(1.0F, 0.0F, 1.0F); // F = float
Set color in graphics context
 g2.setColor(magenta);
Color is used when drawing and filling shapes
 g2.fill(rectangle); // filled with current color
39
Self Check
 What are the RGB color values of Color.BLUE?
 How do you draw a yellow square on a red background?
Answers
 0.0F, 0.0F, and 0.1F
 First fill a big red square, then fill a small yellow square inside:
g2.setColor(Color.RED);
g2.fill(new Rectangle(0, 0, 200, 200));
g2.setColor(Color.YELLOW);
g2.fill(new Rectangle(50, 50, 100, 100));
Note: Use import java.awt.Color;
40
Drawing Graphical Shapes
 Rectangle leftRectangle
= new Rectangle(100, 100, 30, 60);
Rectangle rightRectangle
= new Rectangle(160, 100, 30, 60);
Line2D.Double topLine
= new Line2D.Double(130, 100, 160, 100);
Line2D.Double bottomLine
= new Line2D.Double(130, 160, 160, 160);
41
Reading Text Input
 A graphical application can obtain input by displaying a
JOptionPane
 The showInputDialog method displays a prompt and
waits for user input
 The showInputDialog method returns the string that the
user typed
String input = JOptionPane.showInputDialog("Enter x");
double x = Double.parseDouble(input);
42
An Example
import java.awt.Color; import javax.swing.Jframe;
import javax.swing.JOptionPane; import javax.swing.JComponent;
public class ColorViewer {
public static void main(String[] args) {
JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String input; // Ask the user for red, green, blue values
input = JOptionPane.showInputDialog("red:");
double red = Double.parseDouble(input);
input = JOptionPane.showInputDialog("green:");
double green = Double.parseDouble(input);
input = JOptionPane.showInputDialog("blue:");
double blue = Double.parseDouble(input);
Color fillColor = new Color( (float) red, (float) green, (float) blue);
ColoredSquarecomponent = new ColoredSquare (fillColor);
frame.add(component); frame.setVisible(true); } }43
Example cont.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D;
import java.awt.Rectangle; import javax.swing.JComponent;
public class ColoredSquare extends Jcomponent {
private Color fillColor;
public ColoredSquare (Color aColor) { fillColor = aColor; }
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g; // Select color into graphics context
g2.setColor(fillColor); // Const and fill a square whose center is center of the window
final int SQUARE_LENGTH = 100;
Rectangle square = new Rectangle((getWidth() - SQUARE_LENGTH) / 2, (getHeight()
SQUARE_LENGTH) / 2, SQUARE_LENGTH, SQUARE_LENGTH);
g2.fill(square); }
}44

More Related Content

What's hot

Matlab 1
Matlab 1Matlab 1
Matlab 1
asguna
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
Computer Science Club
 

What's hot (20)

Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 
Intro to matlab
Intro to matlabIntro to matlab
Intro to matlab
 
Vectors data frames
Vectors data framesVectors data frames
Vectors data frames
 
Intro to Matlab programming
Intro to Matlab programmingIntro to Matlab programming
Intro to Matlab programming
 
Chapter2
Chapter2Chapter2
Chapter2
 
Matlab 1
Matlab 1Matlab 1
Matlab 1
 
Matlab ploting
Matlab plotingMatlab ploting
Matlab ploting
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
Chapter2
Chapter2Chapter2
Chapter2
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
 
Introduction to Neural Netwoks
Introduction to Neural Netwoks Introduction to Neural Netwoks
Introduction to Neural Netwoks
 
Explanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expertExplanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expert
 
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
 
5. R basics
5. R basics5. R basics
5. R basics
 
Introduction to matlab lecture 3 of 4
Introduction to matlab lecture 3 of 4Introduction to matlab lecture 3 of 4
Introduction to matlab lecture 3 of 4
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Lec4
Lec4Lec4
Lec4
 
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
 
Kernels and Support Vector Machines
Kernels and Support Vector  MachinesKernels and Support Vector  Machines
Kernels and Support Vector Machines
 

Viewers also liked

Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]
Palak Sanghani
 
Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]
Palak Sanghani
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 

Viewers also liked (6)

Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]
 
Comparisionof trees
Comparisionof treesComparisionof trees
Comparisionof trees
 
Lec 1 25_jul13
Lec 1 25_jul13Lec 1 25_jul13
Lec 1 25_jul13
 
Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]
 
Nature
NatureNature
Nature
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
 

Similar to Lec 9 05_sept [compatibility mode]

Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
Palak Sanghani
 
Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]
Palak Sanghani
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
sotlsoc
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
anhlodge
 

Similar to Lec 9 05_sept [compatibility mode] (20)

Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Ch3
Ch3Ch3
Ch3
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Jeop game-final-review
Jeop game-final-reviewJeop game-final-review
Jeop game-final-review
 
ch03-parameters-objects.ppt
ch03-parameters-objects.pptch03-parameters-objects.ppt
ch03-parameters-objects.ppt
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
 
Matlab1
Matlab1Matlab1
Matlab1
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPT
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
 
Parameters
ParametersParameters
Parameters
 
Getters_And_Setters.pptx
Getters_And_Setters.pptxGetters_And_Setters.pptx
Getters_And_Setters.pptx
 
basic concepts
basic conceptsbasic concepts
basic concepts
 

More from Palak Sanghani

More from Palak Sanghani (16)

Survey form
Survey formSurvey form
Survey form
 
Survey
SurveySurvey
Survey
 
Nature2
Nature2Nature2
Nature2
 
Texture
TextureTexture
Texture
 
Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]
 
Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]
 
Lec 3 01_aug13
Lec 3 01_aug13Lec 3 01_aug13
Lec 3 01_aug13
 
Lec 2 30_jul13
Lec 2 30_jul13Lec 2 30_jul13
Lec 2 30_jul13
 
My Structure Patterns
My Structure PatternsMy Structure Patterns
My Structure Patterns
 
My Similarity Patterns
My Similarity PatternsMy Similarity Patterns
My Similarity Patterns
 
My Radiation Patterns
My Radiation PatternsMy Radiation Patterns
My Radiation Patterns
 
My Gradation Patterns
My Gradation PatternsMy Gradation Patterns
My Gradation Patterns
 
My Circular Patterns
My Circular PatternsMy Circular Patterns
My Circular Patterns
 
My Anomaly Patterns
My Anomaly PatternsMy Anomaly Patterns
My Anomaly Patterns
 
Library of Babel Illustrations
Library of Babel IllustrationsLibrary of Babel Illustrations
Library of Babel Illustrations
 
Circle patterns
Circle patternsCircle patterns
Circle patterns
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 

Lec 9 05_sept [compatibility mode]

  • 1. Math and String Classes Lecture 9 Naveen Kumar
  • 2. Constructing Objects  new Rectangle(5, 10, 20, 30) Detail: – The new operator makes a Rectangle object – It uses the parameters (5, 10, 20, and 30) to initialize the data of the object – returns the object  Usually the output of the new operator is stored in a variable Rectangle box = new Rectangle(5, 10, 20, 30);
  • 3. Constructing Objects Default constructor  new Rectangle() // constructs a rectangle with its top-left corner // at the origin (0, 0), width 0, and height 0
  • 4. Example import java.awt.Rectangle; public class Move { public static void main(String[] args) { Rectangle box = new Rectangle(5, 10, 20, 30); // Move the rectangle box.translate(15, 25); // Print information about the moved rectangle System.out.println("After moving, the top-left corner is:"); System.out.println(box.getX()); System.out.println(box.getY()); } }
  • 5. Random class  Random r = new Random();  int i = r.nextInt(int n) Returns random int ≥ 0 and < n  int i = r.nextInt() Returns random int (full range)  long i = r.nextLong() Returns random long (full range)  float f = r.nextFloat() Returns random float ≥0.0 and <1.0  double d = r.nextDouble() Returns random double ≥ 0.0 and < 1.0  boolean b = r.nextBoolean() Returns random double (true ,false)  double x; x = Math.random(); // assigns random number to x 5 import java.util.Random;
  • 6. Object References  Describe the location of objects  The new operator returns a reference to a new object Rectangle box = new Rectangle();  Multiple object variables can refer to the same object Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25);  Primitive type variables ≠ object variables
  • 7. Cast  (typeName) expression Example:  (int) (balance * 100) Purpose:  To convert an expression to a different type 7
  • 8. Constants: final  A final variable is a constant  Once its value has been set, it cannot be changed  Named constants make programs easier to read and maintain  Convention: use all-uppercase names for constants final double QUARTER_VALUE = 0.25; final double DIME_VALUE = 0.1; 8
  • 9. Constants: static final  static is used with class members  If constant values are needed in several methods, declare them together and tag them as static and final  Give static final constants public access to enable other classes to use them public class Math { . . . public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846; } double circumference = Math.PI * diameter; (call without object) 9
  • 10. Syntax : Constant Definition  In a method: final typeName variableName = expression ;  In a class: accessSpecifier static final typeName variableName = expression; Example:  final double NICKEL_VALUE = 0.05;  public static final double LITERS_PER_GALLON = 3.785; Purpose:  To define a constant in a method or a class 10
  • 11. Increment, and Decrement  items++ is the same as items = items + 1  items-- subtracts 1 from items  ++a;  --a;  a++;  a--; 11
  • 12. Arithmetic Operations  / is the division operator  If both arguments are integers, the result is an integer. The remainder is discarded – 7.0 / 4 yields 1.75 – 7 / 4 yields 1  Get the remainder with % (pronounced "modulo") 7 % 4 is 312
  • 13. The Math class  Math class: contains methods like sqrt and pow  To compute xn, you write Math.pow(x, n)  However, to compute x2 it is significantly more efficient simply to compute x * x  To take the square root of a number x, use the Math.sqrt; for example, Math.sqrt(x) 13 Java.lang.Math
  • 14. Mathematical Methods in Java 14 Math.sqrt(x) square root Math.pow(x, y) power xy Math.exp(x) ex Math.log(x) natural log Math.sin(x), Math.cos(x), Math.tan(x) sine, cosine, tangent (x in radian) Math.round(x) closest integer to x Math.min(x, y), Math.max(x, y) minimum, maximum
  • 15. java.lang.Math methods Constants: E, PI  sin(_), cos(_), abs(_), tan(_),  ceil(_), floor(_), log(_),  max(_,_), min(_,_), pow(_,_), sqrt(_),  round(_), random(),  toDegrees(_), toRadians(_) 15
  • 16. Self Check  What is the value of 1729 / 100? and 1729 % 100?  What does the following statement compute ? double average = 20 + 25 + 30 / 3;  What is the value of Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) in mathematical notation? Answers  17 and 29  Only 30 is divided by 3. To get the correct result, use parentheses. Moreover, if all three are integers, you must divide by 3.0 to avoid integer division: (20 + 25 + 30) / 3.0 16
  • 17. Calling Static Methods  A static method does not operate on an object double x = 4; double root = x.sqrt(); // Error  Static methods are defined inside classes  Naming convention: Classes start with an uppercase letter; objects start with a lowercase letter Math System.out 17
  • 18. Static Method Call  ClassName. methodName(parameters) Example:  Math.sqrt(4) Purpose:  To invoke a static method (a method that does not operate on an object) and supply its parameters18
  • 19. Self Check  Why can't you call x.pow(y) to compute xy ?  Is the call System.out.println(4) a static method call? Answers  x is a number, not an object, and you cannot invoke methods on numbers  No–the println method is called on the object System.out19
  • 20. Strings  A string is a sequence of characters  Strings are objects of the String class  String constants: "Hello, World!"  String variables: String message = "Hello, World!";  String length: int n = message.length();  Empty string: "" 20
  • 21. Concatenation  Use the + operator: String name = "Dave"; String message = "Hello, " + name; // message is "Hello, Dave"  If one of the arguments of the + operator is a string, the other is converted to a string String a = "Agent"; int n = 7; String bond = a + n; // bond is Agent7 21
  • 22. Converting between Strings and Numbers  Convert to number: int n = Integer.parseInt(str); double x = Double.parseDouble(x); int num = Integer.parseInt("1234");  Convert to string: String str = "" + n; str = Integer.toString(n); String str = String.valueOf(num);22
  • 23. Substrings  String greeting = "Hello, World!"; String sub = greeting.substring(0, 5); // sub is "Hello"  Supply start and end positions, end is not included  First position is at 0 23
  • 24. Self Check  Assuming the String variable s holds the value "Agent", what is the effect of the assignment s = s + s.length() ?  Assuming the String variable river holds the value "Mississippi", what is the value of river.substring(1, 2)? and river.substring(2, river.length() - 3)? Answers  s is set to the string Agent5  The strings "i" and  "ssissi" 24
  • 25. Frame Windows  The JFrame class JFrame frame = new JFrame();  frame.setSize(300, 400); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);  import javax.swing.*; 25
  • 26. Frame program import javax.swing.*; public class frame { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } 26
  • 27. Self Check  How do you display a square frame with a title bar that reads "Hello, World!"?  How can a program display two frames at once? Answers  Modify the EmptyFrameViewer program as follows: frame.setSize(300, 300); frame.setTitle("Hello, World!");  Construct two JFrame objects, set each of their sizes, and call setVisible(true) on each of them 27
  • 28. Drawing Shapes  paintComponent: called whenever the component needs to be repainted: public class frame1 extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; . . . } } 28
  • 29. Drawing Shapes  Graphics class lets you manipulate the graphics state (such as current color)  Graphics2D class has methods to draw shape objects  Use a cast to recover the Graphics2D object from the Graphics parameter Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box);  java.awt package29
  • 30. Rectangle Drawing Program Classes  frame1: its paintComponent method produces the drawing  frame: its main method constructs a frame and a frame1, adds the component to the frame, and makes the frame visible – Construct a frame – Construct an object of your component class: frame1 component = new frame1(); – Add the component to the frame frame.add(component); However, if you use an older version of Java (before Version 5), you must make a slightly more complicated call: frame.getContentPane().add(component); – Make the frame visible 30
  • 31. An example (produce a drawing with two boxes) import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JPanel; import javax.swing.Jcomponent; /** A component that draws two rectangles. */ public class frame1 extends Jcomponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // Recover Graphics2D Rectangle box = new Rectangle(5, 10, 20, 30); // Construct a rectangle and g2.draw(box); // draw it box.translate(15, 25); // Move rectangle 15 units to the right and 25 units down g2.draw(box); // Draw moved rectangle } } 31
  • 32. Create frame and add drawing import javax.swing.JFrame; public class frame { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH,FRAME_HEIGHT); frame.setTitle("Two rectangles"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1 component = new frame1(); frame.add(component); frame.setVisible(true); } }32
  • 33. Self Check  How do you modify the program to draw two squares?  How do you modify the program to draw one rectangle and one square?  What happens if you call g.draw(box) instead of g2.draw(box)? Answers  Rectangle box = new Rectangle(5, 10, 20, 20);  Replace the call to box.translate(15, 25) with box = new Rectangle(20, 35, 20, 20);  The compiler complains that g doesn't have a draw method 33
  • 34. Applets  This is almost the same outline as for a component, with two minor differences: – You extend JApplet, not JComponent – You place the drawing code inside the paint method, not inside paintComponent  To run an applet, you need an HTML file with the applet tag  You view applets with the appletviewer 34
  • 35. JApplet /* <APPLET CODE="frameapplet.class" WIDTH=350 HEIGHT=200> </APPLET> */ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JApplet; /** An applet that draws two rectangles. */ public class frameapplet extends JApplet { public void paint(Graphics g) { // Prepare for extended graphics Graphics2D g2 = (Graphics2D) g; // Construct a rectangle and draw it Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); // Move rectangle 15 units to the right and 25 units down box.translate(15, 25); // Draw moved rectangle g2.draw(box); } } 35
  • 36. Graphical Shapes  Rectangle, Ellipse2D.Double, and Line2D.Double describe graphical shapes  We won't use the .Float classes  These classes are inner classes–doesn't matter to us except for the import statement: import java.awt.geom.Ellipse2D; // no .Double  Must construct and draw the shape Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height); g2.draw(ellipse); 36
  • 37. Drawing Lines To draw a line:  Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2); or  Point2D.Double from = new Point2D.Double(x1, y1); Point2D.Double to = new Point2D.Double(x2, y2); Line2D.Double segment = new Line2D.Double(from, to); 37
  • 38. Self Check  Give instructions to draw a circle with center (100,100) and radius 25  Give instructions to draw a letter "V" by drawing two line segments  Give instructions to draw a string consisting of the letter "V" Answers  g2.draw(new Ellipse2D.Double(75, 75, 50, 50);  Line2D.Double segment1 = new Line2D.Double(0, 0, 10, 30); g2.draw(segment1); Line2D.Double segment2 = new Line2D.Double(10, 30, 20, 0); g2.draw(segment2);  g2.drawString("V", 0, 30); 38 Upper-left corner, Width , Height
  • 39. Colors  Standard colors Color.BLUE, Color.RED, Color.PINK etc.  Specify red, green, blue between 0.0F and 1.0F  Color magenta = new Color(1.0F, 0.0F, 1.0F); // F = float Set color in graphics context  g2.setColor(magenta); Color is used when drawing and filling shapes  g2.fill(rectangle); // filled with current color 39
  • 40. Self Check  What are the RGB color values of Color.BLUE?  How do you draw a yellow square on a red background? Answers  0.0F, 0.0F, and 0.1F  First fill a big red square, then fill a small yellow square inside: g2.setColor(Color.RED); g2.fill(new Rectangle(0, 0, 200, 200)); g2.setColor(Color.YELLOW); g2.fill(new Rectangle(50, 50, 100, 100)); Note: Use import java.awt.Color; 40
  • 41. Drawing Graphical Shapes  Rectangle leftRectangle = new Rectangle(100, 100, 30, 60); Rectangle rightRectangle = new Rectangle(160, 100, 30, 60); Line2D.Double topLine = new Line2D.Double(130, 100, 160, 100); Line2D.Double bottomLine = new Line2D.Double(130, 160, 160, 160); 41
  • 42. Reading Text Input  A graphical application can obtain input by displaying a JOptionPane  The showInputDialog method displays a prompt and waits for user input  The showInputDialog method returns the string that the user typed String input = JOptionPane.showInputDialog("Enter x"); double x = Double.parseDouble(input); 42
  • 43. An Example import java.awt.Color; import javax.swing.Jframe; import javax.swing.JOptionPane; import javax.swing.JComponent; public class ColorViewer { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String input; // Ask the user for red, green, blue values input = JOptionPane.showInputDialog("red:"); double red = Double.parseDouble(input); input = JOptionPane.showInputDialog("green:"); double green = Double.parseDouble(input); input = JOptionPane.showInputDialog("blue:"); double blue = Double.parseDouble(input); Color fillColor = new Color( (float) red, (float) green, (float) blue); ColoredSquarecomponent = new ColoredSquare (fillColor); frame.add(component); frame.setVisible(true); } }43
  • 44. Example cont. import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JComponent; public class ColoredSquare extends Jcomponent { private Color fillColor; public ColoredSquare (Color aColor) { fillColor = aColor; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // Select color into graphics context g2.setColor(fillColor); // Const and fill a square whose center is center of the window final int SQUARE_LENGTH = 100; Rectangle square = new Rectangle((getWidth() - SQUARE_LENGTH) / 2, (getHeight() SQUARE_LENGTH) / 2, SQUARE_LENGTH, SQUARE_LENGTH); g2.fill(square); } }44