Introduction to Packages Session 18. Java Simplified / Session 18 / 2 of 40 Review Data may get corrupted when two or more threads access the same variable.

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Java Programming Strings Chapter 7.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Fundamental Programming Structures in Java: Strings.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Copyright © 2012 Accenture All Rights Reserved.Copyright © 2012 Accenture All Rights Reserved. Accenture, its logo, and High Performance Delivered are.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Introduction to Java Java Translation Program Structure
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Chapter 7: Characters, Strings, and the StringBuilder.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Copyright Curt Hill Variables What are they? Why do we need them?
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Classes, Interfaces and Packages
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Multithreading and Garbage Collection Session 16.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
JAVA MULTIPLE CHOICE QUESTION.
Chapter 7 User-Defined Methods.
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Multithreaded Programming in Java
Java Programming: From Problem Analysis to Program Design, 4e
Primitive Types Vs. Reference Types, Strings, Enumerations
EE422C - Software Design and Implementation II
CMSC 202 Static Methods.
Chapter 7: Strings and Characters
Unit-2 Objects and Classes
Java Programming Language
Introduction to Java Programming
The Building Blocks Classes: Java class library, over 1,800 classes:
Multithreading.
Units with – James tedder
Multithreading in java.
Java Basics Data Types in Java.
Chap 2. Identifiers, Keywords, and Types
String Class.
Presentation transcript:

Introduction to Packages Session 18

Java Simplified / Session 18 / 2 of 40 Review Data may get corrupted when two or more threads access the same variable or object at the same time. The method isAlive() returns true if the thread upon which it is called is still running. The method join() will wait until the thread on which it is called terminates. Synchronization is a process that ensures that the resource will be used by only one thread at a time. Synchronization does not provide any benefit for single threaded programs. In addition, their performance is three to four times slower than their non-synchronized counterparts. The method wait() tells the calling thread to give up the monitor and enter the sleep state till some other thread enters the same monitor and calls the method notify().

Java Simplified / Session 18 / 3 of 40 Review Contd… The method notify() wakes up or notifies the first thread that called wait() on the same object. The method notifyAll() wakes up or notifies all the threads that called wait() on the same object. A deadlock occurs when two threads have a circular dependency on a pair of synchronized objects. Garbage collection in Java is a process whereby the memory allocated to objects, which are no longer in use, may be reclaimed or freed. The garbage collector runs as a low priority thread and we can never predict when it will collect the objects.

Java Simplified / Session 18 / 4 of 40 Objectives Discuss the java.lang package Identify the various Wrapper classes Explain the String and StringBuffer classes Discuss the concept of immutability Identify the methods of the following classes and interfaces Math System Object Class ThreadGroup Runtime

Java Simplified / Session 18 / 5 of 40 Code libraries The basic idea behind using a code library is to sort out files or functions based on their functionality. Using these predefined codes saves a lot of coding time. In C libraries are known as header files, in C++ as class libraries and in Java as packages. A library comprises a group of related files. For example: a math library will contain functions or subroutines that are used in mathematical calculations.

Java Simplified / Session 18 / 6 of 40 Creating packages in Java In Java, a package is a combination of classes, interfaces and sub-packages. For example: java.awt package has a sub- package called event. A package in Java can be created by including a package statement as the first statement in a Java program. Syntax to define a package is: package ;

Java Simplified / Session 18 / 7 of 40 Creating packages in Java Contd… When a Java program is executed, the JVM searches for the classes used within the program on the file system. Uses one of two elements to find a class: The package name The directories listed in the CLASSPATH environment variable If no CLASSPATH is defined, then JVM looks for the default java\lib directory and the current working directory.

Java Simplified / Session 18 / 8 of 40 Example package mypackage; public class Palindrome { public boolean test(String str) { char givenstring[]; char reverse[] = new char[str.length()]; boolean flag = true; int count = 0,ctr = 0; givenstring = str.toCharArray(); for (count = str.length()-1;count >= 0;count--) { reverse[ctr] = givenstring[count]; ctr++; } for (count = 0;count < str.length();count++) { if (reverse[count] != givenstring[count]) flag = false; } return flag; } import mypackage.*; class Palintest { public static void main(String[] args) { Palindrome objPalindrome = new Palindrome(); System.out.println(objPalindrome.test(args[0])); } Output

Java Simplified / Session 18 / 9 of 40 Points to be considered Classes that are intended to be used outside the package within other programs must be declared public. If two or more packages define a class with the same name and a program happens to import both packages, then the full name of the class with the package name must be used to avoid conflict.

Java Simplified / Session 18 / 10 of 40 Packages and Access Control Packages act as a container for classes and other subordinate packages. Classes are containers of data and code. Class is the smallest unit of abstraction. There are four access specifiers: public, private, protected and default or no modifier.

Java Simplified / Session 18 / 11 of 40 Packages and Access Control Contd… A public member of a class can be accessed from anywhere; within the package, outside the package, within a subclass, as well as within a non-subclass. A member of a class that is declared private can be accessed only within the class but nowhere outside the class.

Java Simplified / Session 18 / 12 of 40 Packages and Access Control Contd… A protected member of a class can be accessed from any class in the same package and from a subclass that is outside the package. If no access specifier is given, the member would be accessible within any class in the same package but not outside the package.

Java Simplified / Session 18 / 13 of 40 Wrapper Classes Wrapper classes are a part of java.lang package. They encapsulate simple primitive types in the form of classes. It is useful whenever we need object representations of primitive types. All numeric Wrapper classes extend the abstract superclass Number.

Java Simplified / Session 18 / 14 of 40 Wrapper Classes Contd… The six numeric Wrapper classes are Double, Float, Byte, Short, Integer and Long. Double and Float are wrapper classes for floating point values of type double and float respectively. Byte, Short, Integer and Long classes are wrappers for byte, short, int and long data types.

Java Simplified / Session 18 / 15 of 40 Wrapper Classes Contd… Character is a wrapper class for the primitive char data type. Boolean is a wrapper class for boolean values.

Java Simplified / Session 18 / 16 of 40 Example class NumberWrap { public static void main(String[] args) { String number = args[0]; Byte byNum = Byte.valueOf(number); Short shNum = Short.valueOf(number); Integer num = Integer.valueOf(number); Long lgNum = Long.valueOf(number); System.out.println("Output"); System.out.println(byNum); System.out.println(shNum); System.out.println(num); System.out.println(lgNum); } Output

Java Simplified / Session 18 / 17 of 40 Example Contd… class TestCharacterMethods { public static void main(String[] args) { int count; char values[] = {'*','7','p',' ','P'}; for(count = 0 ; count < values.length ; count++) { if(Character.isDigit(values[count])) System.out.println(values[count]+" is a digit"); if(Character.isLetter(values[count])) System.out.println(values[count]+" is a letter"); f(Character.isWhitespace(values[count])) System.out.println(values[count]+" is whitespace"); if(Character.isUpperCase(values[count])) System.out.println(values[count]+" is uppercase"); if(Character.isLowerCase(values[count])) System.out.println(values[count]+" is lowercase"); if(Character.isUnicodeIdentifierStart(values[count])) System.out.println(values[count]+" is allowed as first character of Unicode identifier"); } Output

Java Simplified / Session 18 / 18 of 40 String class In Java, a string literal is an object of type String class. Hence manipulation of strings will be done through the use of the methods provided by the String class. Every time we need an altered version of the String, a new string object is created with the modifications in it.

Java Simplified / Session 18 / 19 of 40 String Class Contd… String length(): This method determines the length of a string. The == operator and equals() method can be used for string comparison. The == operator checks if the two operands being used are one and the same object. The equals() method checks if the contents of the two operands are the same.

Java Simplified / Session 18 / 20 of 40 Example class Stringdemo { public static void main(String args[]) { String ans1, ans2,ans3,ans4; ans1 = new String("Answer"); ans2 = "Answer"; ans4 = new String("ANSWER"); ans3 = new String("Answer"); if(ans1 == ans2) System.out.println("ans1 and ans2 are same object"); if(ans1 == ans3) System.out.println("ans1 and ans3 are same object"); if(ans1.equals(ans2)) System.out.println("ans1 and ans2 have same content"); if(ans1.equalsIgnoreCase(ans4)) System.out.println("ans1 and ans4 have same content"); if(ans1.compareTo("Answers") == 0) System.out.println("Same content alpabetically"); if(ans1.startsWith("A")) System.out.println("Starts with A"); if(ans1.endsWith("r")) System.out.println("Ends with r"); } Output

Java Simplified / Session 18 / 21 of 40 String Class Contd… Searching Strings: The String class also provides a variety of methods to perform search operations. indexOf() method searches within a string for a given character or String. The String class provides a number of methods for String extraction or character extraction. In situations where we need to access parts of a string, these methods prove useful. The method toLowerCase() and toUpperCase() will convert all characters in a string either to lower case or upper case. Both the methods return a String object.

Java Simplified / Session 18 / 22 of 40 Example class StringTest { public static void main(String[] args) { String name = args[0]; if(name.startsWith("M")) System.out.println("Hey my name also starts with an M! "); int length = name.length(); System.out.println("Your name has "+length+" characters"); String name_in_caps = name.toUpperCase(); System.out.println(name_in_caps); } Output

Java Simplified / Session 18 / 23 of 40 Immutability Strings in Java once created cannot be changed directly. This is known as immutability in Strings.

Java Simplified / Session 18 / 24 of 40 Example class Testing { public static void main(String[] args) { String str = "Hello"; str.concat("And Goodbye"); System.out.println(str); } Output

Java Simplified / Session 18 / 25 of 40 StringBuffer class To overcome immutability, Java provides the StringBuffer class, which represents a mutable sequence of characters. A StringBuffer is used to represent a string that can be modified. Whenever there is a concatenation operator (+) used with Strings, a StringBuffer object is automatically created.

Java Simplified / Session 18 / 26 of 40 Example class ConcatDemo { public static void main(String[] args) { String str = "Hello"; StringBuffer sbObj = new StringBuffer(str); str = sbObj.append(" And Goodbye").toString(); System.out.println(str); } Output

Java Simplified / Session 18 / 27 of 40 Math class All the methods of this class are static. The class is final and hence cannot be subclassed. This class defines methods for basic numeric operations as well as geometric functions.

Java Simplified / Session 18 / 28 of 40 Example class MathDemo { public static void main(String[] args) { int num = 38; float num1 = 65.7f; System.out.println(Math.ceil(num)); System.out.println(Math.ceil(num1)); System.out.println(Math.floor(num)); System.out.println(Math.floor(num1)); System.out.println(Math.round(num)); System.out.println(Math.round(num1)); } Output

Java Simplified / Session 18 / 29 of 40 Runtime class Used for memory management and executing additional processes. Every Java program has a single instance of this class. We can determine memory allocation details by using totalMemory() and freeMemory() methods. Encapsulates the runtime environment.

Java Simplified / Session 18 / 30 of 40 class RuntimeDemo { public static void main(String[] args) { Runtime Objrun = Runtime.getRuntime(); Process Objprocess = null; try { Objprocess = Objrun.exec("calc.exe"); } catch(Exception e) { System.out.println("Error executing Calculator"); } Example Output

Java Simplified / Session 18 / 31 of 40 System class Provides facilities such as the standard input, output and error streams. Provides means to access properties associated with the Java runtime system. Fields of this class are in, out and err that represent the standard input, output and error respectively.

Java Simplified / Session 18 / 32 of 40 Example class EnvironmentProperty { public static void main(String[] args) { System.out.println(System.getProperty("java.class.path")); System.out.println(System.getProperty("java.home")); System.out.println(System.getProperty("java.class.version")); System.out.println(System.getProperty("java.specification.vendor")); System.out.println(System.getProperty("java.specification.version")); System.out.println(System.getProperty("java.vendor")); System.out.println(System.getProperty("java.vendor.url")); System.out.println(System.getProperty("java.version")); System.out.println(System.getProperty("java.vm.name")); } Output

Java Simplified / Session 18 / 33 of 40 “Class” Class Instance of this class encapsulates the run time state of an object in a running Java application. This allows us to retrieve information about the object during runtime.

Java Simplified / Session 18 / 34 of 40 Example interface A { final int id = 1; final String name = "diana"; } class B implements A { int deptno; } class ClassDemo { public static void main(String[] args) { A Obja = new B(); B Objb = new B( ); Class Objx; Objx = Obja.getClass(); System.out.println("Obja is object of type: "+ Objx.getName()); Objx = Objb.getClass(); System.out.println("Objb is object of type: "+ Objx.getName()); Objx = Objx.getSuperclass(); System.out.println("Objb's superclass is "+ Objx.getName()); } Output

Java Simplified / Session 18 / 35 of 40 Object class Object class is the superclass of all classes. Even if a user-defined class does not extend from any other class, it extends from the Object class by default.

Java Simplified / Session 18 / 36 of 40 Example class ObjectDemo { public static void main(String args[]) { if (args[0].equals("Aptech")) System.out.println("Yes, Aptech is the right choice!"); } Output

Java Simplified / Session 18 / 37 of 40 Thread, ThreadGroup and Runnable ThreadGroup is used to create a group of threads. Whenever it is necessary to manipulate a group of threads as a whole, it is handy to use the ThreadGroup class. Multithreading support in Java is provided by means of the Thread and ThreadGroup classes and the Runnable interface.

Java Simplified / Session 18 / 38 of 40 Example class ChildThread extends Thread { ChildThread (String name, ThreadGroup myth) { super(myth,name); System.out.println("Thread :"+this); start(); } public void run() { try { while (true) { System.out.println(getName()); Thread.sleep(1000); } catch(InterruptedException e) {} } class GroupingThread { public static void main(String[] args) { ThreadGroup OurGroup = new ThreadGroup("OurGroup"); ChildThread one = new ChildThread("First",OurGroup); ChildThread two = new ChildThread("Second",OurGroup); ChildThread three = new ChildThread("Third",OurGroup); System.out.println("Listed output"); OurGroup.list(); } Output

Java Simplified / Session 18 / 39 of 40 Summary A package is a group of related classes or files. We can create our own package by including the package command as the first statement in our Java code. The classes in a package must be saved under a folder that bears the same name as the package. The java.lang package is imported by default into every Java program. Wrapper classes encapsulate simple primitive types in the form of classes. A String literal in Java is an instance of the String class. The String class provides a variety of methods for searching and extracting portions of Strings. Though Strings themselves cannot be modified directly we can create new Strings by applying certain methods on them. The StringBuffer class is used as a building block for building Strings.

Java Simplified / Session 18 / 40 of 40 Summary Contd… Strings are immutable which means they are constant and their value cannot be changed. Math is a final class that defines methods for basic numeric operations as well as geometric functions. The Runtime class encapsulates the runtime environment and is typically used for memory management and running additional programs. The System class allows us to access the standard input, output and error streams, provides means to access properties associated with the Java runtime system and various environment properties. The Object class is the superclass of all classes. Instances of Class encapsulate the run time state of an object in a running Java application. Multithreading support in Java is provided by means of the Thread and ThreadGroup classes and the Runnable interface.