0% found this document useful (0 votes)
14 views

Learn Advanced Java Programming With Beginners Md Pulok pdf download

The document provides an overview of advanced Java programming, covering essential concepts such as object-oriented nature, platform independence, and Java's syntax. It includes guidance on getting started with Java, including installation of the JDK, setting up an IDE, and understanding the Java development life cycle. Additionally, it highlights the importance of practicing through projects and engaging with the Java community for continuous learning.

Uploaded by

lwafaziurka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Learn Advanced Java Programming With Beginners Md Pulok pdf download

The document provides an overview of advanced Java programming, covering essential concepts such as object-oriented nature, platform independence, and Java's syntax. It includes guidance on getting started with Java, including installation of the JDK, setting up an IDE, and understanding the Java development life cycle. Additionally, it highlights the importance of practicing through projects and engaging with the Java community for continuous learning.

Uploaded by

lwafaziurka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Learn Advanced Java Programming With Beginners

Md Pulok download

https://ebookbell.com/product/learn-advanced-java-programming-
with-beginners-md-pulok-57723846

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Mastering Kotlin Learn Advanced Kotlin Programming Techniques To Build


Apps For Android Ios And The Web Nate Ebel

https://ebookbell.com/product/mastering-kotlin-learn-advanced-kotlin-
programming-techniques-to-build-apps-for-android-ios-and-the-web-nate-
ebel-36179840

Mastering Unity Scripting Learn Advanced C Tips And Techniques To Make


Professionalgrade Games With Unity Alan Thorn

https://ebookbell.com/product/mastering-unity-scripting-learn-
advanced-c-tips-and-techniques-to-make-professionalgrade-games-with-
unity-alan-thorn-5068070

Mastering Kotlin Learn Advanced Kotlin Programming Techniques To Build


Apps For Android Ios And The Web Nate Ebel

https://ebookbell.com/product/mastering-kotlin-learn-advanced-kotlin-
programming-techniques-to-build-apps-for-android-ios-and-the-web-nate-
ebel-10566366

Mastering Unity Scripting Learn Advanced C Tips And Techniques To Make


Professionalgrade Games With Unity Alan Thorn

https://ebookbell.com/product/mastering-unity-scripting-learn-
advanced-c-tips-and-techniques-to-make-professionalgrade-games-with-
unity-alan-thorn-10825794
Mastering Unity Scripting Learn Advanced C Tips And Techniques To Make
Professionalgrade Games With Unity Alan Thorn

https://ebookbell.com/product/mastering-unity-scripting-learn-
advanced-c-tips-and-techniques-to-make-professionalgrade-games-with-
unity-alan-thorn-50950802

The Cool Stuff In Premiere Pro Learn Advanced Editing Techniques To


Dramatically Speed Up Your Workflow 2nd Edition Jarle Leirpoll

https://ebookbell.com/product/the-cool-stuff-in-premiere-pro-learn-
advanced-editing-techniques-to-dramatically-speed-up-your-
workflow-2nd-edition-jarle-leirpoll-6788042

Harmony At The Piano Using Keyboard Harmony To Learn Advanced Piano


Music Teamira 1st Edition Ken Johansen

https://ebookbell.com/product/harmony-at-the-piano-using-keyboard-
harmony-to-learn-advanced-piano-music-teamira-1st-edition-ken-
johansen-52220456

Modern Web Applications With Next Js Learn Advanced Techniques To


Build And Deploy Modern Scalable And Production Ready React
Applications With Next Js Shubham Jain

https://ebookbell.com/product/modern-web-applications-with-next-js-
learn-advanced-techniques-to-build-and-deploy-modern-scalable-and-
production-ready-react-applications-with-next-js-shubham-jain-53850164

Mastering Opencv With Python Use Numpy Scikit Tensorflow And


Matplotlib To Learn Advanced Algorithms For Machine Learning Through A
Set Of Practical Projects Ayush Vaishya

https://ebookbell.com/product/mastering-opencv-with-python-use-numpy-
scikit-tensorflow-and-matplotlib-to-learn-advanced-algorithms-for-
machine-learning-through-a-set-of-practical-projects-ayush-
vaishya-53747356
Table of Contents
Java intro
1. ​General Overview:
2. ​ bject-Oriented Nature:
O
3. ​ latform Independence:
P
4. ​Java Virtual Machine (JVM):
5. ​ yntax Simplicity:
S

6. ​ utomatic Memory Management:


A

7. ​ trongly Typed Language:


S

8. ​ xception Handling:
E

9. ​Rich Standard Library:


10. ​Multi-threading Support:
JAvA Get StARteD

Java Syntax
Java Output

Java Comments

JAvA VARiABleS

Java Data Types


JAvA Type CAStinG

JAvA OpeRAtoRS

JAvA StRinGS

JAvA MAth
Java Booleans

Java If...Else

Java Switch

public class SwitchExample {

String dayName;

case 1:
case 2:
case 3:

case 4:

case 5:

case 6:

Java While Loop

Java For Loop

Java Break/Continue
JAVA ARRAYS

Java Methods

JAvA MethoD PARAmeteRS

JAvA MethoD OveRloADinG

JAvA ReCuRSion

Java OOP

JAVA ClASSeS/OBJeCtS
JAvA ClASS AttRiButeS

JAvA ClASS MethoDS

JAvA ConStRuCtoRS

Java Modifiers
JAvA EnCApSulAtion
Java Packages / API

Java Inheritance
Java Polymorphism

Java Inner Classes


JAvA ABStRACtion

Java Interface
Java Enums
Java Date
JAVA ARRAYLiSt
JAvA LinkeDLiSt

Java HashMap
Java HashSet

Java Iterator

JAvA WRAppeR ClASSeS


Java Exceptions

Java RegEx
JAVA ThReADS

JAVA LAmBDA
JAVA Files

Java intro
An introduction to Java typically begins with an overview of the language
and its key features.
1. General Overview:
Purpose: Java is a versatile, object-oriented, and platform-
independent programming language. It was designed to be simple,
secure, and portable across various platforms.
Origin: Developed by James Gosling and his team at Sun
Microsystems in the mid-1990s, Java was initially created for
programming consumer electronic devices.
2. Object-Oriented Nature:
Objects: In Java, everything is treated as an object. Objects have
both data (attributes) and methods (functions) that can operate on the
data. This approach encourages modular and reusable code.
3. Platform Independence:
Write Once, Run Anywhere (WORA): Java code can be written on
one platform and executed on any other platform without
modification. This is achieved through the use of the Java Virtual
Machine (JVM), which provides a layer of abstraction between the
Java program and the underlying hardware.
4. Java Virtual Machine (JVM):
Execution Environment: JVM is a crucial component of Java that
interprets Java bytecode and executes it on the host machine. This
enables the portability of Java programs across different platforms.
5. Syntax Simplicity:
Readability: Java syntax is designed to be clear and easy to read. It
borrows much of its syntax from C and C++, making it familiar to
many programmers.
6. Automatic Memory Management:
Garbage Collection: Java includes an automatic garbage collector
that automatically reclaims memory occupied by objects that are no
longer in use. This simplifies memory management for developers.
7. Strongly Typed Language:
Data Types: Java is a strongly typed language, meaning that
variables must be declared with a specific data type. This helps catch
errors at compile-time and enhances code reliability.
8. Exception Handling:
Robustness: Java has a robust exception-handling mechanism that
allows developers to handle runtime errors gracefully. This
contributes to the overall stability of Java applications.
9. Rich Standard Library:
API (Application Programming Interface): Java comes with a vast
and comprehensive standard library (Java API) that provides pre-
built functionality for various tasks. This allows developers to focus
on application-specific logic rather than low-level details.
10. Multi-threading Support:
Concurrent Execution: Java supports multi-threading, allowing
developers to create applications that can perform multiple tasks
concurrently. This is crucial for building responsive and efficient
programs.
In summary, Java is a powerful and versatile programming language
known for its platform independence, object- oriented paradigm,
simplicity, and robust features. Its wide range of applications spans from
web development to mobile app development, making it a popular choice
in the software development industry.
Let's start with a simple "Hello, World!" program in Java:

public class HelloWorld {


public static void main(String[] args) { System.out.println("Hello, World!");
}
}

Now, let's break down this example:


1. public class HelloWorld : This line declares a class named
HelloWorld. In Java, everything is defined within a class, and the
filename must match the class name.
2. public static void main(String[] args) : This is the main method. It
is the entry point of the Java program. When you run a Java
application, it starts executing from the main method.
3. System.out.println("Hello, World!"); : This line prints the string
"Hello, World!" to the console. System.out refers to the standard
output stream, and println is a method that prints a line to the
console.
Now, let's discuss what "Java intro" generally means:
Java Introduction: Java is a high-level, object-oriented, and versatile
programming language developed by Sun Microsystems (now owned by
Oracle). It is known for its platform independence, which means that Java
programs can run on any device that has a Java Virtual Machine (JVM).
Here are some key points about Java:
1. Write Once, Run Anywhere (WORA) : Java programs are compiled
into an intermediate bytecode that can be executed on any device with a
Java Virtual Machine (JVM). This promotes portability and allows
developers to write code that can run on various platforms without
modification.
2. Object-Oriented : Java follows the principles of object- oriented
programming (OOP), which includes concepts like encapsulation,
inheritance, and polymorphism. This promotes code organization,
reusability, and modularity.
3. Platform Independence : Java applications are platform- independent
because they are executed by the JVM, which provides a layer of
abstraction between the Java program and the underlying hardware.
This makes Java suitable for a wide range of devices and operating
systems.
4. Rich Standard Library : Java comes with a comprehensive standard
library that provides ready-to-use classes and methods for various
common tasks. This library simplifies development and reduces the
need for developers to write everything from scratch.
5. Security : Java has built-in security features, such as the Java sandbox,
which helps protect against potentially harmful code. This makes Java a
popular choice for developing secure applications.
6. Community and Ecosystem : Java has a large and active developer
community, and there is a vast ecosystem of libraries, frameworks, and
tools available to Java developers. This community support contributes
to the language's longevity and evolution.
Overall, Java is widely used in enterprise applications, web development,
mobile app development (Android), and more. Its simplicity, portability,
and robustness have contributed to its popularity in the software
development industry.
JAvA Get StARteD
Getting started with Java involves understanding the essential steps to set
up your development environment, grasp the basic concepts, and become
familiar with the tools you'll be using.

1. Install Java Development Kit (JDK) :

The first step is to install the Java Development Kit (JDK) on your
machine. The JDK includes the Java Runtime Environment (JRE)
and tools needed for Java development. You can download the JDK
from the official Oracle website or use alternative distributions like
OpenJDK.

2. Set Up Environment Variables:

After installing the JDK, you need to set up environment variables.


This involves adding the JDK's "bin" directory to the system's PATH
variable. This allows the command line to recognize Java commands,
such as javac (Java compiler) and java (Java interpreter).

3. Choose an Integrated Development Environment (IDE):

While Java code can be written in a simple text editor, most


developers prefer using an Integrated Development Environment
(IDE) for a more efficient and feature-rich coding experience.
Popular choices include Eclipse, IntelliJ IDEA, and NetBeans.

4. Understand Java's Basic Structure:

Java programs are organized into classes. A class contains data


(fields) and methods (functions) that operate on that data. The main
method is the entry point for a Java application, and it's where the
program execution begins.

5.
Learn Object-Oriented Programming (OOP) Concepts:
Java is an object-oriented programming language, and understanding
OOP concepts is crucial. Concepts like encapsulation, inheritance,
and polymorphism are fundamental to writing effective Java code.
6. Know the Java Development Life Cycle:

Java programs go through a development life cycle, including


writing code, compiling it with the javac compiler, and executing it
using the java interpreter. Understanding this cycle is essential for
troubleshooting and debugging.

7. Explore the Java Standard Library (Java API):

Java comes with a vast Standard Library known as the Java API
(Application Programming Interface). Familiarize yourself with the
classes and methods provided by the API, as they can save you time
and effort when coding.

8. Use Version Control Systems:

Version control systems like Git are integral to collaborative


development. Learn the basics of Git to manage and track changes in
your Java projects.

9. Join the Java Community:

Java has a vibrant and supportive community. Participate in forums,


read blogs, and follow social media channels to stay updated on the
latest developments, best practices, and tips from experienced Java
developers.

10. Practice and Build Projects:

The best way to learn Java is by hands-on practice. Start with small
projects, gradually increasing complexity. Building real-world
applications enhances your skills and solidifies your understanding of
Java concepts.
In summary, getting started with Java involves installing the JDK, setting
up your development environment, choosing an IDE, understanding
Java's basic structure and OOP concepts, exploring the Java API, using
version control, engaging with the community, and, most importantly,
practicing by working on projects. As you gain experience, you'll become
more comfortable with Java development and be ready to tackle more
advanced topics.
Java Syntax
Java syntax refers to the set of rules and conventions that dictate how Java
programs should be written. Understanding Java syntax is crucial for
creating well-formed and functional Java code.
1. Case Sensitivity:
Java is case-sensitive, meaning that uppercase and lowercase letters
are treated as distinct. For example, variable and Variable are
considered different identifiers.
2. Class Declaration:
In Java, a program is typically organized into classes. The basic
structure of a class includes the keyword class followed by the class
name. The body of the class is enclosed in curly braces {}.
3. Method Declaration:
Methods define the behavior of a class. A method declaration
includes the return type, method name, and parameters (if any). The
method body contains the code that defines the functionality of the
method.
4. Comments:
Comments in Java are used to add explanatory notes to the code.
They are ignored by the compiler and are for the benefit of
developers. Single-line comments start with //, and multi-line
comments are enclosed between /* and */.
5. Variables and Data Types:
Variables are containers for storing data in a program. Java requires
explicit declaration of variables, specifying the data type (e.g., int,
double). Variable names must adhere to certain naming conventions
and cannot start with a number.
6. Statements and Expressions:
Statements are individual instructions in Java, and expressions are
combinations of variables, operators, and literals that evaluate to a
single value. Statements typically end with a semicolon ; .
7. Control Flow Statements:
Java supports various control flow statements like if, else, switch, for,
while, and do-while. These statements control the flow of execution in
a program based on certain conditions.

8. Object Instantiation:
In Java, objects are instances of classes. To create an object, the new
keyword is used, followed by the class constructor. The constructor
initializes the object and allocates memory.

9. Inheritance:
Inheritance is a fundamental concept in object-oriented programming
(OOP). In Java, a class can inherit properties and behaviors from
another class using the extends keyword.

10. Exception Handling:


Java provides a robust mechanism for handling exceptions. The try,
catch, finally, and throw keywords are used to manage exceptional
conditions in the code.

11. Packages and Imports:


Java uses packages to organize classes into namespaces. The package
keyword is used to declare a package, and the import keyword is used
to bring classes from other packages into the current scope.

12. Access Modifiers:


Java uses access modifiers like public, private, and protected to
control the visibility of classes, methods, and variables. This helps
enforce encapsulation and access control.
In summary, Java syntax encompasses rules for defining classes, methods,
variables, control flow, and other elements of a Java program. Adhering to
these syntax rules ensures that the code is readable, maintainable, and
functions as intended.
Let's start with a simple Java code example, and then I'll explain what Java
syntax means: public class BasicSyntaxExample { public static void
main(String[] args) {
// Variable declaration and initialization int
number = 10; String greeting = "Hello,
Java!"; // Conditional statement if (number >
5) {
System.out.println(greeting); } else {
System.out.println("Number is not greater than 5."); }
// Looping statement for
(int i = 0; i < 3; i++) {
System.out.println("Loop iteration: " + i); }
}
}
Explanation of Java Syntax:
1. Class Declaration: In Java, a program is typically organized into
classes. The public class BasicSyntaxExample declares a class named
BasicSyntaxExample.
2. Method Declaration: The public static void main(String[] args)
declares the main method. The main method is the entry point for Java
programs.
3. Variable Declaration and Initialization: In Java, variables are declared
with a specific data type. For example, int number = 10; declares an
integer variable named number and initializes it with the value 10.
Similarly, String greeting = "Hello, Java!"; declares a String variable
named greeting and initializes it with a string.
4. Conditional Statement (if-else): The if (number > 5) is a conditional
statement. If the condition is true, the code inside the block following
if is executed; otherwise, the code inside the block following else is
executed.
5. Print Statement: System.out.println is used to print output to the
console. In the example, it prints either the value of the greeting
variable or a message depending on the condition.
6. Looping Statement (for): The for (int i = 0; i < 3; i++) is a loop that
iterates three times. It initializes a variable i to 0, executes the loop
body as long as i is less than 3, and increments i after each iteration.
In summary, Java syntax refers to the set of rules that dictate how Java
programs are written and structured. It includes rules for declaring
variables, defining methods and classes, using conditional statements and
loops, and more. Understanding and following Java syntax is crucial for
writing correct and readable Java code.
Java Output
Java output refers to the information or results produced by a Java
program during its execution. Output in Java is typically generated to the
console, but it can also be directed to other destinations such as files,
databases, or graphical user interfaces.
1. Console Output: The most straightforward way for a Java program to
produce output is by using the System.out.println() method. This method
sends text to the standard output stream (usually the console), followed
by a newline character. The println stands for "print line."
2. Print Formatting: Java provides various ways to format output, allowing
developers to control the appearance of text. The printf() method is
commonly used for formatted output, allowing placeholders for variables
and specifying their format.
3. Standard Output and Standard Error: Java distinguishes between
standard output (System.out) and standard error (System.err). While both
are typically displayed on the console, they serve different purposes.
Standard output is for normal program output, while standard error is for
error messages or exceptional conditions.
4. Concatenation: Output in Java can be created by concatenating (joining
together) strings. The + operator is used for string concatenation,
allowing the combination of text and variable values to form a complete
output.
5. Escape Sequences: Java supports escape sequences, special characters
preceded by a backslash, to represent non-printable characters or to
control the formatting of the output. For example, \n represents a newline
character, and \t represents a tab character.
6. Logging:
Java provides a logging framework, the Java Logging API, for
capturing various levels of program output. Developers can use
loggers to record messages with different levels of severity, such as
info, warning, and error.
7. File Output:
Besides the console, Java programs can write output to files. This is
achieved using classes like FileOutputStream or higher-level classes
like PrintWriter. Writing output to files is essential for logging and
persisting data.
8. GUI Output:
In graphical user interface (GUI) applications, output is often
displayed in windows, dialog boxes, or other graphical elements. GUI
frameworks like JavaFX or Swing provide components for presenting
information visually.
9. Redirecting Output:
Java allows developers to redirect standard output and standard error
to different destinations. This can be useful for capturing program
output for further analysis or for integrating Java programs into larger
systems.
10. Localization and Internationalization:
Java supports localization and internationalization, allowing
developers to create output messages in different languages or adapt
the output to regional conventions. This is achieved through resource
bundles and the java.util.Locale class.
In summary, Java output involves the generation and presentation of
information by a Java program. Whether displayed on the console,
formatted, redirected to files, or presented in a GUI, understanding how to
manage output is crucial for effective programming and communication of
the program's results.
Let's start with a simple Java code example that involves output, and then
I'll explain what Java output specifically means: public class
OutputExample {
public static void main(String[] args) {
// Output to the console using println System.out.println("Hello,
Java!"); // Output with variables int x = 5; double y = 3.14;
System.out.println("The value of x is: " + x);
System.out.println("The value of y is: " + y); y) ; }

// Formatted output
System.out.printf("Formatted output: x = %d, y = %.2f\n", x, }
Explanation of Java Output:
1. Print to Console (System.out.println): The System.out.println
statement is used to print a line of text to the console. In the example,
it prints the string "Hello, Java!".
2. Output with Variables: You can include variable values in the output
by concatenating or formatting. In the example, the values of variables
x and y are printed using the + operator. The + operator concatenates
the string with the variable values.
3. Formatted Output (System.out.printf): The System.out.printf method
allows you to format the output using placeholders. In the example,
%d is a placeholder for an integer (x), and
%.2f is a placeholder for a floating-point number (y) with two decimal
places.
Output in Java specifically refers to the information that a program
displays to the user or another part of the system. In the provided code
example:
"Hello, Java!" is output to the console using System.out.println.
The values of variables x and y are incorporated into the output to
display specific information about those variables. The
System.out.printf method is used for more controlled and formatted
output, allowing you to specify the format of each value in the output
string.
Understanding how to generate output is essential for debugging,
providing feedback to users, and communicating information within a Java
program. It involves using various methods and techniques to display data
in a readable and meaningful way.
Java Comments
In Java, comments are non-executable statements added to the source
code to provide explanations, documentation, or remarks. Comments are
ignored by the Java compiler and do not affect the program's
functionality. They serve as a means for developers to make their code
more readable and understandable. Here's an explanation of Java
comments:

1. Single-Line Comments:

Single-line comments start with the double forward slash //.


Anything written after // on the same line is treated as a comment and
is not executed by the compiler. Single-line comments are useful for
brief explanations on a single line.

2. Multi-Line Comments:

Multi-line comments are enclosed between /* and */. Anything


between these delimiters, spanning multiple lines, is considered a
comment. Multi-line comments are useful for providing more
extensive explanations, documenting sections of code, or temporarily
excluding blocks of code.

3. Javadoc Comments:

Javadoc comments are a specific type of comment used for


documentation purposes. They start with /** and end with */.
Javadoc comments can be used to generate documentation
automatically using tools like Javadoc. These comments often
precede classes, methods, or fields and include information about the
purpose, parameters, return values, and exceptions thrown.

4. Commenting for Code Clarification:


Comments can be added to clarify complex code or to explain the
rationale behind a particular design choice. This is especially helpful
for making the code more understandable to other developers or to
the person who wrote the code initially.
5. TODO Comments:

TODO comments are used to mark areas of the code that need further attention or
completion. Developers can use these comments to indicate tasks that should be addressed in
the future. IDEs often provide a convenient way to track and manage TODO comments.

6. Commenting Out Code:

Comments are commonly used to "comment out" or disable sections of code temporarily.
This can be useful during debugging or when testing alternative implementations. Instead of
deleting code, commenting it out allows for easy reversion.

7. Header Comments:

Header comments are often placed at the beginning of a file to provide an overview of its
contents. This may include information about the author, creation date, modification history,
or any other relevant details.

8. Commenting for Debugging:

Comments can be used to include debugging information. While debugging, developers


may add comments to highlight specific points or to indicate the purpose of certain lines of
code.

9. Avoiding Redundant Comments:

While comments are valuable, it's important to write code that is self-explanatory whenever
possible. Redundant comments that merely restate the obvious should be avoided, as they
can clutter the code without adding meaningful information.

10. Clean Code Practices:

Following clean code practices encourages developers to write code in such a way that it is
clear and readable without excessive reliance on comments. Well-named variables, methods,
and classes contribute to code clarity.
In summary, comments in Java play a crucial role in enhancing the readability and maintainability
of code. They provide a means for developers to communicate intent, document functionality, and
make the codebase more accessible to others who may read or work on the code in the future.
In Java, comments are used to provide explanations or annotations within
the source code. These comments are not executed by the Java compiler
and do not affect the program's functionality; they are solely for the
benefit of developers to understand and document the code. There are two
types of comments in Java: single-line comments and multi-line
comments.
Here's an example of Java code with both types of comments: public class
Example {

// This is a single-line comment public


static void main(String[] args) {
/*
* This is a multi-line comment.
* It can span multiple lines and is often used for more extensive
explanations.
*/
System.out.println("Hello, World!"); // This is also a single- line
comment // You can use comments to temporarily disable or comment
out code // System.out.println("This line won't be executed."); //
TODO: This is a special type of comment indicating a task to be done //
It's often used to mark areas of code that need attention or completion
}
}
Explanation of Java comments:
1. Single-line comments: These comments begin with // and continue
until the end of the line. They are typically used for short comments or
annotations on a single line.
2. Multi-line comments: These comments start with /* and end with */.
They can span multiple lines and are useful for providing more
extensive explanations or commenting out larger blocks of code.
3. Commenting out code: You can use comments to temporarily disable
or comment out lines of code. This is handy during development when
you want to exclude certain portions of the code without deleting
them.
4. TODO comments: These are special comments often used to mark
areas in the code that require attention or completion. Developers can
use tools to identify and list all the TODO comments in the codebase,
making it easy to keep track of pending tasks.
In summary, Java comments are essential for code documentation,
readability, and collaboration among developers. They help explain the
purpose of code, provide insights into its functionality, and make it easier
for others (or even yourself in the future) to understand and maintain the
codebase.
JAvA VARiABleS
In Java, variables are containers that store data values. They are
fundamental to programming and are used to hold and manipulate
information within a program.
1. Variable Declaration:
In Java, you declare a variable by specifying its data type, followed
by the variable name. The data type indicates the type of values the
variable can hold, such as int for integers, double for floating-point
numbers, or String for text.
2. Data Types:
Java supports various data types, including primitive data types (e.g.,
int, double, char, boolean) and reference data types (e.g., String,
custom classes). Primitive data types hold simple values directly,
while reference data types store references to objects.
3. Naming Conventions:
Variable names in Java must adhere to certain naming conventions.
They should start with a letter, followed by letters, digits, or
underscores. Names are case-sensitive, so myVariable and myvariable
are treated as different variables.
4. Initialization:
After declaring a variable, you can assign an initial value to it
through a process called initialization. This involves using the
assignment operator (=) to associate a value with the variable.
5. Scope:
Variables have a scope, which defines the region of the program
where the variable is accessible. Local variables are declared within a
specific method or block and have limited scope, while instance
variables and class variables have broader scopes.
Constants:
In Java, you can create constants using the final keyword. Constants
are variables whose values cannot be changed once they are assigned.
They are often used for values that should remain constant throughout
the program.
7. Type Inference (Java 10 and later):
Starting from Java 10, Java introduced a feature called local variable
type inference. With this feature, you can use the var keyword to
declare variables without explicitly specifying the data type. The
compiler infers the type based on the assigned value.

8. Variable Naming and Readability:


Choosing meaningful and descriptive names for variables is crucial
for code readability. Good variable names convey the purpose or
meaning of the data they hold, making the code more understandable.

9. Variable Mutability:
The mutability of variables depends on their data type. Some
variables, like those of primitive types, are immutable, meaning their
values cannot be changed once assigned. Others, like objects, can
have their properties modified.

10. Garbage Collection:


In Java, memory management is handled by a process called garbage
collection. Unused objects and variables are automatically identified
and released from memory to free up resources.
In summary, variables in Java are essential for storing and manipulating
data in a program. They have specific data types, naming conventions,
scopes, and may or may not be mutable depending on their type.
Understanding how to declare, initialize, and use variables is fundamental
to writing effective and readable Java code.
In Java, variables are containers for storing data values. Each variable has
a data type, such as int, double, or String, which defines the type of data it
can hold.
public class VariableExample {
public static void main(String[] args) {
// Declare and initialize variables int
age = 25; double height = 5.9;
String name = "John Doe"; // Print the values of variables
System.out.println("Name: " + name); System.out.println("Age: "
+ age); System.out.println("Height: " + height); // Update the value
of a variable age = 26; // Print the updated value
System.out.println("Updated Age: " + age); // Perform operations
with variables int birthYear = 1995; int currentYear = 2024;
int calculatedAge = currentYear - birthYear; // Print the calculated
age System.out.println("Calculated Age: " + calculatedAge); }
}
Explanation of Java variables:
1. Declaration and Initialization: In Java, you declare a variable by
specifying its data type, followed by the variable name. You can also
initialize the variable with a value on the same line. For example, int
age = 25; declares an integer variable named age and initializes it with
the value 25.
2. Data Types: Java supports various data types, including primitive
types like int, double, char, boolean, and reference types like String.
Each data type specifies the kind of values the variable can hold.
3. Printing Variables: You can print the values of variables using the
System.out.println() statement. This is a common practice for
debugging and displaying information to users.
4. Updating Variables: Variables can be updated by assigning new values
to them. In the example, the age variable is updated from 25 to 26.
5. Operations with Variables: Variables can be used in mathematical
operations or other expressions. In the example, the calculatedAge
variable is assigned the result of subtracting birthYear from
currentYear.
In summary, Java variables are named storage locations for holding data
values. They play a crucial role in program0ming by allowing developers
to work with and manipulate data in their programs. Understanding data
types is essential for using variables correctly in Java.
Java Data Types
In Java, data types are a fundamental concept that defines the nature of values a variable can hold.
Each variable in Java must have a declared data type, which specifies the kind of data it can store.
Integer Types: byte, short,
1. Primitive Data Types: Java has eight primitive data types:
int, and long for whole numbers (integer values).
Floating-Point Types: float and double for numbers with a fractional part.
Character Type: char for individual characters (e.g., letters, digits).
Boolean Type: boolean for representing true or false values.
2. Size and Range: Each primitive data type has a specific size in terms of bits
and a defined range of values it can hold. For example, int is typically 32
bits, and its range is from -2^31 to 2^31 - 1.
3. Reference Data Types: Reference data types in Java include classes,
interfaces, arrays, and enumerations. Unlike primitive types, these data
types don't hold the actual data but reference objects in memory.
4. Strings: The String class in Java is used to represent sequences of
characters. Strings are not primitive data types but are commonly used
and treated as such due to their importance in programming.
5. Arrays: Arrays are a reference data type used to store a collection of
elements of the same type. They can be one-dimensional, multi-
dimensional, or jagged.
6. Type Inference (Java 10 and later): Starting from Java 10, local variable type
inference allows the use of the var keyword to declare variables without
explicitly specifying the data type. The compiler infers the type based on
the assigned value.
7. Automatic Type Conversion (Casting):
Java supports automatic type conversion for certain data types. For example, you can assign
an int value to a double variable without explicit casting. However, explicit casting is required
when converting between certain types.
8. Boxing and Unboxing:
Java supports automatic conversion between primitive types and their corresponding wrapper
classes. This process is called autoboxing (converting a primitive type to its wrapper type) and
unboxing (converting a wrapper type to its primitive type).
9. Enumerations:
Enumerations (enum) are a special type of data type that define a set of named constants.
Enumerations make the code more readable and provide a way to represent a fixed set of
values.
10. Type Safety:
Java is a statically-typed language, which means that the data type of a variable must be
known at compile-time. This enhances type safety by catching type-related errors during the
compilation process.
11. User-Defined Data Types:
In addition to built-in data types, Java allows developers to create their own user-defined data
types using classes and interfaces. This feature is fundamental to object-oriented
programming.
In summary, Java data types categorize variables based on the type of values they can hold.
Understanding the characteristics, ranges, and uses of different data types is crucial for writing
correct and efficient Java programs.

In Java, data types are used to classify and define the types of values that
variables can hold. Java supports two main categories of data types:
primitive data types and reference data types.
public class DataTypesExample {

public static void main(String[] args) {


// Primitive data types int
integerNumber = 42;
double doubleNumber =
3.14; char character = 'A';
boolean flag = true;

// Reference data type String


text = "Hello, Java!"; //
Display values
System.out.println("Integer Number: " + integerNumber);
System.out.println("Double Number: " + doubleNumber);
System.out.println("Character: " + character);
System.out.println("Flag: " + flag); System.out.println("Text:
" + text); // Using arrays (reference data type) int[] numbers =
{1, 2, 3, 4, 5}; System.out.println("Array Element: " + numbers[2]); //
User-defined class (reference data type) Person person = new
Person("Alice", 30); System.out.println("Person: " + person.getName() +
", Age: " + person.getAge()); }
}

// User-defined class for reference data type example class


Person {
private String name;
private int age; public
Person(String name,
int age) { this.name =
name; this.age = age;
}

public String getName() {


return name; }

public int getAge() {


return age; }
}
Explanation of Java data types:

1. Primitive Data Types:


int: Represents integer values (e.g., 42).
double: Represents floating-point values (e.g., 3.14).
char: Represents a single character (e.g., 'A'). boolean:
Represents true or false values (e.g., true).

2. Reference Data Type:


String: Represents sequences of characters (e.g., "Hello, Java!").
3. Arrays (Reference Data Type):
Arrays are used to store multiple values of the same data type. In
the example, int[] numbers is an array of integers.
4. User-defined Class (Reference Data Type):
Developers can define their own classes to create custom data
types. In the example, the Person class is a user-defined class with
name and age as its attributes.
Understanding data types is crucial in Java programming because it helps
ensure that variables are used appropriately and that operations are
performed correctly. Primitive data types are the building blocks for more
complex structures, and reference data types allow for the creation of
custom objects and structures.
JAvA Type CAStinG
Java type casting refers to the process of converting a value from one data
type to another. This conversion can be explicit or implicit, depending on
whether it requires the programmer to specify the conversion explicitly.
1. Implicit Casting (Widening):
Implicit casting, also known as widening or automatic type
conversion, occurs when the conversion can be done without any loss
of information. For example, converting an int to a double is implicit
because the double type can represent the integer values without loss.
2. Explicit Casting (Narrowing):
Explicit casting, also known as narrowing, is required when
converting from a larger data type to a smaller one, or when there is a
potential loss of information. For example, converting a double to an
int requires explicit casting because information may be lost due to
truncation.
3. Casting between Primitive Types:
In Java, primitive types can be cast between each other. For example,
casting a long to an int, or a float to a short. However, it's important to
note that casting between incompatible types or those with a
significant difference in size may result in data loss.
4. Casting with Wrapper Classes:
When working with wrapper classes (e.g., Integer, Double), explicit
casting may be required to convert between wrapper types or between
wrapper types and primitive types. This process is known as unboxing
and boxing.
Type Casting with Objects:
When dealing with objects in Java, casting is often used to treat an
object of one type as an object of another type. This is particularly
common in scenarios involving inheritance and polymorphism.
6. Type Safety:
Java's type system emphasizes type safety, and casting plays a role in
maintaining this safety. Casting should be done carefully to avoid
runtime errors and unexpected behavior. The compiler checks the
compatibility of types during the compilation process.
7. Type Compatibility:
Casting is only possible between compatible types. For instance, you
can cast between numeric types, but you cannot cast between
unrelated types, such as trying to cast a String to an int.
8. Type Casting with Enums:
Enumerations (enum) are special types in Java, and casting may be
necessary when working with enums, especially if you need to convert
an enum constant to its ordinal value or vice versa.
9. Primitives and Reference Types:
The process of casting is slightly different for primitive types and
reference types. While primitive types involve direct conversion,
reference types involve converting references between classes or
interfaces in the inheritance hierarchy.
10. ClassCastException:
When casting reference types, it's essential to handle potential
exceptions, such as ClassCastException, which may occur if the object
being cast is not an instance of the specified type.
In summary, Java type casting is a mechanism that allows developers to
convert values between different data types. Whether implicit or explicit,
casting plays a crucial role in managing data types, ensuring type safety,
and facilitating smooth interactions between different parts of a program.
In Java, type casting refers to the process of converting a variable from
one data type to another. There are two types of type casting in Java:
implicit (automatic) casting and explicit (manual) casting.

public class TypeCastingExample { public

static void main(String[] args) {

// Implicit casting (Widening conversion) int intValue = 50;


long longValue = intValue; // Automatically converts int to long
float floatValue = 3.14f; double doubleValue = floatValue; //
Automatically converts float to double System.out.println("Implicit
Casting:"); System.out.println("int to long: " + longValue);
System.out.println("float to double: " + doubleValue); // Explicit
casting (Narrowing conversion) double anotherDoubleValue = 123.456;
int anotherIntValue = (int) anotherDoubleValue; // Manually converts
double to int long anotherLongValue = 987654321; int
anotherIntValue2 = (int) anotherLongValue; // Manually converts long
to int System.out.println("\nExplicit Casting:");
System.out.println("double to int: " + anotherIntValue);
System.out.println("long to int: " + anotherIntValue2); }
}
Explanation of Java type casting:
1. Implicit Casting (Widening Conversion): It occurs automatically when
a smaller data type is assigned to a larger data type.
In the example, int is implicitly cast to long, and float is
implicitly cast to double. This is safe because there is no loss of
precision.
2. Explicit Casting (Narrowing Conversion): It must be done manually
by the programmer when a larger data type is assigned to a smaller data
type.
In the example, double is explicitly cast to int, and long is
explicitly cast to int. This may result in a loss of precision, and the
programmer needs to be aware of potential data loss.

3. Caution with Explicit Casting:


When narrowing the data type, there is a risk of losing
information, especially if the value is too large or if it contains
decimal places.
It's essential to ensure that the value being cast is within the valid
range of the target data type to prevent unexpected results.
Type casting is a common operation in Java when dealing with different
data types. It allows for flexibility in assigning values between variables of
different types, but developers should be cautious to avoid data loss or
unexpected behavior.
JAvA OpeRAtoRS
In Java, operators are symbols that perform operations on variables and
values. They are crucial for manipulating data and controlling the flow of
a program.
1. Arithmetic Operators:
Arithmetic operators perform basic mathematical operations. These
include addition (+), subtraction (-), multiplication (*), division (/),
and modulus (%). Modulus returns the remainder of a division
operation.
2. Relational Operators:
Relational operators are used to compare values. Common relational
operators include equality (==), inequality (!=), greater than (>), less
than (<), greater than or equal to (>=), and less than or equal to (<=).
3. Logical Operators:
Logical operators perform logical operations on boolean values. The
logical AND (&&) returns true if both operands are true, the logical
OR (||) returns true if at least one operand is true, and the logical NOT
(!) returns the opposite boolean value.
4. Assignment Operators:
Assignment operators are used to assign values to variables. The
basic assignment operator is =. Other assignment operators include
+=, -=, *=, /=, and %= which perform an operation and assign the
result to the variable.
5. Increment and Decrement Operators:
Increment (++) and decrement (--) operators are used to increase or
decrease the value of a variable by 1, respectively. They can be used
in prefix or postfix form, affecting the order of evaluation.
6. Bitwise Operators:
Bitwise operators perform operations at the bit level. Examples
include bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise
NOT (~), left shift (<<), and right shift (>>).
7. Conditional (Ternary) Operator:
The conditional or ternary operator (? :) is a shorthand way of
expressing an if-else statement. It evaluates a boolean expression and
returns one of two values depending on whether the expression is true
or false.

8. instanceof Operator:
The instanceof operator is used to test whether an object is an
instance of a particular class or interface. It returns true if the object is
an instance; otherwise, it returns false.

9. Equality and Identity Operators:


The equality operator (==) checks if two values are equal. The
identity operators (== and !=) check if two references point to the
same object.

10. String Concatenation Operator:


The + operator is used for concatenating strings in Java. When used
with strings, it joins them together to create a new string.

11. Other Operators:


Java includes other operators, such as the conditional null operator
(??), which returns the left operand if it is non-null, and the right
operand otherwise (introduced in Java 12).
Understanding how these operators work and their precedence is crucial
for writing correct and efficient Java code. Operators are fundamental
tools for expressing computations and decision-making in programs.
In Java, operators are symbols that perform operations on variables and
values. There are various types of operators in Java, including arithmetic,
relational, logical, assignment, bitwise, and others.
public class OperatorsExample {
public static void main(String[] args) {
// Arithmetic operators int
num1 = 10; int num2 = 5;
int sum = num1 + num2; int difference = num1 - num2; int product
= num1 * num2; int quotient = num1 / num2; int remainder =
num1 % num2; System.out.println("Arithmetic Operators:");
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder); // Relational
operators boolean isEqual = (num1 == num2); boolean isNotEqual
= (num1 != num2); boolean isGreater = (num1 > num2); boolean
isLessOrEqual = (num1 <= num2);
System.out.println("\nRelational Operators:");
System.out.println("Is Equal: " + isEqual); System.out.println("Is
Not Equal: " + isNotEqual); System.out.println("Is Greater: " +
isGreater); System.out.println("Is Less or Equal: " +
isLessOrEqual);
// Logical operators boolean logicalAnd = (true && false); boolean
logicalOr = (true || false); boolean logicalNot = !true;
System.out.println("\nLogical Operators:");
System.out.println("Logical AND: " + logicalAnd);
System.out.println("Logical OR: " + logicalOr);
System.out.println("Logical NOT: " + logicalNot); // Assignment
operators int x = 5; x += 3; // Equivalent to x = x + 3
System.out.println("\nAssignment Operator:");
System.out.println("Updated x: " + x); // Bitwise operators int
binaryNum1 = 0b1010; // Binary literal for 10 int binaryNum2 =
0b1100; // Binary literal for 12 int bitwiseAnd = binaryNum1 &
binaryNum2; int bitwiseOr = binaryNum1 | binaryNum2; int
bitwiseXor = binaryNum1 ^ binaryNum2;
System.out.println("\nBitwise Operators:");
System.out.println("Bitwise AND: " + bitwiseAnd);
System.out.println("Bitwise OR: " + bitwiseOr);
System.out.println("Bitwise XOR: " + bitwiseXor); }
}
Explanation of Java operators:

1. Arithmetic Operators:
+, -, *, /, % perform addition, subtraction, multiplication,
division, and modulus (remainder) operations, respectively.

2. Relational Operators:
==, !=, >, >=, <, <= compare values and return boolean results.

3. Logical Operators:
&& (logical AND), || (logical OR), ! (logical NOT) perform
logical operations and return boolean results.

4. Assignment Operator:
= assigns a value to a variable. Compound assignment operators
like += combine an operation with assignment.

5. Bitwise Operators:
& (bitwise AND), | (bitwise OR), ^ (bitwise XOR) perform
operations at the bit level.
Operators are essential for performing various operations in Java, and
understanding their usage is crucial for writing effective and efficient
code. They enable developers to manipulate variables and values to
achieve desired results.
JAvA StRinGS
In Java, a String is a class that represents a sequence of characters. Strings
are widely used in Java programming for text manipulation, storage, and
representation.
1. Immutable Nature:
One key characteristic of Java Strings is their immutability. Once a
String object is created, its value cannot be changed. Any operation
that appears to modify a String actually creates a new String.
2. String Literal vs. String Object:
Strings in Java can be created using string literals (e.g., "Hello") or
by creating String objects using the new keyword. Using string literals
is more common and convenient, and Java automatically creates
String objects for literals.
3. Concatenation:
Strings in Java can be concatenated using the + operator. This
operation creates a new String that is the concatenation of the
operands. For efficiency, especially when concatenating in a loop,
StringBuilder or StringBuffer classes are recommended.
4. String Pool:
Java maintains a String pool, which is a pool of unique String literals
in memory. When a new String is created using a literal that already
exists in the pool, the existing instance is reused, reducing memory
overhead.
5. String Methods:
The String class provides numerous methods for manipulating and
querying strings. These methods include operations for finding the
length of a string, extracting substrings, converting case, comparing
strings, and more.
6. Escape Sequences:
Strings in Java support escape sequences to represent special
characters. For example, \n represents a newline character, \t
represents a tab character, and \" represents a double quote.
7. String Comparison:
Comparing strings in Java is done using methods like equals() or
compareTo(). It's important to note that == compares references, not
the actual content of the strings.
8. String Interning:
String interning is the process of putting unique String literals into the
String pool, ensuring that identical literals refer to the same String
object. This can be done explicitly using the intern() method.
9. String Indexing:
Characters in a String are indexed starting from 0. Accessing
individual characters is done using the charAt() method. Strings are
immutable, so modifying a character requires creating a new String.
10. Unicode Support:
Java Strings support Unicode, allowing them to represent characters
from various writing systems. This makes Java suitable for
internationalization and localization.
11. Regular Expressions:
Java provides support for regular expressions through the String class
and the java.util.regex package. Regular expressions allow for
powerful string matching and manipulation.
12. StringBuffer and StringBuilder:
While String objects are immutable, StringBuffer and StringBuilder
classes provide mutable alternatives for string manipulation. They are
more efficient for scenarios involving frequent modifications.
In summary, Java Strings are a fundamental part of the language, offering
a versatile and powerful way to work with textual data. Understanding the
immutability of Strings, their methods, and related concepts like the String
pool is crucial for effective string manipulation in Java programs.
In Java, a String is a sequence of characters. It is a class in Java, and
instances of this class represent sequences of characters.
public class StringsExample {

public static void main(String[] args) {


// Creating strings
String greeting = "Hello, "; String
name = "John"; // Concatenation String
welcomeMessage = greeting + name +
"!"; System.out.println("Welcome
Message: " + welcomeMessage); //
String length
int length = welcomeMessage.length(); System.out.println("Length of
Welcome Message: " + length); // Accessing characters in a string
char lastChar =
char firstChar = welcomeMessage.charAt(0);
welcomeMessage.charAt(length - 1); System.out.println("First
Character: " + firstChar); System.out.println("Last Character: " +
lastChar); // Substring
String substring = welcomeMessage.substring(7, 12); System.out.println("Substring: " +
substring); // String comparison String anotherName = "john"; boolean isEqualIgnoreCase =
name.equalsIgnoreCase(anotherName); System.out.println("Is name equal to
anotherName (ignore case)? " +
isEqualIgnoreCase);

// String modification (Strings are immutable) String


originalString = "abc"; String modifiedString =
originalString.concat("def"); System.out.println("Original
String: " + originalString); System.out.println("Modified
String: " + modifiedString); }
}
Explanation of Java strings:

1. Creating Strings:
Strings can be created using double quotes. For example, String
greeting = "Hello, ";.

2. Concatenation:
Strings can be concatenated using the + operator. In the example,
welcomeMessage is formed by concatenating greeting, name, and
"!".

3. String Length:
The length() method is used to find the length of a string.

4. Accessing Characters:
The charAt(index) method allows you to access characters at a
specific index in a string.

5. Substring:
The substring(startIndex, endIndex) method extracts a portion of
a string.

6. String Comparison:
The equals() method is used for case-sensitive string comparison,
and equalsIgnoreCase() is used for case- insensitive comparison.
7. String Modification (Immutability):
Strings in Java are immutable, meaning their values cannot be
changed after they are created. Operations like concatenation
create new strings rather than modifying the original.
Strings are fundamental in Java and are extensively used for representing
text. The String class provides various methods for manipulating and
working with strings, making it versatile for handling textual data in Java
programs. Understanding string operations is crucial for many
programming tasks involving text manipulation.
JAvA MAth
In Java, the Math class is a part of the java.lang package and provides a
set of static methods for performing mathematical operations. These
methods cover a wide range of mathematical functions and are useful for
various applications.
1. Static Methods:
All the methods in the Math class are static, meaning you don't need
to create an instance of the class to use them. You can directly call
these methods using the class name.
2. Basic Arithmetic Operations:
The Math class includes methods for basic arithmetic operations,
such as addition (addExact()), subtraction (subtractExact()),
multiplication (multiplyExact()), and division (floorDiv()). These
methods handle overflow and underflow conditions more robustly.
3. Exponential and Logarithmic Functions:
The Math class provides methods for exponential functions, such as
exp() and pow(), which raise a base to a specified power. It also
includes logarithmic functions like log() and log10() for different
bases.
4. Trigonometric Functions:
Common trigonometric functions are available in the Math class,
including sin(), cos(), and tan(). There are also their inverse
counterparts, such as asin(), acos(), and atan().
5. Rounding Functions:
Methods like round(), floor(), and ceil() are provided for rounding
numbers to the nearest integer, rounding down to the nearest integer,
and rounding up to the nearest integer, respectively.
6. Square Root and Cube Root:
The sqrt() method calculates the square root of a number, and the
cbrt() method calculates the cube root of a number.
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Mother Goose
for Grown-ups
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: Mother Goose for Grown-ups

Author: Guy Wetmore Carryl

Illustrator: Peter Newell


Gustave Verbeek

Release date: October 25, 2015 [eBook #50310]


Most recently updated: October 22, 2024

Language: English

Credits: Produced by Suzanne Shell, Melissa McDaniel, and the


Online
Distributed Proofreading Team at http://www.pgdp.net
(This
file was produced from images generously made
available
by The Internet Archive/American Libraries.)

*** START OF THE PROJECT GUTENBERG EBOOK MOTHER GOOSE


FOR GROWN-UPS ***
Transcriber's Note:
Obvious typographical errors have been corrected.
Inconsistent spelling and hyphenation in the original
document have been preserved.
MOTHER GOOSE FOR
GROWN-UPS
"'WILL YOU TELL ME IF IT'S STRAIGHT?'"

MOTHER GOOSE
FOR GROWN-UPS
By GUY WETMORE CARRYL
With Illustrations by Peter
Newell and Gustave Verbeek
NEW YORK AND LONDON
HARPER & BROTHERS
1900

Copyright, 1900, by Harper & Brothers.


All rights reserved
TO CONSTANCE

In memory of other days,


Dear critic, when your whispered praise
Cheered on the limping pen.
How short, how sweet those younger hours,
How bright our suns, how few our showers,
Alas, we knew not then!

If but, long leagues across the seas,


The trivial charm of rhymes like these
Shall serve to link us twain
An instant in the olden spell
That once we knew and loved so well,
I have not worked in vain!
NOTE
I have pleasure in acknowledging the courteous permission of the
editors to reprint in this form such of the following verses as were
originally published in Harper's Magazine, the Saturday Evening Post,
and the London Sketch.

G. W. C.
CONTENTS

PAGE
The Admirable Assertiveness of Jilted Jack 3
The Blatant Brutality of Little Bow Peep 9
The Commendable Castigation of Old Mother Hubbard 15
The Discouraging Discovery of Little Jack Horner 21
The Embarrassing Episode of Little Miss Muffet 27
The Fearful Finale of the Irascible Mouse 33
The Gastronomic Guile of Simple Simon 39
The Harmonious Heedlessness of Little Boy Blue 47
The Inexcusable Improbity of Tom, the Piper's Son 53
The Judicious Judgment of Quite Contrary Mary 59
The Linguistic Languor of Charles Augustus Sprague 65
The Mysterious Misapprehension Concerning a Man in Our
Town 71

The Opportune Overthrow of Humpty Dumpty 77


The Preposterous Performance of an Old Lady of Banbury 83
The Quixotic Quest of Three Blind Mice 89
The Remarkable Regimen of the Sprat Family 95
The Singular Sangfroid of Baby Bunting 101
The Touching Tenderness of King Karl the First 107
The Unusual Ubiquity of the Inquisitive Gander 113
ILLUSTRATIONS

PAGE
"'WILL YOU TELL ME IF IT'S STRAIGHT?'" Frontispiece
"SHE WAS SO CHARMINGLY WATTEAU-
LIKE" Facing p. 10

"NOW SIMON'S TASTES WERE MOST


PROFUSE" Facing p. 40

"WHILE BY KICKS HE LOOSENED BRICKS" Facing p. 78


"SHE PLUCKED HIM WITH RELENTLESS Facing p.
FROWN" 114
THE ADMIRABLE ASSERTIVENESS
OF

JILTED JACK
A noble and a generous mind
Was Jack's;
Folks knew he would not talk behind
Their backs:
But when some maiden fresh and young,
At Jack a bit of banter flung,
She soon discovered that his tongue
Was sharp as any ax.

A flirt of most engaging wiles


Was Jill;
On Jack she lavished all her smiles,
Until
Her slave (and he was not the first)
Of lovesick swains became the worst,
His glance a strong box might have burst,
His sighs were fit to kill.

One April morning, clear and fair,


When both
Of staying home and idling there
In sloth
Were weary, Jack remarked to Jill:
"Oh, what's the sense in sitting still?
Let's mount the slope of yonder hill."
And she was nothing loth.

But as she answered: "What's the use?"


The gruff
Young swain replied: "Oh, there's excuse
Enough.
Your doting parents water lack;
We'll fill a pail and bring it back."
(The reader will perceive that Jack
Was putting up a bluff.)
Thus hand in hand the tempting hill
They scaled,
And Jack proposed a kiss to Jill,
And failed!
One backward start, one step too bold,
And down the hill the couple rolled,
Resembling, if the truth were told,
A luggage train derailed.

With eyes ablaze with anger, she


Exclaimed:
"Well, who'd have thought! You'd ought to be
Ashamed!
You quite forget yourself, it's plain,
So I'll forget you, too. Insane
Young man, I'll say oafweederzane."
(Her German might be blamed.)

But Jack, whose linguist's pride was pricked,


To shine,
Asked: "Meine Königin will nicht
Be mine?"
And when she answered: "Nein" in spleen,
He cried: "Then in the soup tureen
You'll stay. You're not the only queen
Discarded for a nein!"

The moral's
made for maidens young
And small:
If you would in a foreign tongue
Enthrall,
Lead off undaunted in a Swede
Or Spanish speech, and you'll succeed,
But they who in a German lead
No favor win at all.
THE BLATANT BRUTALITY
OF

LITTLE BOW PEEP


Though she was only a shepherdess,
Tending the meekest of sheep,
Never was African leopardess
Crosser than Little Bow Peep:
Quite apathetic, impassible
People described her as: "That
Wayward, contentious, irascible,
Testy, cantankerous brat!"

Yet, as she dozed in a grotto-like


Sort of a kind of a nook,
She was so charmingly Watteau-like,
What with her sheep and her crook;
"She is a dryad or nymph," any
Casual passer would think.
Poets pronounced her a symphony,
All in the palest of pink.

Thus it was not enigmatical,


That the young shepherd who first
Found her asleep, in ecstatical
Sighs of felicity burst:
Such was his sudden beatitude
That, as he gazed at her so,
Daphnis gave vent to this platitude:
"My! Ain't she elegant though!"

Roused from some dream of Arcadia,


Little Bow Peep with a start
Answered him: "I ain't afraid o' yer!
P'raps you imagine you're smart!"
Daphnis protested impulsively,
Blushing as red as a rose;
All was in vain. She convulsively
Punched the young man in the nose!
All of it's true, every word of it!
I was not present to peep,
But if you ask how I heard of it,
Please to remember the sheep.
There is no need of excuse. You will
See how such scandals occur:
If you recall Mother Goose, you will
Know what tail-bearers they were!

Moral: This pair irreclaimable


Might have made Seraphim weep,
But who can pick the most blamable?
Both saw a little beau peep!
"SHE WAS SO CHARMINGLY WATTEAU-
LIKE"
THE COMMENDABLE CASTIGATION
OF

OLD MOTHER HUBBARD


She was one of those creatures
Whose features
Are hard beyond any reclaim;
And she loved in a hovel
To grovel,
And she hadn't a cent to her name.
She owned neither gallants
Nor talents;
She borrowed extensively, too,
From all of her dozens
Of cousins,
And never refunded a sou:
Yet all they said in abuse of her
Was: "She is prouder than Lucifer!"
(That, I must say, without meaning to blame,
Is always the way with that kind of a dame!)

There never was jolli-


Er colley
Than Old Mother Hubbard had found,
Though cheaply she bought him,
She'd taught him
To follow her meekly around:
But though she would lick him
And kick him,
It never had any effect;
He always was howling
And growling,
But goodness! What could you expect?
Colleys were never to flourish meant
'Less they had plenty of nourishment,
All that he had were the feathers she'd pluck
Off an occasional chicken or duck.

The colley was barred in


The garden
The garden,
He howled and he wailed and he whined.
The neighbors indignant,
Malignant
Petitions unanimous signed.
"The nuisance grows nightly,"
Politely
They wrote. "It's an odious hound,
And either you'll fill him,
Or kill him,
Or else he must go to the pound.
For if this howling infernally
Is to continue nocturnally—
Pardon us, ma'am, if we seem to be curt—
Somebody's apt to get horribly hurt!"

Mother Hubbard cried loudly


And proudly:
"Lands sakes! but you give yourselves airs!
I'll take the law to you
And sue you."
The neighbors responded: "Who cares?
We none of us care if
The sheriff
Lock every man jack of us up;
We won't be repining
At fining
So long as we're rid of the pup!"
They then proceeded to mount a sign,
Bearing this ominous countersign:
"Freemen! The moment has come to protest
And Old Mother Hubbard delendum est!"

They marched to her gateway,


And straightway
They trampled all over her lawn;
Most rudely they harried
ost ude y t ey a ed
And carried
Her round on a rail until dawn.
They marred her, and jarred her,
And tarred her
And feathered her, just as they should,
Of speech they bereft her,
And left her
With: "Now do you think you'll be good!"

The moral's a charmingly pleasing one.


While we would deprecate teasing one,
Still, when a dame has politeness rebuffed,
She certainly ought to be collared and cuffed.
THE DISCOURAGING DISCOVERY
OF

LITTLE JACK HORNER


A knack almost incredible for dealing with an edible
Jack Horner's elder sister was acknowledged to display;
She labored hard and zealously, but always guarded jealously
The secrets of the dishes she invented every day.
She'd take some indigestible, unpopular comestible,
And to its better nature would so tenderly appeal
That Jack invoked a benison upon a haunch of venison,
When really she was serving him a little leg of veal!

Jack said she was a miracle. The word was not satirical,
For daily climbing upward, she excelled herself at last:
The acme of facility, the zenith of ability
Was what she gave her brother for his Christmas Day repast.
He dined that evening eagerly and anything but meagerly,
And when he'd had his salad and his quart of Extra Dry,
With sisterly benignity, and just a touch of dignity,
She placed upon the table an unutterable pie!

Unflagging pertinacity, and technical sagacity,


Long nights of sleepless vigil, and long days of constant care
Had been involved in making it, improving it, and baking it,
Until of other pies it was the wonder and despair:
So princely and so prominent, so solemn, so predominant
It looked upon the table, that, with fascinated eye,
The youth, with sudden wonder struck, electrified, and thunder
struck,
Could only stammer stupidly: "Oh Golly! What a pie!"

In view of his satiety, it almost seemed impiety


To carve this crowning triumph of a culinary life,
But, braced by his avidity, with sudden intrepidity
He broke its dome imposing with a common kitchen knife.
Ah, hideous fatality! for when with eager palate he
Commenced to eat, he happened on an accident uncouth,
And cried with stifled moan: "Of it one plum I tried. The stone of it
Had never been extracted and I've broke a wisdom tooth!"
Had never been extracted, and I ve broke a wisdom tooth!

Jack's sister wept effusively, but loudly and abusively


His unreserved opinion of her talents he proclaimed;
He called her names like "driveller" and "simpleton" and "sniveller,"
And others, which to mention I am really too ashamed.
The moral: It is saddening, embarrassing, and maddening
A stone to strike in what you thought was paste. One thing
alone
Than this mischance is crueller, and that is for a jeweller
To strike but paste in what he fondly thought to be a stone.
THE EMBARRASSING EPISODE
OF

LITTLE MISS MUFFET


Little Miss Muffet discovered a tuffet,
(Which never occurred to the rest of us)
And, as 'twas a June day, and just about noonday,
She wanted to eat—like the best of us:
Her diet was whey, and I hasten to say
It is wholesome and people grow fat on it.
The spot being lonely, the lady not only
Discovered the tuffet, but sat on it.

A rivulet gabbled beside her and babbled,


As rivulets always are thought to do,
And dragon-flies sported around and cavorted,
As poets say dragon-flies ought to do;
When, glancing aside for a moment, she spied
A horrible sight that brought fear to her,
A hideous spider was sitting beside her
And most unavoidably near to her!

Albeit unsightly, this creature politely


Said: "Madam, I earnestly vow to you,
I'm penitent that I did not bring my hat. I
Should otherwise certainly bow to you."
Though anxious to please, he was so ill at ease
That he lost all his sense of propriety,
And grew so inept that he clumsily stept
In her plate—which is barred in Society.

This curious error completed her terror;


She shuddered, and growing much paler, not
Only left tuffet, but dealt him a buffet
Which doubled him up in a sailor-knot.
It should be explained that at this he was pained:
He cried: "I have vexed you, no doubt of it!
Your fist's like a truncheon." "You're still in my luncheon,"
Was all that she answered. "Get out of it!"
And The moral is this: Be it madam or miss
To whom you have something to say,
You are only absurd when you get in the curd
But you're rude when you get in the whey.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like