




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































ipin Enterprises Tantia Jogani Industrial Estate, Unit No. 2, Ground Floor, Sitaram Mill Compound, J.R. Boricha Marg, Mumbai - 400 011
Published by : Director Institute of Distance and Open Learning , University of Mumbai, Vidyanagari, Mumbai - 400 098.
July 2022, Print - I
Programme Co-ordinator :Shri Mandar Bhanushe Head, Faculty of Science and Technology, IDOL, University of Mumbai, Mumbai Course Co-ordinator : Mr. Sumedh Shejole Asst. Professor, IDOL, University of Mumbai, Mumbai
Editor : Mr Milind Thorat Assistant Professor K J Somaiya Institute of Engineering & IT Mumbai
Writers : Ahtesham Shaikh Anjuman-i-Islam's Akbar Peerbhoy College Vashi, Navi Mumbai
: Mrs. Vandana Maurya B.K. Birla College(Autonomous), Kalyan
: Dr. Manisha Divate Usha Pravin Gandhi College of Arts, Science and Commerce, Mumbai
DTP Composed and : Mumbai University Press Printed by Vidyanagari, Santacruz (E), Mumbai - 400098
Prof. Suhas Pednekar Vice-Chancellor, University of Mumbai,
Prof. Ravindra D. Kulkarni Prof. Prakash Mahanwar Pro Vice-Chancellor, Director, University of Mumbai, IDOL, University of Mumbai,
Course:
USCS
TOPICS (Credits : 02 Lectures/Week:03) Core Java
Objectives:
The objective of this course is to teach the learner how to use Object Oriented paradigm to develop
code and understand the concepts of Core Java and to cover-up with the pre-requisites of Core java.
Expected Learning Outcomes:
Unit I
The Java Language: Features of Java, Java programming format, Java Tokens, Java Statements, Java Data Types, Typecasting, Arrays OOPS : Introduction, Class, Object, Static Keywords, Constructors, this Key Word, Inheritance, super Key Word, Polymorphism (overloading and overriding), Abstraction, Encapsulation, Abstract Classes, Interfaces String Manipulations : String, String Buffer, String Tokenizer Packages: Introduction to predefined packages (java.lang, java.util, java.io, java.sql, java.swing), User Defined Packages, Access specifiers
Unit II
Exception Handling: Introduction, Pre-Defined Exceptions, Try-Catch-Finally, Throws, throw, User Defined Exception examples Multithreading: Thread Creations, Thread Life Cycle, Life Cycle Methods, Synchronization, Wait() notify() notify all() methods I/O Streams: Introduction, Byte-oriented streams, Character- oriented streams, File, Random access File, Serialization Networking: Introduction, Socket, Server socket, Client – Server Communication
Wrapper Classes: Introduction, Byte, Short, Integer, Long, Float, Double, Character, Boolean classes Collection Framework : Introduction, util Package interfaces, List, Set, Map, List interface & its classes, Set interface & its classes, Map interface & its classes
Unit III
Inner Classes : Introduction, Member inner class, Static inner class, Local inner class, Anonymous inner class AWT: Introduction, Components, Event-Delegation-Model, Listeners, Layouts, Individual components Label, Button, CheckBox, Radio Button, Choice, List, Menu, Text Field, Text Area
Textbook (s):
Additional Reference(s):
Core JAVA systems. Thus, the ability to create robust programs was given a high priority in the design of Java. To gain reliability, Java restricts a few key areas and forces to find your mistakes early in program development. At the same time, Java frees a programmer from having to worry about many of the most common causes of programming errors.
Multithreaded: Java supports multithreaded programming, which allows a programmer to write programs that performs multiple tasks simultaneously. The Java run-time system comes with an elegant and sophisticated solution for multi-process synchronization that helps to construct smoothly running interactive systems.
Architecture-neutral: Java was designed to support applications on networks composed of a variety of systems with a variety of CPU and operating system architectures. With Java, the same version of the application runs on all platforms. The Java compiler does this by generating bytecode instructions which have nothing to do with particular processor architecture. Rather, they are designed to be both easy to interpret on any machine and easily translated into native machine code on the fly.
Interpreted & High performance: Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be executed on any system that implements the Java Virtual Machine. Most previous attempts at cross- platform solutions have done so at the expense of performance. The Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler. Java run-time systems that provide this feature lose none of the benefits of the platform-independent code.
Distributed: Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network.
Dynamic: Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the Java environment, in which small fragments of byte code may be dynamically updated on a running system.
The Java Language
1) Package Section
It must be the first line of a java program or can be omitted if the class is to be kept only in the default package. The package statement defines a namespace in which classes are stored, based on functionality. If omitted, the classes are put into the default package, which has no name.
2) Import Section
Specifies the location to use a class or package into a program.
3) Class / Interface section
A java program may contain several classes or interfaces.
4) Class with Main Method
Every Java stand-alone program requires the main method as the starting point of the program. This is an essential part of a Java program. There may be many classes in a Java program code file, and only one class defines the main method.
Example:
// ----- 1 Package Section -------
Package mypack;
// -------- 2 Import Section -------
import java.util.Date; // This line will import only one class from the util package
import java.awt.*; // This line will import all classes available in awt package
// ----------- 3 Class / Interface Section ----------
class A {
// Class Body
}
interface B {
// Interface Body
}
// ----------- 4 Main Method Section ----------
public class Test{
public static void main(String[] args){
// body of main method
}
}
The Java Language Java keyword (reserved word) cannot be used for a variable name.
Examples of valid identifiers in java: num1, name, Resi_addr, Type_of_road, Int etc.
Examples of invalid identifiers in java: 1num, full-name, Resiaddr, Type*ofroad, int etc.
3. Literals: Literals are the value assigned to a variable;
Example: 10, “Mumbai”, 3.14, ‘Y’, ‘\n’ etc.
4. Operators: Operators are the symbols that performs operations. Java contains different types of operators like Arithmetic Operator (+,- ,*,/,%), Logical Operator (&&, ||, ~, ), Relational Operator(<, <=, >, >=, !=, ==), Bitwise Operators (&, |, ~), Shift Operators (<<, >>, >>>) , Assignment Operators(=, +=, -+, *=, /=, %=), Conditional Operator (?:), InstanceOf Operator 5. Separators: Separators are used to separate words, expressions, sentences, blocks etc.
Symbol Name Description
Space Used to separate tokens.
; Semicolon^ Used to separate the statements
( ) Parentheses^ Used to contain the lists of parameters in method definition and invocation. Also used for defining the precedence in expressions, containing expressions in control statements, and surrounding cast types.
{ } Braces^ Used to contains the values of automatically initialized arrays. Also used to define a block of code, for classes, methods, and local scopes.
[ ] Brackets^ Used to declare array types. Also used when dereferencing array values.
, Comma^ Separates consecutive identifiers in a variable declarations. Also used to chain statements together inside a for statement
. Period^ Used to separate packages names from subpackages and classes. Also used to separate a variable or method from a reference variable.
3 Java Statements
A statement specifies an action in a Java program. Statements in Java can be broadly classified into three categories:
Core JAVA
1. Declaration
A declaration statement is used to declare a variable, method or class.
For example: int num;
double PI = 3.14;
String name=”University of Mumbai;
int showResult(int a, int b);
2. Expression
An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.
Arithmetic Expression: ( A + B ) * C - ( D % E ) * ( - F + G )
Logical Expression: ~(m > n && x < y) != (m <= n || x >= y)
3. Flow Control By default, all the statements in a java program are executed in the order they appear in the program code. However sometime a set of statements need to be executed and a part to be skipped, also some part need to be repeated as long as a condition is true or till some fix number of iteration. Java programming language uses flow control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Java’s program control statements can be put into the following categories: Branching / selection, Looping / iteration, and jump control. Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion.
Core JAVA a default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place.
Example:
class ladderifelsetest{ public static void main(String[] args){ int num=10; if(num> 0){ System.out.println(“Number is +VE”); }
else if(num<0){
System.out.println(“Number is -VE”);
}
else {
System.out.println(“Number is ODD”);
}
} }
switch
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements.
General Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
The Java Language
casevalueN :
//statement sequence break;
default:
// default statement sequence
}
For versions of Java prior to JDK 7, expression must be of type byte, short, int, char, or an enumeration. JDK 7 onwards the switch expression can also be of type String.
Example:
class switchcasetest{ public static void main(String[] args){ int num=10; switch(num){ case 1: System.out.println(“Monday”);
break;
case 2: System.out.println(“Tuesday”);
break;
case 3: System.out.println(“Wednesday”);
break;
case 4: System.out.println(“Thursday”);
break;
case 5: System.out.println(“Friday”);
break;
case 6: System.out.println(“Saturday”);
break;
case 7: System.out.println(“Sunday”);
break;
The Java Language
do-while
Sometimes it is desirable to execute the body of a loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. Java provides a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.
General Syntax:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression.
Examples:
public class DoWhileDemo
{
public static void main(String args[])
{ int n = 10;
do{
System.out.println("Loop Executed Once even if condition is False" );
n - -;
} while(n > 10) ;
}
}
For
The for loop operates as follows. When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. It is important to understand that the
Core JAVA initialization expression is executed only once. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.
General Syntax: for(initialization; condition; increment / decrement expression) { // loop body } Examples: public class ForDemo { public static void main(String args[]) { for(int x = 1 ; x <=10 ; x++) { System.out.println("Loop Variable Value is : " + x); } } } There will be times when you will want to include more than one statement in the initialization and iteration portions of the for loop. Example: public class TwoVarFor { public static void main(String args[]) { int a, b ; for(a=1, b=4; a<= b; a++, b--){ System.out.println(“value of A is : “+a+” Value of B is : “+b); } } }
Core JAVA 4 Java Data Types
The Primitive Types: Java defines eight primitive types of data: byte , short , int , long , char , float , double , and boolean. The primitive types are also commonly referred to as simple types.
These can be put in four groups:
The smallest integer type is byte. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with raw binary data that may not be directly compatible with Java’s other built-in types. The most commonly used integer type is int. long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value.
2. Floating-point numbers This group includes float and double , which represent numbers with fractional precision. Name Width Approximate Range float 32 4 byte 1.4e–045 to 3.4e+ double 64 8 byte 4.9e–324 to 1.8e+
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision. Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high- speed mathematical calculations.
The Java Language
3. Characters This group includes char , which represents symbols in a character set, like letters and numbers. C++ char is 8 bit i.e. 256 symbols while java char uses 16 bit i.e. 65536 symbols to represent Unicode characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages and is a unification of character sets, such as Latin, Greek, Arabic, Cyrillic Hebrew, Katakana, Hangul, and many more. There is no signed char in java. char can also be used as an integer type on which you can perform arithmetic operations. Example: if char ans =’A’ then ans = ans + 5 will result ‘F’. 4. Boolean This group includes boolean , which is a special type for representing true/false values.
5 Typecasting
As a part of Java’s safety and robustness Java is a strongly typed language. Every variable has a type, every expression has a type, all assignments, whether explicit or via parameter passing in method calls is checked for type compatibility and every type is strictly defined. There are no automatic coercions or conversions of conflicting types. If the two types are compatible and the target type is equal to or larger than the source type JVM performs automatic type conversion. This type of conversion is also called implicit conversion or automatic type casting or widening conversion.
byte short int long or int float double
If the two types are incompatible and the target type is smaller than the source type then typecasting is required conversion. This type of conversion is also called explicit conversion or manual type casting or narrowing conversion.
General syntax: (type_type) value|expression
Eg. int a = (int) 3.14;
Truncation will occur when a floating-point value is assigned to an integer type, because integers do not have fractional component. For example, if the value 3.14 is assigned to an integer, the resulting value will simply be 3; the 0.14 will have been truncated.
Java also performs type promotion while evaluating mix mode expression. Java defines several type promotion rules that apply to expressions. They are as follows: First, all byte , short , and char values are promoted to int , as just described. Then, if one operand is a long , the whole expression is promoted to long. If one operand is a float , the entire expression is promoted to float. If any of the operands are double , the result is double.