This document provides an overview of basic Java syntax including:
- How to create, compile, and execute simple Java programs
- Using arrays, loops, if/else statements, and comparing strings
- Building one-dimensional and multi-dimensional arrays
- Common data structures like Vector and Hashtable
- Errors handling and the Collections Framework
At Ullink, our java heap are usually pretty large (up to 256GB) and we are dealing with large volume of data. But most of the space consumed in the heap are not business data as we may intuitively think, it is data structures!
In this presentation I would like to show you what are the cost of java objects, and the usual suspects in our data structures (Lists, Maps, Strings) and what we can do about this.
At Ullink, our java heap are usually pretty large (up to 256GB) and we are dealing with large volume of data. But most of the space consumed in the heap are not business data as we may intuitively think, it is data structures!
In this presentation I would like to show you what are the cost of java objects, and the usual suspects in our data structures (Lists, Maps, Strings) and what we can do about this.
This session will take you on a tour of several languages that on the surface only share one thing in common – they all run on JVM as the execution platform. However, despite completely different appearances of Scala, Clojure, Jython and Groovy, we will demonstrate that they have some important commonalities. You will also see the emerging importance of JVM as a generic platform (as opposed to focusing on Java the language).
During the session we will implement a solution to a simple problem in each language, then compare these languages to Java. These solutions, while simple, will nonetheless highlight some of the common principles and implementation patterns that exist across the languages based on different paradigms. The solutions will also show how these approaches are different from implementation patterns common in Java.
This session will take you on a tour of several languages that on the surface only share one thing in common – they all run on JVM as the execution platform. However, despite completely different appearances of Scala, Clojure, Jython and Groovy, we will demonstrate that they have some important commonalities. You will also see the emerging importance of JVM as a generic platform (as opposed to focusing on Java the language).
During the session we will implement a solution to a simple problem in each language, then compare these languages to Java. These solutions, while simple, will nonetheless highlight some of the common principles and implementation patterns that exist across the languages based on different paradigms. The solutions will also show how these approaches are different from implementation patterns common in Java.
Basic java important interview questions and answers to secure a jobGaruda Trainings
P2Cinfotech is one of the leading, Online IT Training facilities and Job Consultant, spread all over the world. We have successfully conducted online classes on various Software Technologies that are currently in Demand. To name a few, we provide quality online training for QA, QTP, Manual Testing, HP LoadRunner, BA, Java Technologies, SEO, Web Technologies, .NET, Oracle DBA etc.
A peep into Vodafone's Club 2020 model for bringing advertisers to the consumers. Avery good example for Intelligent Push Pull Marketing or You can also call it Surrogate Spamming :)
Uhren mit Design - ausgezeichnet mit dem Red Dot Awardred-dot-award
Der Red Dot ist die renommierte Auszeichnung für hohe Designqualität. Mit dem begehrten Qualitätssiegel prämiert die international besetzte Jury ausschließlich Produkte, die sich durch ihre hervorragende Gestaltung deutlich von vergleichbaren Entwürfen abheben. Der Red Dot Design Award, dessen Ursprünge bis 1955 zurückreichen, ist heute einer der größten und renommiertesten Wettbewerbe der Welt. Im Jahr 2013 verzeichnete er mehr als 15.500 Einreichungen aus 70 Nationen. So dokumentiert Red Dot heute in drei Disziplinen – von Produkt-über Kommunikationsdesign bis hin zu Konzepten – die prägnantesten Trends und besten Designs der Welt. Im der Kategorie Uhren und Schmuck wurden 2013 insgesamt 21 Produkte ausgezeichnet, davon 16 Uhren
TwEVS - An idea for using twitter as a student owned electronic voting systemMartin Hawksey
Presentation on how twitter could be used as an electronic voting system (using Yahoo Pipes and Google Chart API). Presented at e-Learning Alliance FE/HE SIG, St Andrews 29th Sept. 2009
Related posts on my work with voting systems here http://mashe.hawksey.info/2010/01/mashe-review-evs/
Static analysis: Around Java in 60 minutesAndrey Karpov
Theory
Code quality (bugs, vulnerabilities)
Methodologies of code protection against defects
Code Review
Static analysis and everything related to it
Tools
Existing tools of static analysis
SonarQube
PVS-Studio for Java what is it?
Several detected examples of code with defects
More about static analysis
Conclusions
ZeroSpace is a part of Woxa Technology where industrial trainer are ready to trained you.Take a demo class and choose your future in the programming field. We offer to learn in latest technology with live project which is demanding.
feel free to contact us-: 8471003400
Woxa Technologies have great industrial exoerts in java field they work on the live projects with students they are not teacher they are industrial trainer.
for more information 8471003400
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMERAndrey Karpov
Theory
Code quality (bugs, vulnerabilities)
Methodologies of code protection against defects
Code Review
Static analysis and everything related to it
Tools
Existing tools of static analysis
SonarQube
PVS-Studio for Java what is it?
Several detected examples of code with defects
More about static analysis
Conclusions
Since its first public release over two decades ago, the Java platform has become ubiquitous in virtually all areas of computing; from embedded systems to enterprise applications. As the demands of modern software development have evolved, so too have programming languages. There are many languages on the Java platform designed to be a “better Java”; though none are as widespread as Java itself. Despite the somewhat conservative nature of Java as a language, there have been a number of notable additions designed to address the challenges developers face without breaking compatibility. This presentation aims to provide an overview of the newer language features and APIs in recent releases of Java in the hope of increasing developer productivity.
MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...Howard Greenberg
Wondering how to take advantage of Java and Managed Beans in XPages? To do this requires knowing how to store data in Java objects and a good understanding of Maps, Trees, Lists, and Sets. No, we are not talking about Google Maps or those big green things in forests but different Java interfaces! Come learn different programming models to use when storing application configuration information, speeding up lookups to Domino data and feeding data to repeat and table controls. Learn how to build reports from different data sources. Plus, we will also look at working with dates and numbers in Java and Domino. Finally, we will review the Domino Java APIs and an alternative, the OpenNTF Domino API.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
2. Basic Java Syntax2 www.corewebprogramming.com
Agenda
• Creating, compiling, and executing simple
Java programs
• Accessing arrays
• Looping
• Using if statements
• Comparing strings
• Building arrays
– One-step process
– Two-step process
• Using multidimensional arrays
• Manipulating data structures
• Handling errors
3. Basic Java Syntax3 www.corewebprogramming.com
Getting Started
• Name of file must match name of class
– It is case sensitive, even on Windows
• Processing starts in main
– public static void main(String[] args)
– Routines usually called “methods,” not “functions.”
• Printing is done with System.out
– System.out.println, System.out.print
• Compile with “javac”
– Open DOS window; work from there
– Supply full case-sensitive file name (with file extension)
• Execute with “java”
– Supply base class name (no file extension)
4. Basic Java Syntax4 www.corewebprogramming.com
Example
• File: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world.");
}
}
• Compiling
DOS> javac HelloWorld.java
• Executing
DOS> java HelloWorld
Hello, world.
5. Basic Java Syntax5 www.corewebprogramming.com
More Basics
• Use + for string concatenation
• Arrays are accessed with []
– Array indices are zero-based
– The argument to main is an array of strings that
correspond to the command line arguments
• args[0] returns first command-line argument
• args[1] returns second command-line argument
• Etc.
• The length field gives the number of
elements in an array
– Thus, args.length gives the number of command-
line arguments
– Unlike in C/C++, the name of the program is not inserted
into the command-line arguments
6. Basic Java Syntax6 www.corewebprogramming.com
Example
• File: ShowTwoArgs.java
public class ShowTwoArgs {
public static void main(String[] args) {
System.out.println("First arg: " +
args[0]);
System.out.println("Second arg: " +
args[1]);
}
}
7. Basic Java Syntax7 www.corewebprogramming.com
Example (Continued)
• Compiling
DOS> javac ShowTwoArgs.java
• Executing
DOS> java ShowTwoArgs Hello World
First args Hello
Second arg: Class
DOS> java ShowTwoArgs
[Error message]
8. Basic Java Syntax8 www.corewebprogramming.com
Looping Constructs
• while
while (continueTest) {
body;
}
• do
do {
body;
} while (continueTest);
• for
for(init; continueTest; updateOp) {
body;
}
9. Basic Java Syntax9 www.corewebprogramming.com
While Loops
public static void listNums1(int max) {
int i = 0;
while (i <= max) {
System.out.println("Number: " + i);
i++; // "++" means "add one"
}
}
10. Basic Java Syntax10 www.corewebprogramming.com
Do Loops
public static void listNums2(int max) {
int i = 0;
do {
System.out.println("Number: " + i);
i++;
} while (i <= max);
// ^ Don’t forget semicolon
}
12. Basic Java Syntax12 www.corewebprogramming.com
Aside: Defining Multiple
Methods in Single Class
public class LoopTest {
public static void main(String[] args) {
listNums1(5);
listNums2(6);
listNums3(7);
}
public static void listNums1(int max) {…}
public static void listNums2(int max) {…}
public static void listNums3(int max) {…}
}
13. Basic Java Syntax13 www.corewebprogramming.com
Loop Example
• File ShowArgs.java:
public class ShowArgs {
public static void main(String[] args) {
for(int i=0; i<args.length; i++) {
System.out.println("Arg " + i +
" is " +
args[i]);
}
}
}
14. Basic Java Syntax14 www.corewebprogramming.com
If Statements
• Single Option
if (boolean-expression) {
statement;
}
• Multiple Options
if (boolean-expression) {
statement1;
} else {
statement2;
}
15. Basic Java Syntax15 www.corewebprogramming.com
Boolean Operators
• ==, !=
– Equality, inequality. In addition to comparing primitive
types, == tests if two objects are identical (the same
object), not just if they appear equal (have the same
fields). More details when we introduce objects.
• <, <=, >, >=
– Numeric less than, less than or equal to, greater than,
greater than or equal to.
• &&, ||
– Logical AND, OR. Both use short-circuit evaluation to
more efficiently compute the results of complicated
expressions.
• !
– Logical negation.
16. Basic Java Syntax16 www.corewebprogramming.com
Example: If Statements
public static int max2(int n1, int n2) {
if (n1 >= n2)
return(n1);
else
return(n2);
}
17. Basic Java Syntax17 www.corewebprogramming.com
Strings
• String is a real class in Java, not an array of
characters as in C and C++.
• The String class has a shortcut method to
create a new object: just use double quotes
– This differs from normal objects, where you use the new
construct to build an object
• Use equals to compare strings
– Never use ==
18. Basic Java Syntax18 www.corewebprogramming.com
Strings: Common Error
public static void main(String[] args) {
String match = "Test";
if (args.length == 0) {
System.out.println("No args");
} else if (args[0] == match) {
System.out.println("Match");
} else {
System.out.println("No match");
}
}
• Prints "No match" for all inputs
– Fix:
if (args[0].equals(match))
19. Basic Java Syntax19 www.corewebprogramming.com
Building Arrays:
One-Step Process
• Declare and allocate array in one fell swoop
type[] var = { val1, val2, ... , valN };
• Examples:
int[] values = { 10, 100, 1000 };
Point[] points = { new Point(0, 0),
new Point(1, 2),
... };
20. Basic Java Syntax20 www.corewebprogramming.com
Building Arrays:
Two-Step Process
• Step 1: allocate an array of references:
type[] var = new type[size];
• Eg:
int[] values = new int[7];
Point[] points = new Point[someArray.length];
• Step 2: populate the array
points[0] = new Point(...);
points[1] = new Point(...);
...
Points[6] = new Point(…);
• If you fail to populate an entry
– Default value is 0 for numeric arrays
– Default value is null for object arrays
21. Basic Java Syntax21 www.corewebprogramming.com
Multidimensional Arrays
• Multidimensional arrays are implemented as
arrays of arrays
int[][] twoD = new int[64][32];
String[][] cats = { { "Caesar", "blue-point" },
{ "Heather", "seal-point" },
{ "Ted", "red-point" } };
• Note: the number of elements in each row (dimension)
need not be equal
int[][] irregular = { { 1 },
{ 2, 3, 4},
{ 5 },
{ 6, 7 } };
22. Basic Java Syntax22 www.corewebprogramming.com
TriangleArray: Example
public class TriangleArray {
public static void main(String[] args) {
int[][] triangle = new int[10][];
for(int i=0; i<triangle.length; i++) {
triangle[i] = new int[i+1];
}
for (int i=0; i<triangle.length; i++) {
for(int j=0; j<triangle[i].length; j++) {
System.out.print(triangle[i][j]);
}
System.out.println();
}
}
}
24. Basic Java Syntax24 www.corewebprogramming.com
Data Structures
• Java 1.0 introduced two synchronized data
structures in the java.util package
– Vector
• A strechable (resizeable) array of Objects
• Time to access an element is constant regardless of
position
• Time to insert element is proportional to the size of the
vector
• In Java 2 (eg JDK 1.2 and later), use ArrayList
– Hashtable
• Stores key-value pairs as Objects
• Neither the keys or values can be null
• Time to access/insert is constant
• In Java 2, use HashMap
25. Basic Java Syntax25 www.corewebprogramming.com
Useful Vector Methods
• addElement/insertElementAt/setElementAt
– Add elements to the vector
• removeElement/removeElementAt
– Removes an element from the vector
• firstElement/lastElement
– Returns a reference to the first and last element, respectively
(without removing)
• elementAt
– Returns the element at the specified index
• indexOf
– Returns the index of an element that equals the object specified
• contains
– Determines if the vector contains an object
26. Basic Java Syntax26 www.corewebprogramming.com
Useful Vector Methods
• elements
– Returns an Enumeration of objects in the vector
Enumeration elements = vector.elements();
while(elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
• size
– The number of elements in the vector
• capacity
– The number of elements the vector can hold before
becoming resized
27. Basic Java Syntax27 www.corewebprogramming.com
Useful Hashtable Methods
• put/get
– Stores or retrieves a value in the hashtable
• remove/clear
– Removes a particular entry or all entries from the hashtable
• containsKey/contains
– Determines if the hashtable contains a particular key or element
• keys/elements
– Returns an enumeration of all keys or elements, respectively
• size
– Returns the number of elements in the hashtable
• rehash
– Increases the capacity of the hashtable and reorganizes it
28. Basic Java Syntax28 www.corewebprogramming.com
Collections Framework
• Additional data structures added by Java 2
Platform
Collection
Set
SortedSet
List
ArrayList
LinkedList
Vector†
HashSet
TreeSet
Map
SortedMap
HashMap
Hashtable†
TreeMap
†Synchronized AccessInterface Concrete class
29. Basic Java Syntax29 www.corewebprogramming.com
Collection Interfaces
• Collection
– Abstract class for holding groups of objects
• Set
– Group of objects containing no duplicates
• SortedSet
– Set of objects (no duplicates) stored in ascending order
– Order is determined by a Comparator
• List
– Physically (versus logically) ordered sequence of objects
• Map
– Stores objects (unordered) identified by unique keys
• SortedMap
– Objects stored in ascending order based on their key value
– Neither duplicate or null keys are permitted
30. Basic Java Syntax30 www.corewebprogramming.com
Collections Class
• Use to create synchronized data structures
List list = Collection.synchronizedList(new ArrayList());
Map map = Collections.synchronizedMap(new HashMap());
• Provides useful (static) utility methods
– sort
• Sorts (ascending) the elements in the list
– max, min
• Returns the maximum or minimum element in the
collection
– reverse
• Reverses the order of the elements in the list
– shuffle
• Randomly permutes the order of the elements
31. Basic Java Syntax31 www.corewebprogramming.com
Wrapper Classes
• Each primitive data type has a
corresponding object (wrapper class)
– The data is stored as an immutable field of the object
Primitive Corresponding
Data Type Object Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
32. Basic Java Syntax32 www.corewebprogramming.com
Wrapper Uses
• Defines useful constants for each data type
– For example,
Integer.MAX_VALUE
Float.NEGATIVE_INFINITY
• Convert between data types
– Use parseXxx method to convert a String to the
corresponding primitive data type
try {
String value = "3.14e6";
Double d = Double.parseDouble(value);
} catch (NumberFormatException nfe) {
System.out.println("Can't convert: " + value);
}
33. Basic Java Syntax33 www.corewebprogramming.com
Wrappers: Converting Strings
Data Type Convert String using either …
byte Byte.parseByte(string )
new Byte(string ).byteValue()
short Short.parseShort(string )
new Short(string ).shortValue()
int Integer.parseInteger(string )
new Integer(string ).intValue()
long Long.parseLong(string )
new Long(string ).longValue()
float Float.parseFloat(string )
new Float(string ).floatValue()
double Double.parseDouble(string )
new Double(string ).doubleValue()
34. Basic Java Syntax34 www.corewebprogramming.com
Error Handling: Exceptions
• In Java, the error-handling system is based
on exceptions
– Exceptions must be handed in a try/catch block
– When an exception occurs, process flow is immediately
transferred to the catch block
• Basic Form
try {
statement1;
statement2;
...
} catch(SomeException someVar) {
handleTheException(someVar);
}
36. Basic Java Syntax36 www.corewebprogramming.com
Throwable Types
• Error
– A non-recoverable problem that should not be caught
(OutOfMemoryError, StackOverflowError, …)
• Exception
– An abnormal condition that should be caught and handled
by the programmer
• RuntimeException
– Special case; does not have to be caught
– Usually the result of a poorly written program (integer
division by zero, array out-of-bounds, etc.)
• A RuntimeException is considered a bug
37. Basic Java Syntax37 www.corewebprogramming.com
Multiple Catch Clauses
• A single try can have more that one catch
clause
– If multiple catch clauses are used, order them from the
most specific to the most general
– If no appropriate catch is found, the exception is
handed to any outer try blocks
• If no catch clause is found within the method, then the
exception is thrown by the method
try {
...
} catch (ExceptionType1 var1) {
// Do something
} catch (ExceptionType2 var2) {
// Do something else
}
38. Basic Java Syntax38 www.corewebprogramming.com
Try-Catch, Example
...
BufferedReader in = null;
String lineIn;
try {
in = new BufferedReader(new FileReader("book.txt"));
while((lineIn = in.readLine()) != null) {
System.out.println(lineIn);
}
in.close();
} catch (FileNotFoundException fnfe ) {
System.out.println("File not found.");
} catch (EOFException eofe) {
System.out.println("Unexpected End of File.");
} catch (IOException ioe) {
System.out.println("IOError reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump
}
39. Basic Java Syntax39 www.corewebprogramming.com
The finally Clause
• After the final catch clause, an optional
finally clause may be defined
• The finally clause is always executed,
even if the try or catch blocks are exited
through a break, continue, or return
try {
...
} catch (SomeException someVar) {
// Do something
} finally {
// Always executed
}
40. Basic Java Syntax40 www.corewebprogramming.com
Thrown Exceptions
• If a potential exception is not handled in the
method, then the method must declare that
the exception can be thrown
public SomeType someMethod(...) throws SomeException {
// Unhandled potential exception
...
}
– Note: Multiple exception types (comma separated) can be
declared in the throws clause
• Explicitly generating an exception
throw new IOException("Blocked by firewall.");
throw new MalformedURLException("Invalid protocol");
41. Basic Java Syntax41 www.corewebprogramming.com
Summary
• Loops, conditional statements, and array
access is the same as in C and C++
• String is a real class in Java
• Use equals, not ==, to compare strings
• You can allocate arrays in one step or in two
steps
• Vector or ArrayList is a useful data
structure
– Can hold an arbitrary number of elements
• Handle exceptions with try/catch blocks