Docsity

Java programming with, Summaries of Javascript programming

Toggle sidebar
bg1
SEMESTER-III
OOPS THROUGH JAVA
Unit 1. OOPsConcepts and Java Programming:
Introduction to Object-Orientedconcepts, procedural and object-oriented programming paradigm
Java programming: An Overview of Java, JavaEnvironment, Data types, Variables, constants, scope and life time of
variables, operators, typeconversionand casting, AcceptingInput fromtheKeyboard,Reading Input with
Java.util.Scanner Class, DisplayingOutput, Displaying Formatted Output with String.format(), Control Statements
Unit 2. Arrays and OOP Constructs:
Arrays, Command Line Arguments,Strings-String Class Methods
Classes & Objects: Creating Classes, declaringobjects, Methods, parameter passing, staticfieldsand methods,
Constructors, and
โ€˜
this
โ€™
keyword, overloading methods and access Inheritance:
Inheritance hierarchies, super and subclasses, member access rules,
โ€˜
super
โ€™
keyword, preventing inheritance: final
classesand methods, the object class and itsmethods; Polymorphism: Dynamic binding, method overriding,
abstract classes and methods;
Unit3. Interfaces, Packages & Exception Handling:
Interfaces VS Abstract classes, defining aninterface, implement interfaces, accessing implementations through
interface references, extending interface;
Packages: Defining,creating and accessing apackage, importing packages.
Exception Handling: Benefits of exception handling, the classification of exceptions, exception hierarchy, checked
exceptions and unchecked exceptions, usageof try, catch, throw, throwsand finally, rethrowingexceptions,
exception specification, built in exceptions, creatingown exception sub classes.
Unit 4. Multithreading & Stream based I/O:
Differences between multiple processes and multiple threads, thread states, thread life cycle, creating threads,
interrupting threads, threadpriorities, synchronizing threads, interthread communication.
Stream based I/O (java.io)
โ€“
The Streamclasses-Byte streamsand Character streams, Reading console Input and
Writing Console Output, File class, Readingand writing Files, The Console class, Serialization
Unit 5. GUI Programming with Swing:
Introduction, MVC architecture,components, containers. Understanding Layout Managers -Flow Layout, Border
Layout, Grid Layout, Card Layout, GridBag Layout. EventHandling- The Delegation event model- Events, Event
sources, Event Listeners, Eventclasses,Handlingmouse andkeyboard events, Adapterclasses
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download Java programming with and more Summaries Javascript programming in PDF only on Docsity!

SEMESTER-III

OOPS THROUGH JAVA

Unit 1. OOPs Concepts and Java Programming: Introduction to Object-Oriented concepts, procedural and object-oriented programming paradigm Java programming: An Overview of Java, Java Environment, Data types, Variables, constants, scope and life time of variables, operators, type conversion and casting, Accepting Input from the Keyboard, Reading Input with Java.util.Scanner Class, Displaying Output, Displaying Formatted Output with String.format(), Control Statements Unit 2. Arrays and OOP Constructs: Arrays, Command Line Arguments, Strings-String Class Methods Classes & Objects: Creating Classes, declaring objects, Methods, parameter passing, static fields and methods, Constructors, and โ€˜thisโ€™ keyword, overloading methods and access Inheritance: Inheritance hierarchies, super and subclasses, member access rules, โ€˜superโ€™ keyword, preventing inheritance: final classes and methods, the object class and its methods; Polymorphism: Dynamic binding, method overriding, abstract classes and methods; Unit 3. Interfaces, Packages & Exception Handling: Interfaces VS Abstract classes, defining an interface, implement interfaces, accessing implementations through interface references, extending interface; Packages: Defining, creating and accessing a package, importing packages. Exception Handling: Benefits of exception handling, the classification of exceptions, exception hierarchy, checked exceptions and unchecked exceptions, usage of try, catch, throw, throws and finally, rethrowing exceptions, exception specification, built in exceptions, creating own exception sub classes. Unit 4. Multithreading & Stream based I/O: Differences between multiple processes and multiple threads, thread states, thread life cycle, creating threads, interrupting threads, thread priorities, synchronizing threads, inter thread communication. Stream based I/O (java.io) โ€“ The Stream classes-Byte streams and Character streams, Reading console Input and Writing Console Output, File class, Reading and writing Files, The Console class, Serialization Unit 5. GUI Programming with Swing: Introduction, MVC architecture, components, containers. Understanding Layout Managers - Flow Layout, Border Layout, Grid Layout, Card Layout, GridBag Layout. Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event classes, Handling mouse and keyboard events, Adapter classes

  1. Basic Concepts of Object-Oriented Programming (OOP) OR Object -Oriented Concepts Object-Oriented Programming (OOP) is a popular programming paradigm that focuses on using objects and classes to build software. It models real-world problems using objects, which makes programs easier to understand, reuse, and maintain. In OOP, both data and functions are grouped together as a single unit. This helps in better control, security, and organization of code. Main Concepts of OOP:
  1. Class: o A class is a blueprint or template to create objects and it is a logical entity. o It defines data (variables) and methods (functions). o class ClassName { variables; methods; }
  2. Object: o An object is an instance of a class and it is a physical entity. o It represents a real-world entity like a student, car, or employee. o An object is used to access the properties (data) and perform the tasks (methods) defined in a class. o ClassName objectName = new ClassName();
  3. Encapsulation: o Encapsulation means wrapping data (properties) and methods (tasks) into a single class and protecting the data from direct access. o Achieved using access modifiers like private, public, etc.
  4. Abstraction: o Abstraction means hiding the internal implementation details and showing only the necessary features to the user. o In simple words: We tell the user WHAT to do, but hide HOW it is done.
  5. Inheritance: o It allows one class to acquire the properties of another class. o Promotes code reusability. o Example: A Car class can inherit from a Vehicle class.
  6. Polymorphism: o The ability of an object or method to take multiple forms and behave differently in different situations. o Types: Compile-time โ†’ Method Overloading
  1. An Overview of JAVA Java is a high-level, object-oriented, secure, robust, and platform-independent programming language. It is widely used for developing web applications, desktop applications, mobile applications, and many other software systems. History of Java Java was developed by James Gosling and his team at Sun Microsystems. The development of Java started in 1991 as part of a project called the Green Project. The original goal was to develop software for consumer electronic devices, such as televisions and set-top boxes.The team wanted a language that was simple, portable, reliable, and able to run on different devices. Initially, the language was called Oak.James Gosling chose the name Oak because there was an oak tree outside his office at Sun Microsystems. However, the name Oak was already a trademark, so the team had to find a new name. In 1995 , the language was renamed Java.The name Java was chosen by the development team during discussions about a new name. Java is also associated with coffee from the Indonesian island of Java. The name was short, unique, and easy to remember. This is why Java is strongly associated with coffee, including its famous coffee-cup

logo. โ˜• Java was officially released in 1995 by Sun Microsystems.

One of Java's most famous principles is:โ€œWrite Once, Run Anywhere.โ€ This means a Java program can be written once and run on different operating systems with the help of the Java Virtual Machine (JVM). Java source code is compiled into bytecode. This bytecode can run on any operating system that has a suitable JVM. Therefore, Java is called platform independent. Originally, Java was developed and maintained by Sun Microsystems. In 2010, Oracle Corporation acquired Sun Microsystems. After the acquisition, Oracle became responsible for the development and maintenance of Java. Oracle has continued to develop Java and release new versions with improvements, new features, performance enhancements, and security updates.

Major Features of Java Java provides many important features: โ— Simple โ€“ Easy to learn and use. โ— Object-Oriented โ€“ Uses classes and objects. โ— Platform Independent โ€“ Runs on different operating systems. โ— Secure โ€“ Provides features for secure application development. โ— Robust โ€“ Supports exception handling and automatic memory management. โ— Portable โ€“ Java programs can be moved between platforms. โ— Multithreaded โ€“ Allows multiple tasks to execute simultaneously. โ— High Performance โ€“ JVM technologies provide efficient execution.

  1. JAVA Environment The Java environment means the set of tools and components required to develop, compile, and run Java programs. The Java environment mainly consists of JDK, JRE, and JVM.
  1. JDK โ€“ Java Development Kit - JDK is used by developers to create Java programs. It contains:

โ— JRE โ— Compiler (javac) โ— Debugging and other development tools So, if we want to write and develop Java programs, we need the JDK.

  1. JRE โ€“ Java Runtime Environment - JRE provides the environment required to run Java programs. It contains: โ— JVM โ— Java class libraries โ— Supporting files JRE is mainly used for running Java applications.
  2. JVM โ€“ Java Virtual Machine - JVM is responsible for executing Java bytecode. It converts bytecode into instructions that the computer can understand. The JVM is also the main reason Java is platform independent. How Java Environment Works Java Program (.java) โ†“ Java Compiler (javac) โ†“ Bytecode (.class) โ†“ JVM โ†“ Output

โ— Use the Java interpreter (java) to run the bytecode. โ— Command: java Hello โ— Output: Hello, Java!

  1. Data Types A data type specifies what kind of data a variable can store. It tells the Java compiler what type of value is being stored and how that value should be handled. For example: int age = 20; Here, int is the data type, age is the variable, and 20 is the value. Java data types are mainly divided into two categories: Data Types | โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ†“ โ†“ Primitive Non-Primitive | | 8 basic types String, Array, Class, Object, Interface
  1. Primitive Data Types - Primitive data types are the basic, built-in data types provided by Java. They are used to store simple values directly. Java has 8 primitive data types.

Data Type Purpose Example byte Small whole numbers byte age = 20; short Small whole numbers short num = 1000; int Whole numbers int marks = 90; long Large whole numbers long population = 100000L; float Decimal numbers float price = 10.5f; double Decimal numbers double salary = 50000.50; char Single character char grade = 'A'; boolean True or false boolean pass = true;

  1. Non-Primitive Data Types - Non-primitive data types are reference types that are used to store or refer to objects and more complex data. Unlike primitive types, they are generally created using classes, arrays, or interfaces. Common examples are: String ,Array, Class, Object, Interface Example: String name = "Ravi"; int[] marks = {90, 80, 70}; Here: โ— String โ†’ stores a sequence of characters. โ— int[] โ†’ stores multiple integer values.

Example: class DataTypes { public static void main(String[] args) { int age = 20; double salary = 25000.50; char grade = 'A'; String name = "Ravi"; int[] marks = {90, 85, 95}; System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); System.out.println("Grade: " + grade); System.out.println("First Mark: " + marks[0]); } } Output Name: Ravi Age: 20 Salary: 25000. Grade: A First Mark: 90

โ— Destroyed when the method/block finishes execution. void method() { int x = 10; // x is local to this method }

  1. Instance Variable: โ— Declared inside a class but outside any method. โ— Each object of the class has its own copy. โ— Accessible by all instance methods. class Student { int rollNo; // Instance variable }
  2. Static Variable (Class Variable): โ— Declared inside a class with the keyword static. โ— Shared by all objects of the class. โ— Exists even if no objects are created. class Counter { static int count = 0; // Static variable }

7) Constants in Java

A constant is a fixed value th a t d o e s n o t c h a n g e d u rin g p ro g ra m e xe cu tio n. In J a va , y o u ca n d e fin e

co n s ta nts in tw o w a ys :

1. Literal Constants

2. Symbolic Constants (u s in g fin a l k e yw o rd ).

1. Literal Constants

โ— Literal m ea n s th e ex a ct va lu e w ritten in c o d e.

Constant Type Definition Syntax/Example

Integer Literal F ixe d w h o le-n u m b e r v a lu e in t x = 1 0 0 ;

Floating-point F ixe d d e cim a l v a lu e d o u b le d = 3 .1 4 ;

Character Literal S ing le ch a ra cte r e n clo s e d in s in g le q u o te s ch a r c = 'A ';

String Literal S eq u en c e o f c h a ra c te rs e n clo s e d in d o u b le q u o te s S trin g s = "J a v a ";

Boolean Literal tru e o r fa ls e b o o lea n b = fa ls e;

2. Symbolic Constants (final Variables)

โ— U s e th e f in a l m o d ifie r to d e cla re a constant variable w h o s e va lu e c a nn o t c h a n g e o n ce

in itia liz ed.

โ— N a m in g c o n v en tio n : UPPERCASE_WITH_UNDERSCORES.

Syntax:

fin a l d a ta T yp e C O N ST A N T_ N A M E = va lu e;

Example:

fin a l in t M A X _ S T U D E N T S = 5 0 ;

fin a l d o u b le P I = 3 .1 4 1 5 9 ;

fin a l S trin g C O M P A N Y = "A B C C o rp ";

โ— Attempting to reassign a f in a l va ria b le c au s e s a c o m p ile-tim e erro r.

Operator Description Example Result | Logical AND (5 > 3) || (3 < 4) Logical OR ! Logical NOT !(5 > 3) false

  1. Assignment Operators - Used to assign values to variables.

Operator Description Example Meaning = Simple assignment a = 10 Assign 10 to a += Add and assign a += 5 a = a + 5 -= Subtract and assign a -= 3 a = a - 3 *= Multiply and assign a *= 2 a = a * 2 /= Divide and assign a /= 4 a = a / 4 %= Modulus and assign a %= 3 a = a % 3

  1. Unary Operators - Operate on a single operand.

Operator Description Example Result ++ Increment by 1 a++ or ++a a = a + 1 -- Decrement by 1 a-- or --a a = a - 1

6.Ternary Operator (?:) โ— Conditional operator that acts as a shortcut for if-else. โ— Syntax: condition? expression1 : expression โ— If condition is true, evaluates expression1, else expression2. Example: int a = 10, b = 20; int max = (a > b)? a : b; // max = 20 System.out.println(max); // Output: 20

  1. instanceof Operator โ— Tests whether an object is an instance of a specified class or interface. โ— Returns true or false. Example: String s = "Hello"; if (s instanceof String) { System.out.println("s is a String"); } Output: s is a String

Example

public class OperatorExample { public static void main(String[] args) { int a = 10, b = 20, c = 5, d = 15; // Arithmetic operators int sum = a + b; System.out.println("Sum: " + sum); // Relational operators System.out.println("a == b " + (a == b)); // Logical operators boolean result = (a < b) && (b > c); System.out.println("Logical AND: " + result); // Assignment operators d += 5; System.out.println("d after += 5: " + d); } }

Output:

Sum: 30 a == b false Logical AND: true d after += 5: 20

  1. Type Conversion and Casting Type Conversion Type conversion = changing one data type into another automatically. Java automatically converts a smaller type โ†’ larger type. It happens automatically because no data loss occurs. This is called implicit conversion.

From To byte short, int, long, float, double short int, long, float, double int long, float, double long float, double float double

Example: int i = 100; long l = i; // int to long Type Casting Type casting = manually changing one data type into another.

Scanner sc = new Scanner(System.in); System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.println("Age = " + age); } } If the user enters: Enter your age: 20 Output: Age = 20

  1. Displaying Output, Displaying Formatted Output with String.format() What is Output? Output means displaying information on the screen. Java mainly uses: System.out.println(); System.out.print();

System.out.println() - It displays the output and then moves to the next line. System.out.println("Hello"); System.out.println("Java"); Output: Hello Java

System.out.print() It displays the output but does not move to the next line. System.out.print("Hello "); System.out.print("Java"); Output: Hello Java

Printing Variables We can also display variable values. int age = 20; System.out.println(age); Output: 20

We can combine text and variables using +. String name = "Ravi"; int age = 20; System.out.println("Name: " + name); System.out.println("Age: " + age); Output:

Name: Ravi Age: 20

Formatted Output Sometimes we want output in a specific format. For this, Java provides: String.format() Example String name = "Ravi"; int age = 20; String result = String.format("Name: %s, Age: %d", name, age); System.out.println(result); Output: Name: Ravi, Age: 20

  1. Control Statements Control structures in Java are used to dictate the flow of execution of the program based on certain conditions or repetitions. Java provides several control structures that can be categorized into three main types:
  1. Conditional (Decision-Making) Statements
  2. Looping (Iteration) Statements
  3. Jump Statements
  4. Conditional (Decision-Making) Statements The if Statement- The if statement in Java is used to execute a block of code only if a specified condition is true. Syntax: if (condition) { // code to be executed if condition is true } Example Program: public class IfExample { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("The number is positive."); }

// code if condition3 is true } else { // code if none of the above conditions are true} Example Program: public class IfElseIfExample { public static void main(String[] args) { int marks = 75; if (marks >= 90) { System.out.println("Grade: A"); } else if (marks >= 75) { System.out.println("Grade: B"); } else if (marks >= 60) { System.out.println("Grade: C"); } else { System.out.println("Grade: F"); } } } Output: Grade: B

  1. Looping (Iteration) Statements The while Loop - The while loop is used to repeat a block of code as long as the given condition is true. The condition is checked before each iteration. Syntax: while (condition) { // code to be executed } Example Program: public class WhileExample { public static void main(String[] args) { int i = 1; while (i <= 3) { System.out.println("i = " + i);

i++; } } } Output: i = 1 i = 2 i = 3

The do-while Loop - The do-while loop is similar to the while loop, but the code block executes at least once, because the condition is checked after the loop body. Syntax: do { // code to be executed } while (condition); Example Program: public class DoWhileExample { public static void main(String[] args) { int i = 1; do { System.out.println("i = " + i); i++; } while (i <= 3); } } Output: i = 1 i = 2 i = 3 The for Loop- The for loop is used when the number of iterations is known. It has three parts: initialization, condition, and increment/decrement. Syntax: for (initialization; condition; update) { // code to be executed }