Java Fundamentals - Chapter 2 Review (Parts of a Java Program, Print/API, Variables and Literals, Primitives, Arithmetic, Conversions, final, String, Scope, Comments, Style, Input, Dialog Boxes, Common Errors)
2.1 The Parts of a Java Program
A Java program must have at least one class definition, marked by
public class ClassName.The
mainmethod (public static void main(String[] args)) is the entry point for Java applications.//denotes a single-line comment;/* ... */denotes multi-line comments.Files:
.javafor source code;.classfor bytecode (afterjavac). Run withjava ClassName.Braces
{}enclose bodies; statements end with semicolons;, but headers and braces do not.Java is case-sensitive.
2.2 The print and println Methods, and the Java API
The Java API (Application Programmer Interface) is a library of prewritten classes.
System.out.println("string")prints the string and moves the cursor to the next line.System.out.print("string")prints the string without moving to the next line.Escape sequences like
\n(newline) and\t(horizontal tab) control output formatting within strings.
2.3 Variables and Literals
Variable: a named memory location to hold data of a specific type. Declared before use (e.g.,
int value;).Literal: a direct value in code (e.g.,
5,"Hello").String concatenation: The
+operator combines strings and automatically converts non-strings to strings for output.Identifiers (programmer-defined names) must start with a letter,
_, or$, followed by letters, digits,_, or$(no spaces, case-sensitive, cannot start with a digit).
2.4 Primitive Data Types
Data types determine memory usage and format.
Numeric types:
byte(1 byte),short(2 bytes),int(4 bytes, default for integers),long(8 bytes, suffixL).Floating-point types:
float(4 bytes, suffixF),double(8 bytes, default for floating-points).boolean: holdstrueorfalse.char: holds a single character (2 bytes, uses Unicode), enclosed in single quotes (e.g.,'A').String: not a primitive type; it's a class type (object) holding references to text data.
2.5 Arithmetic Operators
Binary arithmetic operators:
+(addition),-(subtraction),*(multiplication),/(division),%(modulus/remainder).Integer division:
5 / 2results in2(fraction discarded if both operands are integers). Use5.0 / 2or casting ((double)5 / 2) for floating-point results.Operator precedence:
*,/,%evaluate before+,-. Parentheses()override precedence.
2.6 Combined Assignment Operators
Shorthand operators combine arithmetic with assignment, e.g.,
x += 5is equivalent tox = x + 5.Other examples:
-=,*=,/=,%=.
2.7 Conversion between Primitive Data Types
Widening conversion: Automatic from lower-ranked to higher-ranked type (e.g.,
inttodouble).Narrowing conversion: Manual using a cast operator
(type)expression(e.g.,(int)12.9gives12). May result in loss of precision.Mixed-type expressions: Java promotes lower-ranked operands to the higher-ranked type; the result is of the higher type.
2.8 Creating Named Constants with final
The
finalkeyword creates a named constant, whose value cannot be changed after initialization.Syntax:
final double INTEREST_RATE = 0.069;.Constants are typically uppercase with underscores (e.g.,
MATH.PI).
2.9 The String Class
Stringvariables hold references toStringobjects, not the actual characters.Common methods:
length()(returnsint),charAt(index)(returnschar),toLowerCase()/toUpperCase()(return newStringobjects).Stringobjects are immutable (cannot be changed after creation).
2.10 Scope
Scope defines where a variable is accessible.
Local variables (declared inside a method) are accessible from their declaration point to the end of the method's block.
Variables must be declared before use. Cannot have two local variables with the same name in the same scope.
2.11 Comments
Compiler ignores comments, which are for human readability.
Types:
//(single-line),/* ... */(multi-line),/** ... */(documentation comments for Javadoc).
2.12 Programming Style
Emphasizes code readability through consistent indentation, spacing, and appropriate use of blank lines.
Indent code blocks within braces.
2.13 Reading Keyboard Input
Use the
Scannerclass to read input fromSystem.in.import java.util.Scanner;is required.Create a
Scannerobject:Scanner keyboard = new Scanner(System.in);.Methods:
nextInt(),nextDouble(),nextLine()(reads an entire line including newline character).Issue:
nextLine()afternextInt()/nextDouble()can read a leftover newline. Solution: consume the newline with an extrakeyboard.nextLine().
2.14 Dialog Boxes
Use
JOptionPanefor graphical input/output dialogs.import javax.swing.JOptionPane;is required.JOptionPane.showMessageDialog(null, "Message");for displaying messages.String input = JOptionPane.showInputDialog("Prompt");for getting string input.Input from
showInputDialogis always aStringand must be parsed to numeric types (e.g.,Integer.parseInt(input)).Use
System.exit(0);to terminate dialog-based programs.
2.15 Common Errors to Avoid
Mismatched braces, quotes, parentheses.
Misspelling keywords (Java is case-sensitive, keywords are lowercase).
Using reserved Java keywords as identifiers.
Inconsistent spelling/case for variable names.
Forgetting semicolons at statement ends.
Integer division when floating-point results are desired.
Incorrect operator precedence (use parentheses).
Not importing necessary classes (
Scanner,JOptionPane).Not converting
Stringinput to numeric types when using dialog boxes.
2.1 The Parts of a Java Program
A Java program typically includes at least one class definition with a main method as its entry point, uses comments for readability, and is compiled from .java source files into .class bytecode files.
2.2 The print and println Methods, and the Java API
Java's API provides prewritten classes, while System.out.print and System.out.println are used to display output to the console, often utilizing escape sequences for formatting.
2.3 Variables and Literals
Variables are named memory locations holding specific data types, literals are direct values in code, and identifiers are programmer-defined names following specific naming rules.
2.4 Primitive Data Types
Java offers several primitive data types, including numeric (byte, short, int, long, float, double), boolean for logical values, and char for single characters, in addition to the String class for text.
2.5 Arithmetic Operators
Arithmetic operators like +, -, *, /, and % perform calculations, with specific rules for integer division and operator precedence that can be overridden by parentheses.
2.6 Combined Assignment Operators
Shorthand combined assignment operators (+=, -=, *=, /=, %=) provide a concise way to perform an arithmetic operation and assign the result back to the same variable.
2.7 Conversion between Primitive Data Types
Java supports automatic widening conversions from lower to higher-ranked types, and manual narrowing conversions using a cast operator, with mixed-type expressions promoting operands to a common higher type.
2.8 Creating Named Constants with final
The final keyword is used to declare named constants whose values cannot be changed after initialization, typically named in uppercase with underscores.
2.9 The String Class
The String class represents sequences of characters as immutable objects and provides methods for common operations like length(), charAt(), toLowerCase(), and toUpperCase().
2.10 Scope
Scope defines the region of a program where a variable is accessible, with local variables being accessible from their declaration to the end of their enclosing method block and requiring unique names within that scope.
2.11 Comments
Comments are ignored by the compiler and are used to provide human-readable explanations within the code, coming in single-line (//), multi-line (/* ... */), and documentation (/** ... */) forms.
2.12 Programming Style
Programming style emphasizes consistent formatting, indentation, and spacing to enhance code readability and maintainability.
2.13 Reading Keyboard Input
The Scanner class from java.util allows a Java program to read various data types, such as integers, doubles, and strings, from keyboard input.
2.14 Dialog Boxes
The JOptionPane class from javax.swing enables the creation of standard dialog boxes for graphical input and output, requiring explicit parsing of string input to numeric types and program termination with System.exit(0).
2.15 Common Errors to Avoid
Common programming errors include syntax mistakes like mismatched delimiters, misspellings, incorrect use of keywords, neglecting semicolons, and issues related to type conversion or operator precedence.