Use LEFT and RIGHT arrow keys to navigate between flashcards;
Use UP and DOWN arrow keys to flip the card;
H to show hint;
A reads text to speech;
207 Cards in this Set
- Front
- Back
Why are interpreted languages slower than compiled ones?
|
the interpreter needs to work with the code as a whole and take shortcuts to speed up the process
compiled languages can be much faster than interpreted languages because they do things to make the program run more efficiantly |
|
Interpreted language
|
are programming language in which programs are 'indirectly' executed ("interpreted") by an interpreter program
BASIC, JS, Perl, PHP, Ruby |
|
Interpreted language advantages
|
1)platform independence (Java's byte code, for example)
2)reflection and reflective use of the evaluator (e.g. a first-order eval function) 3)dynamic typing 4)smaller executable program size (since implementations have flexibility to choose the instruction code) 5)dynamic scoping |
|
reflection in computer science
|
the ability of a computer program to examine and modify the structure and behavior of an object at a runtime.
Used mostly in high level VM programming languages also in scripting languages |
|
compiled language
|
compiled language is a programming language whose implementations are typically compilers (translators which generate machine code from source code), and not interpreters (step-by-step executors of source code, where no translation takes place).
The term is somewhat vague; in principle any language can be implemented with a compiler or with an interpreter. A combination of both solutions is also increasingly common: a compiler can translate the source code into some intermediate form (often called bytecode), which is then passed to an interpreter which executes it. A program translated by a compiler tends to be much faster than an interpreter executing the same program: even a 10:1 ratio is not uncommon C++, C# |
|
Requirements for Java program name
|
Java program must have a name that matches the
first part of its filename and should be capitalized the same way. |
|
main statement is the entry point to most Java programs. The most common exceptions are (2 list)
-------------------------------- the structure of applets differs from application (list) |
1)applets - programs that are run as part of a web
page 2)servlets - programs run by a web server -------------------------------- 1)no main() block 2)has init() and paint() |
|
Java was developed in 1990 by
OOP def |
James Gosling
Object-oriented programming software development methodology in which a program is conceptualized as a group of objects that worked together |
|
in Netbeans how to specify argument for the program that is expecting command line parameters
|
1)Choose the menu command Run, Set Project Configuration, Customize. The Project Properties dialog opens.
2)In the Arguments field, enter arguments 3)Change the main Class text field if needed |
|
What is different in applets vs regular apps?
applet (def) |
1)applets do not have main()
2)they have init() and paint() applet (def) - A Java program that runs as part of a web page is called an applet |
|
Sample applet
|
import java.awt.*;
public class RootApplet extends javax.swing.JApplet { int number; public void init() { number = 225; } public void paint(Graphics screen) { Graphics2D screen2D = (Graphics2D) screen; screen2D.drawString("The square root of " + number + " is " + Math.sqrt(number), 5, 50); } } |
|
Do all arguments sent to a Java application have to be strings?
|
Java stores all arguments as strings when an application runs. When you want to use one of these arguments as an integer or some other nonstring type, you have to convert the value.
|
|
list of java primitive data type (8)
|
byte - 8 bit - from -128 to 127
short - 16 bit - from -32,678 to 32,677 int - 32 bit - from -2,147,483,648 to 2,147,483,647 long - 64 bit - from -9.22 quintillion to 9.22 quintillion float - 32 bit double - 64 bit boolean - true/false char - 16 bit unicode char |
|
Can I specify integers as binary values in Java?
|
You can for the first time in Java 7. Put the characters 0b in front of the number and follow it with the bits in the value. Because 1101 is the binary form for the number 13, the following statement sets an integer to 13:
int z = 0b0000_1101; The underscore is just to make the number more readable. It’s ignored by the Java compiler. |
|
command displays a string in console app
---------------------------- string vs char ---------------------------- escape quotes in Java |
System.out.println(weight);
---------------------------- "String" - string 'C' - char ---------------------------- System.out.println(“Jane Campion directed \”The Piano\” in 1993.”); |
|
Special Characters
Single quotation mark Double quotation mark Backslash Tab |
\' - Single quotation mark
\" - Double quotation mark \\ - Backslash \t - Tab |
|
Special Characters
Backspace Carriage return Formfeed Newline |
\b - Backspace
\r - Carriage return \f - Formfeed \n - Newline |
|
Concatenation operator in Java
|
+
System.out.println(“\”\’The Piano\’ is as peculiar and haunting as any” + “ film I’ve seen.\”\n\t— Roger Ebert, Chicago Sun-Times”); |
|
Determining the Length of a String
|
length() method
String cinematographer = “Stuart Dryburgh”; int nameLength = cinematographer.length(); |
|
change string case
|
toUpperCase();
toLowerCase(); String baines = “Harvey Keitel”; String change = baines.toUpperCase(); |
|
Searches for the first occurrence of a character or substring.
Searches for the last occurrence of a character or substring. |
indexOf( )
lastIndexOf( ) You can specify a starting point for the search using these forms: int indexOf(int ch, int startIndex) int lastIndexOf(int ch, int startIndex) int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex) |
|
switch statement
|
switch (grade) {
case ‘A’: System.out.println(“You got an A. Great job!”); break; case ‘B’: System.out.println(“You got a B. Good work!”); break; case ‘C’: System.out.println(“You got a C. What went wrong?”); break; default: System.out.println(“You got an F. You’ll do well in Congress!”); } |
|
Java 7 and switch
|
Java 7 adds support for using strings as the test variable in a switch-case statement
switch (command) { case "BUY": quantity += 5; balance -= 20; break; case "SELL": quantity -= 5; balance += 15; } |
|
enable Java 7 on NetBeans
|
Projects pane, right-click on desired project and click "Properties" from the pop-up menu
Project Properties dialog opens. Click "Sources" In "Source/Binary Format" select JDK 7 |
|
Conditional Operator
|
int numberOfEnemies = (skill > 5) ? 10 : 5;
(skill > 5) condition ? true value 10 false value 5 |
|
loop displays every number from 0 to 999 evenly divisible by 12
|
for (int dex = 0; dex < 1000; dex++) {
if (dex % 12 == 0) { System.out.println(“#: “ + dex); } } |
|
You can place loops inside each other.
In some cases, you might want to break out of both loops. How you do this? |
To make this possible, you have to give the outer loop a name as shown
int points = 0, target = 100; targetLoop: while (target <= 100) { for (int i = 0; i < target; i++) { if (points > 50) break targetLoop; points = points + i; } } <name>:<loop operator> |
|
Loop something for 1 minute
|
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000; while (true) { double x = Math.sqrt(index); long now = System.currentTimeMillis(); if (now > endTime) { break; } index++; } |
|
Java is flexible about where the
square brackets are placed when an array is being created -------------------------------- following example creates an array of strings and gives them initial values: |
String niceChild[];
String[] naughtyChild; -------------------------------- String[] reindeerNames = { “Dasher”, “Dancer”, “Prancer”, “Vixen”, “Comet”, “Cupid”, “Donder”, “Blitzen” }; |
|
create an array that has two dimensions
-------------------------------- Sorting an array is easy in Java because the Arrays class does all of the work. Arrays, which is part of the _______ |
boolean[][] selectedPoint = new boolean[50][50];
-------------------------------- java.util group of classes import java.util.* statement to make all the java.util classes available in the program |
|
All numeric arrays have the initial value
char boolean |
numeric - 0
char - '\0' boolean - false |
|
following example creates an array of strings and gives them initial values:
|
String[] reindeerNames = { “Dasher”, “Dancer”, “Prancer”, “Vixen”,
“Comet”, “Cupid”, “Donder”, “Blitzen” }; |
|
create an array that has two dimensions
|
boolean[][] selectedPoint = new boolean[50][50];
|
|
Sorting an array is easy in Java because the Arrays class does all of the work. Arrays, which is part of the _______
|
java.util group of classes
import java.util.* statement to make all the java.util classes available in the program |
|
The letters that appear most often in English are
--------------------------------- toCharArray() method |
E, R, S, T, L, N, C, D, M, and O, in that order.
----------------------------------------- When you’re working with strings, one useful technique is to put each character in a string into its own element of a character array. To do this, call the string’s toCharArray() method, which produces a char array with the same number of elements as the length of the string. |
|
In a multidimensional array, is it possible to use the length variable to measure different dimensions other than the first?
|
Yes
1st dimension data.length 2nd dimension data[0].length 3nd dimension data[0][0].length |
|
inheritance (def)
------------------------------------------------------------ inheritance (code) ------------------------------------------------------------ Can classes inherit from more than one class in Java? |
is a mechanism that enables one class to inherit all the behavior and attributes of another class
------------------------------------------------------------ public class ErrorCorrectionModem extends Modem { // program goes here } ------------------------------------------------------------ It’s possible with some programming languages (such as C++), but not in Java. |
|
casting (def)
------------------------------- statements cast a float value into an int: |
Converting information to a new form is called casting. Casting produces a new value that is a different type of variable or object than its source
-------------------------- float source = 7.06F; int destination = (int) source; |
|
subclass (def)
Class that sits on top of all Java class hierarchy superclass (def) |
a class that inherits from another class
Class that sits on top of all Java class hierarchy - Object superclass (def) - class that gives the inheritance is called a superclass |
|
When you are converting information from a larger variable type into a smaller type, you must explicitly cast it, as in the following statements
|
int xNum = 103;
byte val = (byte) xNum; |
|
Casting Objects
|
You can cast objects into other objects when the source and destination are
related by inheritance. One class must be a subclass of the other. To use an object in place of one of its subclasses, you must cast it explicitly with statements such as the following: Graphics comp = new Graphics(); Graphics2D comp2D = (Graphics2D) comp; |
|
There are classes in Java for each of the simple variable types
--------------------------------------------- following statement creates an Integer object with the value 5309: |
Boolean, Byte, Character, Double, Float, Integer, Long, and Short
---------------------------- Integer suffix = new Integer(5309); |
|
Integer suffix = new Integer(5309);
To get an int value from the preceding suffix object, the following statement could be used: |
int newSuffix = suffix.intValue();
|
|
When the string’s value could become an integer, this can be done using the
|
parseInt()
String count = “25”; int myCount = Integer.parseInt(count); |
|
How to add a cmd line argument to project in NetBeans?
|
Run, Set Project Configuration, Customize. The Project Properties window opens.
Enter <name of the class> as the Main Class and 169 in the Arguments field. |
|
Java’s autoboxing and unboxing capabilities
|
Java’s autoboxing and unboxing capabilities make it possible to use the basic data type and object forms of a value interchangeably.
Autoboxing casts a simple variable value to the corresponding class. Unboxing casts an object to the corresponding simple value. |
|
Can classes inherit from more than one class in Java?
|
It’s possible with some programming languages (such as C++), but not in Java.
|
|
protected variable (def)
statement (def) expression (def) |
You can use a protected variable only in the same class as the variable, any subclasses of that class, or classes in the same package.
statement (def) is a simple command that causes something to happen expression (def) is a statement that produces a value |
|
package (def)
|
group of related classes that serve a common purpose. An example is the java.util package
|
|
private variable (def)
|
private variable is restricted even further than a protected variable - you can use it only in the same class
|
|
When no access control is set on a variable
|
When no access control is set, the variable is
available only to classes in the same package. This is called default or package access. |
|
package access (def)
|
if variable is declared without any of the access modifiers (private, protected, public) the variable is available only to classes in the same package
|
|
access control (def)
|
Putting a statement such as public in a variable declaration statement is called access control because it determines how other objects made from other classes can use that variable—or if they can use it at all
|
|
class variables (def)
|
There are times when an attribute should describe an entire class of objects instead of a specific object itself.
Only one copy of the variable exists for the whole class. |
|
object variables (def) aka instance variable (def)
|
In Java (and in OOP in general) the objects have two kind of fields(variable).
Instance variables(or object variable/non-static fields) are fields that belongs to a particular instance of an object. Static variables (or class variable) are common to all the instance of the same class. public class Foobar{ static int counter = 0 ; //static variable..all instances of Foobar will share the same counter public int id; //instance variable. Each instance has its own id public Foobar(){ this.id = counter++; } } |
|
accessor methods (def)
|
accessor methods enable access to the private variable of an object from other objects
|
|
Can two methods have the same name?
|
Yes as long as they have different number or type of variables
void tauntUser() { System.out.println(“That has gotta hurt!”); } void tauntUser(String taunt) { System.out.println(taunt); } |
|
method’s signature (def)
|
methods have the same name, but the arguments differ the arguments to a method are called the method's signature
|
|
constructor methods (def)
|
handles the work required to create a new method
They have the task of initializing the object's data members |
|
Can constructor return a value?
|
No
Constructors are defined like other methods, except they cannot return a value public Virus() { String author = “Ignoto”; int maxFileSize = 30000; } |
|
Class Methods (def)
|
class methods are a way to provide functionality associated with an entire class instead of a specific object.
To make a method into a class method, use static in front of the method name, as in the following code: static void showVirusCount() { System.out.println(“There are “ + virusCount + “ viruses”); } |
|
Requirements for using public when defining multiple classes in 1 files?
|
If more than one class is defined in the same source file, only one of the classes can be
public. The other classes should not have public in their class statements. The name of the source code file must match the public class that it defines. |
|
overriding (def)
|
Creating a new method in a subclass to change behavior inherited from a superclass is called overriding.
You need to override a method any time the inherited behavior produces an undesired result. To do this, you give the method with the same name, return type, and argument as the method in the superclass |
|
Establishing Inheritance code
|
class AnimatedLogo extends JApplet {
// behavior and attributes go here } |
|
this keyword
|
used to refer to the current objec
this.title = “Cagney”; |
|
super keyword
|
serves a similar purpose: It refers to the immediate superclass of the object.
|
|
Vectors def
|
Vectors are like arrays, which also hold elements of related data, but they
can grow or shrink in size at any time. Vector class belongs to the java.util package of classes import java.util.Vector; The name of the class held by the vector is placed within < and > characters, as in this statement: Vector<String> victor = new Vector<String>(); |
|
You can add an object to a vector by calling its
|
add() method
victoria.add(“Vance”); victoria.add(“Vernon”); victoria.add(“Velma”); |
|
You retrieve elements from vectors by calling their
|
get() method with the
element’s index number as the argument: String name = victoria.get(1) This statement stores “Vernon” in the name string if the vector was initialized previously like this victoria.add(“Vance”); victoria.add(“Vernon”); victoria.add(“Velma”); |
|
To see if a vector contains an object in one of its elements, call its
|
contains() method with that object as an argument:
if (victoria.contains(“Velma”)) { System.out.println(“Velma found”); } |
|
Looping Through a Vector
|
Java includes a special for loop that makes it easy to load a vector and examine each of its elements in turn.
for (String name : victoria) { System.out.println(name); } |
|
awt (abbr)
|
Abstract Windowing Toolkit
|
|
Windows in Swing (def)
|
are simple containers that do
not have a title bar or any of the other buttons normally along the top edge of a GUI. JWindow |
|
Frames in Swing (def)
|
Frames are windows that include all the common windowing features users expect to find when they run software —such as buttons to close, expand, and shrink the window.
JFrame |
|
following statements create a subclass of JFrame
|
import javax.swing.*;
public class MainFrame extends JFrame { public MainFrame() { // set up the frame } } |
|
set Frame title method in Swing
|
setTitle()
setTitle(“Main Frame”); could use the super("Main Frame"); |
|
set size of a frame in Swing
pack() method for Frame |
setSize(350, 125);
sets the frame big enough to hold the preferred size of each component inside the frame |
|
define what happens when the X buttons in clicked call what method
|
setDefaultCloseOperation() method
|
|
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) - Exit the program when the button is clicked
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)—Close the frame and keep running the application. |
|
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE) |
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)—Keep the frame open and continue running.
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)—Close the frame and continue running. |
|
Nimbus def
|
Java 7 introduces an enhanced look and feel called Nimbus, but it must be turned on to be used in a class
UIManager.setLookAndFeel( “com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel” ); |
|
following statement creates a JButton called
okButton and gives it the text label OK |
JButton okButton = new JButton(“OK”);
After a component such as JButton is created, it should be added to a container by calling its add() method: add(okButton); |
|
FlowLayout class def
|
When you add components to a container, you do not specify the place in the container where the component should be displayed. The arrangement of components is decided by an object called a layout manager. The simplest of these managers is the FlowLayout class, which is part of the java.awt package.
FlowLayout flo = new FlowLayout(); |
|
JLabel component
|
displays information that the user cannot modify. This information can be text, a graphic, or both. These components are
often used to label other components in an interface, hence the name JLabel pageLabel = new JLabel(“Web page address: “, JLabel.RIGHT); JTextField pageAddress = new JTextField(20); FlowLayout flo = new FlowLayout(); setLayout(flo); add(pageLabel); add(pageAddress); |
|
JTextField component
|
an area where a user can enter a single line of text. You can set up the width of the box when you create the text field.
JLabel pageLabel = new JLabel(“Web page address: “, JLabel.RIGHT); JTextField pageAddress = new JTextField(20); FlowLayout flo = new FlowLayout(); setLayout(flo); add(pageLabel); add(pageAddress); |
|
JCheckBox component
|
component is a box next to a line of text that can be checked or unchecked by the user.
JCheckBox jumboSize = new JCheckBox(“Jumbo Size”); FlowLayout flo = new FlowLayout(); setLayout(flo); add(jumboSize); |
|
ButtonGroup object
|
To make a JCheckBox object part of a group, you have to create a ButtonGroup object
JCheckBox frogLegs = new JCheckBox(“Frog Leg Grande”, true); JCheckBox fishTacos = new JCheckBox(“Fish Taco Platter”, false); JCheckBox emuNuggets = new JCheckBox(“Emu Nuggets”, false); FlowLayout flo = new FlowLayout(); ButtonGroup meals = new ButtonGroup(); meals.add(frogLegs); meals.add(fishTacos); meals.add(emuNuggets); setLayout(flo); add(jumboSize); add(frogLegs); add(fishTacos); add(emuNuggets); |
|
JComboBox component
|
is a pop-up list of choices that also can be set up to receive text input
JComboBox profession = new JComboBox(); FlowLayout flo = new FlowLayout(); profession.addItem(“Butcher”); profession.addItem(“Baker”); profession.addItem(“Candlestick maker”); profession.addItem(“Fletcher”); profession.addItem(“Fighter”); profession.addItem(“Technical writer”); setLayout(flo); add(profession); |
|
JTextArea component
|
text field that enables the user to enter more
than one line of text JTextArea comments = new JTextArea(8, 40); FlowLayout flo = new FlowLayout(); setLayout(flo); add(comments); |
|
JPanel objects
|
The purpose of JPanel objects is to subdivide a display area into different groups of components
JPanel topRow = new JPanel(); FlowLayout flo = new FlowLayout(); setLayout(flo); add(topRow); |
|
What this computes?
int count = 0, i=0; do { count += i; i++; if (count > 5) break; } while ( i <= 4 ); |
6
|
|
The default manager for panels is
|
FlowLayout class in the java.awt package
Layout: from left to right, and then down to the next line when there’s no more space. |
|
GridLayout Manager
|
organizes all components in a container into a specific number of rows and columns
GridLayout grid = new GridLayout(2, 3); setLayout(grid); GridLayout class in the java.awt package |
|
BorderLayout Manager
|
arranges components at specific positions within the container that are identified by one of five directions: north, south, east, west, or center.
BorderLayout class, also in java.awt BorderLayout crisisLayout = new BorderLayout(); setLayout(crisisLayout); add(panicButton, BorderLayout.NORTH); add(dontPanicButton, BorderLayout.SOUTH); add(blameButton, BorderLayout.EAST); add(mediaButton, BorderLayout.WEST); add(saveButton, BorderLayout.CENTER); |
|
BoxLayout Manager
|
BoxLayout class is in javax.swing package
makes it possible to stack components in a single row horizontally or vertically. JPanel pane = new JPanel(); BoxLayout box = new BoxLayout(pane, BoxLayout.Y_AXIS); pane.setLayout(box); pane.add(panicButton); pane.add(dontPanicButton); pane.add(blameButton); pane.add(mediaButton); pane.add(saveButton); add(pane); |
|
Insets
|
As you are arranging components within a container, you can move components away from the edges of the container using Insets, an object that represents the border area of a container.
Insets class, which is part of the java.awt package Insets around = new Insets(10, 6, 10, 3); 10 pixels inside the top edge, 6 pixels inside the left, 10 pixels inside the bottom, and 3 pixels |
|
Graphics2D class extends the
|
Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for rendering 2-dimensional shapes, text and images
|
|
CardLayout Manager
|
CardLayout class lets you implement an area that contains different components at different times. A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays
|
|
GridBagLayout Manager
|
GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths.
|
|
GroupLayout Manager
|
GroupLayout is a layout manager that was developed for use by GUI builder tools, but it can also be used manually. GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for each dimension independently. Consequently, however, each component needs to be defined twice in the layout.
|
|
SpringLayout Manager
|
SpringLayout is a flexible layout manager designed for use by GUI builders. It lets you specify precise relationships between the edges of components under its control. For example, you might define that the left edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a second component. SpringLayout lays out the children of its associated container according to a set of constraints
|
|
Applets and Insets
|
import java.awt.*;
import java.applet.*; public class myInsets extends Applet { public Insets insets () { return new Insets (50, 50, 50, 50); } public void init () { setLayout (new BorderLayout ()); add ("Center", new Button ("Insets")); } public void paint (Graphics g) { Insets i = insets(); int width = size().width - i.left - i.right; int height = size().height - i.top - i.bottom; g.drawRect (i.left-2, i.top-2, width+4, height+4); g.drawString ("Insets Example", 25, size().height - 25); } } |
|
print on console Sop (code)
|
System.out.println
System.out.println("x++ * 3 = "); System.out.println("x++ * 3 = " + answer1); |
|
All objects in Java are sub classes of the
|
Object class
|
|
To use an object in place of one of its subclass, you must
|
cast it explicitly with statements such as the following:
Graphics comp = new Graphics(); Graphics2D comp2D = (Graphics2D) comp; cast a Graphocs object called comp into a Grpahic2D object. No information loss only gain the methods and variables the subclass defines. |
|
Syntax to get the value from an Integer object to an Integer variable
|
Integer suffix = new Integer(44);
int newSuffix = suffix.intValue(); |
|
What method can convert a String value to Integer
|
parseInt() method of the Integer class
String count = "25"; int myCount = Integer.parseInt(count); this will brake if count is not a valid integer value |
|
JApplet has _____ superclasses above it in the hierarchy
|
5
Applet Panel Container Component Object |
|
To refer to a constructor method of the superclass, as in ...
To refer to a variable of the superclass, as in ... To refer to a method of the superclass, as in ... |
To refer to a constructor method of the superclass, as in
super(“Adam”, 12); To refer to a variable of the superclass, as in super.hawaii = 20; To refer to a method of the superclass, as in super.dragnet() |
|
Includes for using Swing
|
import java.awt.*;
import java.awt.event.*; import javax.swing.*; |
|
class declaration code
|
class MyClass {
// field, constructor, and // method declarations } |
|
MyClass is a subclass of MySuperClass and that it implements the YourInterface interface code
|
class MyClass extends MySuperClass implements YourInterface {
// field, constructor, and // method declarations } |
|
Member variable def
local variables def parameters def |
Member variables in a class—these are called fields.
Variables in a method or block of code—these are called local variables. Variables in method declarations—these are called parameters. |
|
Overloading Methods def
|
Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").
|
|
constructors def
|
class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle
public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } To create a new Bicycle object called myBike, a constructor is called by the new operator: Bicycle myBike = new Bicycle(30, 0, 8); new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields. Although Bicycle only has one constructor, it could have others, including a no-argument constructor: public Bicycle() { gear = 1; cadence = 10; speed = 0; } |
|
Parameters def
Arguments def |
Parameters refers to the list of variables in a method declaration.
Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order. |
|
Arbitrary Number of Arguments
|
You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none. public Polygon polygonFrom(Point... corners) { int numberOfSides = corners.length; double squareOfSide1, lengthOfSide1; squareOfSide1 = (corners[1].x - corners[0].x) * (corners[1].x - corners[0].x) + (corners[1].y - corners[0].y) * (corners[1].y - corners[0].y); lengthOfSide1 = Math.sqrt(squareOfSide1); // more method body code follows that creates and returns a // polygon connecting the Points } |
|
Parameter Names def
|
When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.
The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor. A parameter can have the same name as one of the class's fields. If this is the case, the parameter is said to shadow the field. |
|
Passing Primitive Data Type Arguments def
|
Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Here is an example:
public class PassPrimitiveByValue { public static void main(String[] args) { int x = 3; // invoke passMethod() with x as argument passMethod(x); // print x to see if its value has changed System.out.println("After invoking passMethod, x = " + x); } // change parameter in passMethod() public static void passMethod(int p) { p = 10; } } When you run this program, the output is: After invoking passMethod, x = 3 |
|
an example of a method that accepts an array as an argument.
|
public Polygon polygonFrom(Point[] corners) {
// method body goes here } |
|
construct called varargs
|
You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name public Polygon polygonFrom(Point... corners) { int numberOfSides = corners.length; double squareOfSide1, lengthOfSide1; squareOfSide1 = (corners[1].x - corners[0].x) * (corners[1].x - corners[0].x) + (corners[1].y - corners[0].y) * (corners[1].y - corners[0].y); lengthOfSide1 = Math.sqrt(squareOfSide1); // more method body code follows that creates and returns a // polygon connecting the Points } |
|
You will most commonly see varargs with the printing methods; for example, this printf method:
|
public PrintStream printf(String format, Object... args)
allows you to print an arbitrary number of objects. It can be called like this: System.out.printf("%s: %d, %s%n", name, idnum, address); or like this System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, email) |
|
the parameter is said to shadow the field
|
Circle class and its setOrigin method:
public class Circle { private int x, y, radius; public void setOrigin(int x, int y) { ... } } Circle class has three fields: x, y, and radius. The setOrigin method has two parameters, each of which has the same name as one of the fields. Each method parameter shadows the field that shares its name. So using the simple names x or y within the body of the method refers to the parameter, not to the field. |
|
Passing Reference Data Type Arguments
|
Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.
consider a method in an arbitrary class that moves Circle objects: public void moveCircle(Circle circle, int deltaX, int deltaY) { // code to move origin of circle to x+deltaX, y+deltaY circle.setX(circle.getX() + deltaX); circle.setY(circle.getY() + deltaY); // code to assign a new reference to circle circle = new Circle(0, 0); } Let the method be invoked with these arguments: moveCircle(myCircle, 23, 56); Inside the method, circle initially refers to myCircle. The method changes the x and y coordinates of the object that circle references (i.e., myCircle) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called. |
|
How the Java compiler differentiates the constructors for one class
The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a |
based in the number and the type of arguments
no-argument constructor: Rectangle rect = new Rectangle(); |
|
default constructor def
|
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.
|
|
instantiation (def)
attributes (def) |
instantiation (def) - the process of creating an object from a class is called instantiation, which is why objects also are called instance
attributes (def) - are the data that differentiates one object from another. They can be used to determine the appearance, state, and other qualities of objects that belong to that class |
|
object variables
--------------------------- All objects in Java are sub classes of the --------------------------- instance |
instance variables
--------------------------- Object class --------------------------- usually called just methods, are used when you are working within an object of the class |
|
single class inheritance (def)
multiple inheritance (def) |
single class inheritance (def)
java's form of inheritance is called single inheritance because each java class can have only one superclass multiple inheritance (def) in c++ classes can have more than one superclass, and they inherit combined variables and methods from all those superclasses |
|
interface (def)
What Is an Interface? Code |
collection of methods that indicate a class has some behavior in addition to what it inherits from its superclasses
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows: interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before } |
|
packages (def)
What Is a Package? |
in java are way of grouping related classes and interfaces
group of related classes that serve a common purpose. An example is the java.util package Packages enable groups of classes to be available only if they are needed ad eliminate potential conflicts among class names in different groups of classes A package is a namespace that organizes a set of related classes and interfaces |
|
variables in java list (by logical type)
|
instance variables
class variables local variables |
|
getting user input basic code
|
import java.util.Scanner;
class apples P public static void main(String argsp[}){ Scanner bucky = new Scanner(System.in); System.out.println(bucky.nextLine()); } } |
|
==
equals(b) != (explain operators) |
== compares references, not values
equals(b) Compares values for equality != not equal |
|
Random generation
(code) |
import java.util.Random;
class diceRandom { public static void main(STring[] args) { Random dice = new Random(); int number; for (int counter=1; counter<= 10; counter++) { number = 1+dice.nextInt(6); System.out.println(number + "" ""); } } } |
|
prints a line (code)
concat strings imports what so we can read user input (code) |
prints a line - System.out.println(number + " ");
concat strings - + import java.util.Scanner; |
|
default class (cmd)
scanner class usages (cmd) |
public static void main (String args[])
Scanner scanMe = new Scanner(System.in); |
|
arrays as parameter for methods
initialize multidimensional array print a decimal by aways using two digits |
public static void change (int arr[])
int arr[][] = {{8,9,10,11},{-11,-12,-13}} String.format("%02d"); |
|
enchanced loop example
|
class enchancedFor {
public static void main (String[] args) { int bucky[] = { 3,4 }; int total = 0; for ( int x: bucky ){ total = total + x; } } } |
|
function with unkown amount of parameters
|
public static int average(int...number) {
int total=0; for (int x:numbers) total+=x; return total/numbers.lenght; } |
|
loop through a two dimensional array
|
..for (int row=0;row<x.lenght; row++)
for (int column=0;column<x[row].lenght; column++) {}.. |
|
nextLine();
|
used for inputting stirng
-------------------------------- import java.util.Random; class readScanner { public static void main(STring[] args) { Scanner scanMe = new Scanner(System.in); String Str = scanMe.nextLine(); } } } |
|
keyword for defining constants
literals (def and exmp) how you indicate long for a literal |
keyword for defining constants - final
naming convention capitalize letter final int TOUCHDOWN = 6; ---- you can work with values as literals in Java statment. It is any number, text, or other information that directly represnts a value int year = 2007; ---- how you indicate long for a literal - using the letter L pennytotal = pennytotal + 4L; |
|
how you indicate float point literals
of what type are float literals considere by defaul character literals |
how you indicate float point literals -
use a period character . as in double myGPA = 2.25; of what type are float literals considered by default double to change to float add letter F float piValue = 3.14115927; character literals a single char surrounded by quotation mark such as 'a', '$' |
|
new char
tab char backspace carriage return formfeed |
\n - new char
\t - tab char \b - backspace \r - carriage return \f - formfeed |
|
backslash
single quotation mark double quotation mark octal hex unicode |
\\ - backslash
\' - single quotation mark \" - double quotation mark \d -octal \xd - hex \ud - unicode |
|
enum (def)
|
An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public class EnumTest { Day day; //we can use enum day in the class } |
|
enum range
|
public enum fish {
tuna("tasty", "2"), salmon("nice", "3", flander("no like", "22"), snapper("not", "30"), eel("i like", "10"); private final String desc; private final String popular; //missing in this example are 2 methods for getting value of class members } ....some where in main class... for (fish people: EnumSet.range (fish.tuna, fish.flander)) { System.out.printf("%s\t%s", people, people.getDesc(), people.getPop()); } } |
|
before we use enumaration we need to import
java built class for GUI componets how to count how many time a class has been used |
import java.until.EnumSet;
import javax.swing.JOptionPane; how to count how many time a class has been used by using a static variable |
|
floyd triangle code
|
int countLine = 0, totalMembers = 15, countLast = 1;
for (int i = 0; i < totalMembers;) { System.out.print("\n"); for ( countLine = 1; countLine < countLast; countLine++) { System.out.print(i+1); i++; } countLast++; } |
|
show a dialog box for entering text
show a message dialog |
String fn = JOptionPane.showInputDialog("Enter first number!");
JOptionPane.showMessageDialog(null, sum, "Result", JOptionPane.PLAIN_MESSAGE); |
|
convert sting to int
-------------------------------------------------- What to import in order to use string -------------------------------------------------- Length of a string what to do (example) |
int num1 = Integer.parseInt(String);
-------------------------------------------------- What to import in order to use string import java.lang.String; -------------------------------------------------- import java.lang.String; Stirng s = null; s.lenght(); |
|
JMX abbr and def
JNDI abbr and def |
JMX - Java Management Extensions provides a standard way of managing resources such as applications, devices, and services.
JNDI - Java Naming and Directory Interface enables accessing the Naming and Directory Service such as DNS and LDAP. |
|
JAXP abbr and def
JAXB abbr and def |
JAXP - Introduces the Java API for XML Processing (JAXP) 1.4 technology.
JAXB - Introduces the Java architecture for XML Binding (JAXB) technology. |
|
RMI abbr and def
|
RMI - The Remote Method Invocation API allows an object to invoke methods of an object running on another Java Virtual Machine.
|
|
In the Java prog language, all source code is first written in ___________ files ending with the ______ extension. Those source files are then compiled into _________ by the __________. A .class file does not contain code that is native to your processor; it instead contains ________________ the machine language of the Java Virtual Machine. The _________ launcher tool then runs your application with an instance of the Java Virtual Machine
|
plain text files
java extension .class files javac compiler bytecodes javac |
|
data encapsulation (def)
|
Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation
|
|
Character and String Literals
|
Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as '\u'
single quotes' for char double quotes" for String literals |
|
In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal
|
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010; You can place underscores only between digits; you cannot place underscores in the following places: At the beginning or end of a number Adjacent to a decimal point in a floating point literal Prior to an F or L suffix In positions where a string of digits is expected |
|
Create an array with new
Alternatively, you can use the shortcut syntax to create and initialize an array |
newArray = new int[10];
int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; int[] elfSeniority; this create the array but doesn't not store any values in it int[] elfSeniority = new int[250]; creates an array and sets aside space for the values that it holds |
|
Copying Arrays
|
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) |
|
how to read a double
|
import java.util.Scanner;
.. Scanner container = new Scanner (System.in); double firstNum; System.out.println("Enter first number: "); firstNum = container.nextDouble(); |
|
The term "instance variable" is another name for
The term "class variable" is another name for |
The term "instance variable" is another name for
non-static field. The term "class variable" is another name for static field. |
|
how can you call a method from a class without first creating an instance of the class
|
if a method is declared with the static keyword, this method can be called without first creating an instance of the class.
That's because static methods are called from classes, not from objects |
|
Java requires that each public class is stored in a
|
Java requires that each public class is stored in a separate file
|
|
Consider the following statements:
int x = 3; int answer = x++ * 10; |
You might expect it to equal 40
Correct is 30 This statement is equal to int x = 3; int answer = x++ * 10; the following statement int answer = x * 10; x++; When a postfixed operator is used on a variable inside an expression, the variable’s value doesn’t change until after the expression has been completely evaluated |
|
The following order is used when working out an expression (precedence)
|
1. Incrementing and decrementing take place first.
2. Multiplication, division, and modulus division occur next from left to right. 3. Addition and subtraction follow. 4. Comparisons take place next. 5. The equal sign (=) is used to set a variable’s value. |
|
Evaluate
1) int y = 10; x = y * 3 + 5; 2) int x = 5; int number = x++ * 6 + 4 * 10 / 2; |
1) x = 35
2) we use x++ which meant that x is evaluated after the expression multiplication and division are handled from left to right. First, 5 is multiplied by 6, 4 is multiplied by 10, and that result is divided by 2 int number = 30 + 20 |
|
Java uses letter after variables to declare type
|
float pi = 3.14F;
F - indicates float L - long integers D - double floating -poing If letter is omited defaul is double. |
|
Java 7 and _ for organazing number
|
long salary = 264400000;
long salary = 264_400_000; The underscores are ignored, so the variable still equals the same value. |
|
compound assignments (def)
|
You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.
|
|
instanceof operator (def)
|
instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
|
|
Consider the following code snippet:
int i = 10; int n = i++%5 What are the values of i and n after the code is executed? ------------------------------------------------------------------------------ int i = 10; int n = i++%5; What are the values of i and n after the code is executed? |
i is 11, and n is 0.
------------------------ i is 11, and n is 1. |
|
enhanced for statement
|
class EnhancedForDemo {
public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } } } |
|
labeled break terminates the outer for loop (labeled "search")
|
search:
for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement |
|
continue statement
|
kips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop
steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count. String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { // interested only in p's if (searchMe.charAt(i) != ' ) continue; // process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); |
|
labeled continue statement skips the current iteration of an outer loop marked with the given label.
|
String searchMe = "Look for a substring in me";
String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test; } } foundIt = true; break test; } System.out.println(foundIt ? "Found it" : "Didn't find it"); |
|
class declaration short
------------------------------- class declaration full (without modifiers) |
class MyClass {
// field, constructor, and // method declarations } -------------------------------------- class MyClass extends MySuperClass implements YourInterface { // field, constructor, and // method declarations } |
|
Access Modifiers list
|
public modifier—the field is accessible from all classes.
private modifier—the field is accessible only within its own class. |
|
typical method declaration
method signature def |
public double calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons) { //do the calculation here } the method's name and the parameter types |
|
class contains constructors def
|
class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } To create a new Bicycle object called myBike, a constructor is called by the new operator: Bicycle myBike = new Bicycle(30, 0, 8); You can have multiple constructors as long as they have diff. argument list |
|
You don't have to provide any constructors for your class, but you must be careful when doing this. Because....
|
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
|
|
example of a method that accepts an array as an argument
|
public Polygon polygonFrom(Point[] corners) {
// method body goes here } |
|
You will most commonly see varargs with the printing methods; for example
|
public PrintStream printf(String format, Object... args)
allows you to print an arbitrary number of objects. It can be called like this: System.out.printf("%s: %d, %s%n", name, idnum, address); or like this System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, email); |
|
Parameter Names
|
When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.
|
|
Passing Primitive Data Type Arguments
|
Primitive arguments, such as an int or a double, are passed into methods by value
This means that any changes to the values of the parameters exist only within the scope of the method. public class PassPrimitiveByValue { public static void main(String[] args) { int x = 3; // invoke passMethod() with x as argument passMethod(x); // print x to see if its value has changed System.out.println("After invoking passMethod, x = " + x); } // change parameter in passMethod() public static void passMethod(int p) { p = 10; } } When you run this program, the output is: After invoking passMethod, x = 3 |
|
Passing Reference Data Type Arguments
|
Reference data type parameters, such as objects, are also passed into methods by value.
When the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level. public void moveCircle(Circle circle, int deltaX, int deltaY) { // code to move origin of circle to x+deltaX, y+deltaY circle.setX(circle.getX() + deltaX); circle.setY(circle.getY() + deltaY); // code to assign a new reference to circle circle = new Circle(0, 0); } Let the method be invoked with these arguments: moveCircle(myCircle, 23, 56) Inside the method, circle initially refers to myCircle. The method changes the x and y coordinates of the object that circle references (i.e., myCircle) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called. |
|
Java 7 adds support for using _________ as the test variable in a switch-case statement. (Java 7 and switch)
|
..
String command = “BUY”; .. switch (command) { case “BUY”: quantity += 5; balance -= 20; break; case “SELL”: quantity -= 5; balance += 15; } |
|
Enable Java 7 support for a project
|
1)Projects pane, right-click your project
2)click Properties from pop-up menu 3)Project Properties dialog opens 4)In the Categories pane, click Sources 3)In the Source/Binary Format drop-down, choose JDK7 |
|
ternary operator def
|
int numberOfEnemies = (skillLevel > 5) ? 10 : 5;
ternary expression has five parts: . The condition to test, surrounded by parentheses, as in (skillLevel > 5) . A question mark (?) . The value to use if the condition is true . A colon (:) . The value to use if the condition is false |
|
get current time and date
|
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY); int minute = now.get(Calendar.MINUTE); int month = now.get(Calendar.MONTH) + 1; int day = now.get(Calendar.DAY_OF_MONTH); int year = now.get(Calendar.YEAR); |
|
JApplet has _____ superclasses above it in the hierarchy + list
|
5
Applet Panel Container Component Object |
|
Static methods def
|
Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args) A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field: public static int getNumberOfBicycles() { return numberOfBicycles; } |
|
Not all combinations of instance and class variables and methods are allowed:
|
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to. |
|
Constants def
|
The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter): static final double PI = 3.141592653589793; |
|
compile-time constant def
|
If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
|
|
static initialization blocks (def)
|
If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example: static { // whatever code is needed for initialization goes here } |
|
alternative to static blocks
|
you can write a private static method:
class Whatever { public static varType myVar = initializeClassVariable(); private static varType initializeClassVariable() { // initialization code goes here } } The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable. |
|
java swing hello world with JOptionPane and what import?
|
package web;
import javax.swing.JOptionPane; public class popUp { public static void main (String args[]) { JOptionPane myIO = new JOptionPane(); myIO.showMessageDialog(null, "Hello World!"); } } //we can just do JOptionPane.showMessageDialog(null, "Hello World!"); as showMessageDialog is static method |
|
What is the result?
public class tickyMath { public static void main (String args[]) { int a = 2; int b = 3; a *= b + 1; System.out.println("Result of a *= b + 1 is " + a ); } } |
a *= b + 1 = 8
<=> a = a * b + 1 |
|
java swing read input from user
|
Use showInputDialog();
------------------------------------- import javax.swing.JOptionPane; public class popUpInput { public static void main (String args[]){ JOptionPane myIO = new JOptionPane(); String inputText = myIO.showInputDialog("Please enter your name:"); String outputText = "You entered: " + inputText; myIO.showMessageDialog(null, outputText); } } |
|
recursive method to calculate fibonachi
|
public static long fib(int n) {
if (n <= 2) return 1; return fib(n - 1) + fib(n - 2); } |
|
recursive method to calculate factorial
|
public static long factorial(int n) {
// The bottom of the recursion if (n == 0) { return 1; } // Recursive call: the method calls itself else { return n * factorial(n - 1); } } |
|
iterative method to calculate factorial
|
public static long factorial(int n) {
long result = 1; for (int i = 1; i <= n; i++) { result = result * i; } return result; } |
|
Overriding Methods def
|
When a method is defined in a subclass and its superclass, the subclass method is used.
This enables a subclass to change, replace or completely wipe out some of the behavior or attributes of its superclass |
|
this and super in a Subclass
|
this keyword is used to refer to the current object.
super keyword serves a similar purpose: It refers to the immediate superclass of the object. You can use super in several different ways: . To refer to a constructor method of the superclass, as in super(“Adam”, 12); . To refer to a variable of the superclass, as in super.hawaii = 50; . To refer to a method of the superclass, as in super.dragnet(); |
|
random example
x / 16 is equal to |
private Random random = new Random();
x / 16 is equal to x shifted right by 4 as x >> 4 |