Introduction to Java PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides a foundational introduction to Java programming. It covers basic concepts and illustrates examples of Java programming constructs. The introduction highlights Java's object-oriented nature and emphasizes its use for programming applications.
Full Transcript
Introduction to Java History of Programming Languages Machine Languages (Assembly Languages) High-Level Languages Procedural Languages C Object-Oriented Languages C++ C# Java C vs Java Key differences...
Introduction to Java History of Programming Languages Machine Languages (Assembly Languages) High-Level Languages Procedural Languages C Object-Oriented Languages C++ C# Java C vs Java Key differences C Java Procedural Object-Oriented User-based Automatic memory memory management management Doesn’t support Supports threads multithreading No direct Exception handling mechanism for mechanism is handling available exceptions Introducing Java Programming language A syntax for developing a set of instructions to be executed on the computer Java features: Object-oriented Extremely powerful Easy to learn Easy to read and understand First Java Program Sample Java program: package com.mycompany.hello; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Java Code Structure Include custom Define a class Java package named "HelloWorld" package com.mycompany.hello; main() method – public class HelloWorld { the entry point public static void main(String[] args) { System.out.println("Hello World!"); } } Print text to standard output by calling the method println of the class System Formatting Java Code Class names begin with an uppercase package com.mycompany.helloworld; The '{' symbol is public class HelloWorld { at the end of the line public static void main(String[] args) { System.out.println("Hello World!"); } } The '} ' symbol The block is under the after the '{' corresponding symbol is line indented by a Object-Oriented Programming Object-Oriented Programming (OOP) is a methodology to design programs using classes and objects OOP Advantages Makes development and maintenance easy Provides data hiding Provides ability to simulate real- world events much more effectively Java is object-oriented Objects Classes Classes provide the structure for objects Define the prototype, act as a template Classes define: Set of attributes (state) Represented by fields Set of actions (behavior) Represented by methods Classes are data types Classes – Example Presenting a class in a UML diagram: Class Name Attribute BankAccount s (Fields) owner: String balance: double lock() Operatio deposit(sum:double) ns withdraw(sum:double (Method ) s) Objects An object is a concrete instance of a particular class Creating an object from a class is called instantiation Objects have state Set of values associated with their attributes Example: Class: BankAccount Objects: John's account, Peter's Objects – Example Obje Class johnAccount ct owner="John BankAccount Smith" balance=2000.0 owner: String Obje peterAccount balance: double ct owner="Peter lock() White" deposit(sum:double balance=150.0 ) withdraw(sum:doubl Obje janeAccount e) ct owner="Jane Green" balance=333.33 Defining Classes A class is defined by class keyword Identifier (name) A set of fields and methods in a separate code block class { // Fields Declaration // Methods Definition } Defining Classes - Example Define a class named 'Circle' Add a field of type double named 'radius' class Circle { double radius; // More code } Declaring Objects // Declare two variables of type Circle Circle c1; Circle c2; Circle c1; double r1 = c1.radius; // Will cause an error Value and Reference Types In Java there are two categories of types Value types – hold actual data Reference types – hold reference to data Placed in different areas of memory Value types exist in the execution stack Freed when become out of scope Value and Reference Types – Examples Value types Primitive types Examples: int, float, boolean Reference types Classes Strings Examples: String, Circle, BankAccount Memory Allocation int i = 12; boolean b = true; String str = "Hello"; Circle c1; Stack Heap i 12 … b true … str address1 Hello c1 null … … … Memory Allocation i = 55; b = false; str = "Good-bye"; c1 = new Cicrle(); Stack Heap i 55 … b false Good-bye str address2 Hello c1 address3 c1 object … … Constructor = new (); Creating Objects Objects are created in three steps: Declaration - a variable name with an object type (class name) Instantiation - new operator is used to create the object Initialization - a call to a constructor Examples: Circle c1; c1 = new Circle(); Circle c2 = new Circle(); // All steps in one line Destructors Destructor is a special method called automatically upon destruction of an object Destructors exist implicitly in Java They are part of the Garbage Collection Invoked when an instance of an object is no longer in use Accessing Fields in an Object. Circle c1 = new Circle(); c1.radius = 5; double local = c1.radius; Methods Methods manipulate the data of the object to which they belong or perform other tasks Defining methods in a class: Specify a method name, return type and a list of return parameters 1st types and 1st class Converter { names: type type name public double cadToUsd(double amount, double rate) { double result = amount * rate; 2nd return result; name } 2nd type } Accessing Methods in an Object Use the name of the object, followed by the name of the method, separated by dot Pass compatible values to method.() parameters // Create an object of Converter class Examples: Converter myConverter = new Converter(); // Call cadToUsd method double amount = myConverter.cadToUsd(100, 0.7); Parameters vs Arguments Parameter represents a value that the method expects to receive when called Method's declaration defines a parameter list Argument represents the value that is passed to a methodParameter when it is invoked public list double cadToUsd(double amount, double rate) {... } The calling code supplies the... argument list amount = myConverter.cadToUsd(200, 0.9); Argument list main Entry Point Creating a class with main method will allow it to be the main entry point for your application: public static void main(String args[]) {... } Packages Packaging is a way of categorizing classes Protects against name collisions Helps organizing source code Types of packages: User defined – created by individual developer Built-in package – already defined in Java like java.io.*, java.lang.*, etc NetBeans NetBeans – Integrated Development Environment (IDE) Development tool that facilitates: Writing code Designing user interfaces Compiling and executing applications Testing and debugging applications Browsing the help NetBeans – Example Creating New SE Application File New Project Choose Java Application (default) Creating New SE Application Project Name indicates the entire application name Project Location is the path where all files are created Main Class indicates the package and name for the main entry Code Execution Process Compile Machine Java Java JVM Code r Source Bytecod (Execute Code e d by CPU) Compile Runtime Time Time Capitalization Conventions Casing Styles – describe different ways to case identifiers Pascal Casing – first letter in the identifier and in each subsequent concatenated word is capitalized BackgroundColor Camel Casing – first letter of an identifier is lowercase, and the first letter of each subsequent concatenated word is capitalized Naming Conventions Use Pascal casing for all type names (classes) For example: Student, BankAccount Use Camel casing for parameter names, variables and methods For example: name, lastName, addCourse() Do not use '_', '&', '$' Use all uppercase for constants, '_' to separate words Java System Class Contains several useful class fields and methods: InputStream in – standard input stream PrintStream out – standard output stream System.out.println(data) – typical way to write a line of output data Java Scanner Class A simple text scanner for parsing primitive types and strings Breaks its input into tokens using a delimiter pattern A default delimiter is a whitespace The resulting tokens may then be converted into values of different types using the various next methods Scanner Constructors Scanner(File source) – scanner produces values scanned from the specified file Scanner(InputStream source) – scanner produces values from the specified input stream Scanner(Path source) – scanner produces values from the specified file Scanner(String source) – scanner produces values from the specified Scanner Common Methods hasNext() Returns true if the scanner has another token in its input Its primitive-type companion methods (such as hasNextInt() and hasNextByte()) return true if the next token that can be interpreted as a matching type This method may block while waiting for input to scan – the scanner does not advance past Scanner Common Methods next() Finds and returns the next complete token from this scanner Its primitive-type companion methods (nextInt(), nextDouble(), etc) scan the next token as a matching type Throws InputMismatchException if the next token does not match the specified type Scanner Common Methods close() When a Scanner is closed, it will close its input source or destination of data that can be closed Releases resources that the object is holding (such as open files) For more methods and usages refer to: http://docs.oracle.com/javase/19/do Scanner – Example Reading various types from console: // Create an object of Scanner // to read from standard input Scanner scanner = new Scanner(System.in); // Read a string String name = scanner.next(); // Read an int input int age = scanner.nextInt(); // Read a double input double price = scanner.nextDouble(); Scanner Code Examples Using delimiters other than whitespace: String input = "1 cut 2 cut red cut blue cut"; Scanner sc = new Scanner(input).useDelimiter("\\s*cut\\ s*"); System.out.println(sc.next()); System.out.println(sc.next()); System.out.println(sc.next()); System.out.println(sc.next()); Output: 1 2 red blue The String Class The String class provides many methods for safely creating, manipulating, and comparing strings String objects contain sequences of characters Strings use Unicode to support multiple languages and alphabets A string variable has null value until initialized String Accessors length() – gets the number of characters in the current String object charAt() – provides access to the char value (character) at a given position The Stringindex is in the range of [0 … str = "Hello!"; length()-1] int len = str.length(); // len = 6 char ch = str.charAt(1); // ch = 'e' index = 0 1 2 3 4 5 str[index] =H e l l o ! Comparing Strings Checking if the strings are equal or not: boolean equals(String str) – returns true if current string is equal to str, false otherwise boolean equalsIgnoreCase(String str) – case-insensitive Concatenating Strings There are two ways to combine strings: Using the concat() str1.concat(str2); method // returns a new string that is // str1 with str2 added to it at the end Using the + or the += operators String str = str1 + str2 + "end"; Any object can String name = "Peter"; be appended to a string: int age = 22; String full = name + " " + age; // "Peter 22" Searching in Strings Finding a character or substring within a given string: int indexOf(String str) – first occurrence int indexOf(String str, int fromIndex) – first occurrence starting at a given position int lastIndexOf(String str) – last occurrence Searching in Strings – Example String str = "Java Programming Course"; int index = str.indexOf("J"); // index = 0 index = str.indexOf("Course"); // index = 17 index = str.indexOf("COURSE"); // index = -1 // IndexOf is case-sensitive, -1 means not found index = str.indexOf("ram"); // index = 9 index = str.indexOf("r"); // index = 6 index = str.indexOf("r", 7); // index = 9 index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 … = J a v a str[index P r o g r a m m i … ] = Extracting Substrings Using the substring() method: String substring(int beginIndex, int endIndex) String welcome = "Welcome to the show!"; String middle = welcome.substring(8, 10); // middle is "to" String substring(int startIndex) String end = welcome.substring(8); // "to the show!" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 W e l c o m e t o t h e s h o w ! Replacing Substrings replaceAll(String str1, String str2) – replaces all occurrences of given string with another The recipe String result= is a new string "Icecream (strings + strawberry are + banana"; String replaced = recipe.replaceAll(" + ", ", "); immutable) // Icecream, strawberry, banana Summary Classes define specific structure for objects Objects are particular instances of a class and use this structure Fields contain object's data Methods provide functionality Constructors are invoked when creating new class instances