Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java Fundamentals

You're reading from   Java Fundamentals A fast-paced and pragmatic introduction to one of the world's most popular programming languages

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789801736
Length 408 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (5):
Arrow left icon
Miles Obare Miles Obare
Author Profile Icon Miles Obare
Miles Obare
Basheer Ahamed Fazal Basheer Ahamed Fazal
Author Profile Icon Basheer Ahamed Fazal
Basheer Ahamed Fazal
Rogério Theodoro de Brito Rogério Theodoro de Brito
Author Profile Icon Rogério Theodoro de Brito
Rogério Theodoro de Brito
Gazihan Alankus Gazihan Alankus
Author Profile Icon Gazihan Alankus
Gazihan Alankus
Vinicius Isola Vinicius Isola
Author Profile Icon Vinicius Isola
Vinicius Isola
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Java Fundamentals
Preface
1. Introduction to Java 2. Variables, Data Types, and Operators FREE CHAPTER 3. Control Flow 4. Object-Oriented Programming 5. OOP in Depth 6. Data Structures, Arrays, and Strings 7. The Java Collections Framework and Generics 8. Advanced Data Structures in Java 9. Exception Handling Appendix

Generics


Classes that work with other classes in a generic way, like Vector, didn't have a way to explicitly tell the compiler that only one type was accepted. Because of that, it uses Object everywhere and runtime checks like instanceof and casting were necessary everywhere.

To solve this problem, Generic was introduced in Java 5. In this section you'll understand better the problem, the solution and how to use it.

What was the Problem?

When declaring an array, you tell the compiler what type of data goes inside the array. If you try to add something else in there, it won't compile. Look at the following code:

// This compiles and work
User[] usersArray = new User[1];
usersArray[0] = user;

// This wouldn't compile
// usersArray[0] = "Not a user";

/* If you uncomment the last line and try to compile, you would get the following error: */

File.java:15: error: incompatible types: String cannot be converted to User
        usersArray[0] = "Not a user";
                        ^

Let's say you...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime